Skip to content

Commit

Permalink
refactor(cdk): support noUncheckedIndexedAccess (#8620)
Browse files Browse the repository at this point in the history
  • Loading branch information
splincode authored Aug 27, 2024
1 parent c4c5e0b commit 4978a21
Show file tree
Hide file tree
Showing 27 changed files with 91 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ export const TUI_INPUT_CARD_GROUP_TEXTS = tuiCreateTokenFromFactory<
]),
),
map(([index, cardNumber, expiry, cvcTexts]) => ({
cardNumberText: cardNumber[index],
expiryText: expiry[index],
cvcText: cvcTexts[index],
cardNumberText: cardNumber[index] ?? '',
expiryText: expiry[index] ?? '',
cvcText: cvcTexts[index] ?? '',
})),
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
<ng-template #anotherTab>
<ng-container
[ngTemplateOutlet]="codeSection"
[ngTemplateOutletContext]="{$implicit: files?.[tabs[activeItemIndex]] || ''}"
[ngTemplateOutletContext]="{$implicit: files?.[tabs?.[activeItemIndex] || 0] || ''}"
/>
</ng-template>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export class TuiDocNavigation {
}

protected get itemsWithoutSections(): TuiDocRoutePages {
return this.items[this.items.length - 1];
return this.items[this.items.length - 1] ?? [];
}

protected $pages(pages: any): readonly TuiDocRoutePage[] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {catchError, distinctUntilChanged, EMPTY, map} from 'rxjs';
export class TuiStuck {
protected readonly stuck = toSignal(
inject(IntersectionObserverService).pipe(
map((entries) => entries[entries.length - 1].intersectionRatio < 1),
map((entries) => (entries[entries.length - 1]?.intersectionRatio ?? 0) < 1),
distinctUntilChanged(),
tuiWatch(inject(ChangeDetectorRef)),
catchError(() => EMPTY), // SSR
Expand Down
4 changes: 2 additions & 2 deletions projects/cdk/directives/pan/pan.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ export class TuiPanService extends Observable<readonly [number, number]> {
),
pairwise(),
map(([first, second]) => {
const deltaX = second.clientX - first.clientX;
const deltaY = second.clientY - first.clientY;
const deltaX = (second?.clientX ?? 0) - (first?.clientX ?? 0);
const deltaY = (second?.clientY ?? 0) - (first?.clientY ?? 0);

return [deltaX, deltaY] as [number, number];
}),
Expand Down
12 changes: 6 additions & 6 deletions projects/cdk/directives/swipe/swipe.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ export class TuiSwipeService extends Observable<TuiSwipeEvent> {
filter(
([first, second]) =>
!!first.touches.length &&
first.touches[0].identifier ===
second.changedTouches[0].identifier,
first.touches[0]?.identifier ===
second.changedTouches[0]?.identifier,
),
map(([start, end]) => {
const startX = start.touches[0].clientX;
const startY = start.touches[0].clientY;
const endX = end.changedTouches[0].clientX;
const endY = end.changedTouches[0].clientY;
const startX = start.touches[0]?.clientX ?? 0;
const startY = start.touches[0]?.clientY ?? 0;
const endX = end.changedTouches[0]?.clientX ?? 0;
const endY = end.changedTouches[0]?.clientY ?? 0;

const distanceX = startX - endX;
const distanceY = startY - endY;
Expand Down
8 changes: 4 additions & 4 deletions projects/cdk/directives/zoom/zoom.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ export class TuiZoomService extends Observable<TuiZoomEvent> {
),
map(({event, delta}) => {
const clientX =
(event.touches[0].clientX +
event.touches[1].clientX) /
((event.touches[0]?.clientX ?? 0) +
(event.touches[1]?.clientX ?? 0)) /
2;
const clientY =
(event.touches[0].clientY +
event.touches[1].clientY) /
((event.touches[0]?.clientY ?? 0) +
(event.touches[1]?.clientY ?? 0)) /
2;

return {clientX, clientY, delta, event};
Expand Down
12 changes: 10 additions & 2 deletions projects/cdk/schematics/ng-add/steps/add-taiga-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,20 @@ function addTuiEntitiesToStandalone({
bootstrapOptions = bootstrapFunction.addArgument('{providers}: []'),
] = bootstrapFunction.getArguments();

if (!rootComponentIdentifier) {
return;
}

const mainClass = getComponentFromIdentifier(rootComponentIdentifier);

const optionsObject = getOptionsObject(
bootstrapOptions as Identifier | ObjectLiteralExpression,
);

if (!optionsObject) {
return;
}

if (mainClass) {
addMainModuleToRootComponent({mainClass, options, context});
addRootTuiProvidersToBootstrapFn(optionsObject);
Expand Down Expand Up @@ -143,14 +151,14 @@ function getModules(extraModules?: ImportingModule[]): ImportingModule[] {

function getOptionsObject(
options: Identifier | ObjectLiteralExpression,
): ObjectLiteralExpression {
): ObjectLiteralExpression | null {
if (Node.isObjectLiteralExpression(options)) {
return options;
}

const definition = options.getDefinitionNodes()[0];

return definition.getChildrenOfKind(SyntaxKind.ObjectLiteralExpression)[0];
return definition?.getChildrenOfKind(SyntaxKind.ObjectLiteralExpression)[0] ?? null;
}

export function addTaigaModules(options: TuiSchema): Rule {
Expand Down
11 changes: 9 additions & 2 deletions projects/cdk/schematics/ng-add/steps/wrap-with-tui-root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,16 @@ function getAppTemplatePath(mainPath: string): string {

if (standaloneBootstrapFunction) {
const [componentIdentifier] = standaloneBootstrapFunction.getArguments();
const component = getComponentFromIdentifier(componentIdentifier);

return (component && getTemplatePathFromComponent(component)) || '';
if (componentIdentifier) {
const component = getComponentFromIdentifier(componentIdentifier);

if (component) {
return getTemplatePathFromComponent(component);
}
}

return '';
}

const mainModule = getMainModule(mainPath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ function migrateTuiMaskedMoneyValueIsEmpty(options: TuiSchema): void {
const [value] = parent.getArguments();

parent.replaceWithText(
`Number.isNaN(maskitoParseNumber(${value.getText()}, ','))`,
`Number.isNaN(maskitoParseNumber(${value?.getText()}, ','))`,
);
}
});
Expand Down Expand Up @@ -82,7 +82,7 @@ function migrateTuiMaskedNumberStringToNumber(options: TuiSchema): void {
const [value, decimalSeparator] = parent.getArguments();

parent.replaceWithText(
`maskitoParseNumber(${value.getText()}, ${decimalSeparator.getText()})`,
`maskitoParseNumber(${value?.getText()}, ${decimalSeparator?.getText()})`,
);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const OPTIONS_MIGRATIONS: Record<
const [, propertyValue] = property.getText().split(/\s?:\s?/);

property.replaceWithText(
propertyValue.match(/^['"`]never['"`]$/)
propertyValue?.match(/^['"`]never['"`]$/)
? 'precision: 0'
: property.getText().replace('decimal', 'decimalMode'),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function updateTuiMapper(options: TuiSchema): void {

const [inputType] = typeArguments;

inputType.replaceWithText(`[${inputType.getText()}, ...any]`);
inputType?.replaceWithText(`[${inputType.getText()}, ...any]`);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function updateTuiMatcher(options: TuiSchema): void {

const [inputType] = typeArguments;

inputType.replaceWithText(`[${inputType.getText()}, ...any]`);
inputType?.replaceWithText(`[${inputType.getText()}, ...any]`);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ export function migrateOverscroll({
);
});

addTodo(recorder, elements[0].sourceCodeLocation as ElementLocation, templateOffset);
const element = elements[0]?.sourceCodeLocation as ElementLocation | undefined;

if (element) {
addTodo(recorder, element, templateOffset);
}
}

function addTodo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ export function migratePreventDefault({
const event = preventDefaultAttr.value;

const preventDefaultStart =
sourceCodeLocation?.attrs?.[preventDefaultAttr.name].startOffset || 0;
sourceCodeLocation?.attrs?.[preventDefaultAttr.name]?.startOffset || 0;
const preventDefaultEnd =
sourceCodeLocation?.attrs?.[preventDefaultAttr.name].endOffset || 0;
sourceCodeLocation?.attrs?.[preventDefaultAttr.name]?.endOffset || 0;

recorder.insertLeft(
templateOffset + preventDefaultStart,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export function migrateProgressSegmented({
}

const max = maxAttr.value;
const insertTo = sourceCodeLocation?.attrs?.[maxAttr.name].endOffset || 0;
const insertTo = sourceCodeLocation?.attrs?.[maxAttr.name]?.endOffset || 0;

recorder.insertRight(insertTo + templateOffset, ` [segments]="${max}"`);
});
Expand Down
8 changes: 5 additions & 3 deletions projects/cdk/schematics/utils/add-unique-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ export function addUniqueImport(
moduleSpecifier,
});

if (existingDeclaration.length) {
const modules = existingDeclaration[0]
const imports = existingDeclaration?.[0];

if (imports) {
const modules = imports
.getNamedImports()
.map((namedImport) => namedImport.getText());

editImports(existingDeclaration[0], () => ({
editImports(imports, () => ({
namedImports: [...modules, namedImport],
isTypeOnly: false,
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function getComponentFromIdentifier(
})[0];

const rootComponentPath =
rootImportDeclaration.getModuleSpecifierSourceFile()?.getFilePath() || '';
rootImportDeclaration?.getModuleSpecifierSourceFile()?.getFilePath() || '';

return getNgComponents(rootComponentPath, {name: identifier.getText()})[0];
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ import type {TemplateResource} from '../../ng-update/interfaces/template-resourc
function decoratorToTemplateResource(decorator: Decorator): TemplateResource | null {
const [metadata] = decorator.getArguments() as ObjectLiteralExpression[];

const templateUrl = metadata.getProperty('templateUrl') as PropertyAssignment;
const template = metadata.getProperty('template') as PropertyAssignment;
const templateUrl = metadata?.getProperty('templateUrl') as
| PropertyAssignment
| undefined;
const template = metadata?.getProperty('template') as PropertyAssignment | undefined;
const componentPath = decorator.getSourceFile().getFilePath();

if (templateUrl) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ export function replaceInputProperty({
});

propertyValues.forEach(([startOffset, endOffset]) => {
recorder.remove(startOffset, endOffset - startOffset);
recorder.insertRight(startOffset, newValue);
recorder.remove(startOffset ?? 0, (endOffset ?? 0) - (startOffset ?? 0));
recorder.insertRight(startOffset ?? 0, newValue);
});

return true;
Expand Down Expand Up @@ -229,6 +229,6 @@ export function removeInputProperty({
].map(([start, end]) => [templateOffset + start, templateOffset + end]);

propertyOffsets.forEach(([start, end]) => {
recorder.remove(start, end - start);
recorder.remove(start ?? 0, (end ?? 0) - (start ?? 0));
});
}
4 changes: 2 additions & 2 deletions projects/cdk/utils/color/hex-to-rgba.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const getChunksFromString = (hex: string, chunkSize: number): RegExpMatchArray |
const convertHexUnitTo256 = (hexStr: string): number =>
parseInt(hexStr.repeat(2 / hexStr.length), 16);

const getAlphaFloat = (a: number, alpha?: number): number => {
const getAlphaFloat = (a?: number, alpha?: number): number => {
if (typeof a !== 'undefined') {
return Number((a / 255).toFixed(2));
}
Expand Down Expand Up @@ -36,7 +36,7 @@ export function tuiParseHex(

const chunkSize = Math.floor((hex.length - 1) / 3);
const hexArr = getChunksFromString(hex.slice(1), chunkSize);
const [r, g, b, a] = hexArr?.map(convertHexUnitTo256) ?? [];
const [r = NaN, g = NaN, b = NaN, a] = hexArr?.map(convertHexUnitTo256) ?? [];
const floatAlpha = getAlphaFloat(a, alpha);

return [r, g, b, floatAlpha];
Expand Down
4 changes: 2 additions & 2 deletions projects/cdk/utils/color/parse-gradient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ export function tuiParseGradient(input: string): TuiParsedGradient {

while (matchColorStop !== null) {
stops = stops.concat({
color: matchColorStop[1],
position: getPosition(matchColorStop[2], stops.length),
color: matchColorStop[1] || '',
position: getPosition(matchColorStop[2] || '', stops.length),
});

matchColorStop = stopsRegexp.exec(stopsString);
Expand Down
16 changes: 8 additions & 8 deletions projects/cdk/utils/color/rgba-to-hex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ export function tuiRgbaToHex(color: string): string {
throw new Error('Invalid RGBa');
}

const rgb: number[] =
(color
.replaceAll(/\s/g, '')
.match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i) as unknown as number[]) ??
[];
const rgb =
color.replaceAll(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i) ??
null;

let alpha: number | string = (rgb?.[4] ?? '').toString().trim();

let hex = rgb
? (rgb[1] | (1 << 8)).toString(16).slice(1) +
(rgb[2] | (1 << 8)).toString(16).slice(1) +
(rgb[3] | (1 << 8)).toString(16).slice(1)
? ((parseInt(rgb?.[1] ?? '', 10) || 0) | (1 << 8)).toString(16).slice(1) +
((parseInt(rgb?.[2] ?? '', 10) || 0) | (1 << 8)).toString(16).slice(1) +
((parseInt(rgb?.[3] ?? '', 10) || 0) | (1 << 8)).toString(16).slice(1)
: color;

alpha = alpha !== '' ? alpha : 0o1;
Expand Down
2 changes: 1 addition & 1 deletion projects/cdk/utils/focus/move-focus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function tuiMoveFocus(
currentIndex += step;

while (currentIndex >= 0 && currentIndex < elements.length) {
elements[currentIndex].focus();
elements[currentIndex]?.focus();

if (tuiIsNativeFocused(elements[currentIndex])) {
return;
Expand Down
4 changes: 2 additions & 2 deletions projects/cdk/utils/miscellaneous/distance-between-touches.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export function tuiDistanceBetweenTouches({touches}: TouchEvent): number {
return Math.hypot(
touches[0].clientX - touches[1].clientX,
touches[0].clientY - touches[1].clientY,
(touches[0]?.clientX ?? 0) - (touches[1]?.clientX ?? 0),
(touches[0]?.clientY ?? 0) - (touches[1]?.clientY ?? 0),
);
}
8 changes: 5 additions & 3 deletions projects/layout/components/search/search-filters.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,11 @@ export class TuiSearchFiltersComponent implements AfterContentInit {

protected readonly overflown = toSignal(
inject(ResizeObserverService, {self: true}).pipe(
map(([{contentRect}]) =>
Math.floor((contentRect.width - this.more) / WIDTH / this.unit),
),
map((entry) => {
const width = entry[0]?.contentRect.width ?? 0;

return Math.floor((width - this.more) / WIDTH / this.unit);
}),
distinctUntilChanged(),
tuiZonefull(inject(NgZone)),
),
Expand Down
10 changes: 8 additions & 2 deletions projects/testing/core/spin-button.harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,16 @@ export class TuiSpinButtonHarness extends TuiComponentHarness {
public static hostSelector = 'tui-spin-button';

public async isLeftDisabled(): Promise<boolean> {
return (await this.locatorForAll(TuiButtonHarness)())[0].hasClass('t-hidden');
return (
(await this.locatorForAll(TuiButtonHarness)())[0]?.hasClass('t-hidden') ??
false
);
}

public async isRightDisabled(): Promise<boolean> {
return (await this.locatorForAll(TuiButtonHarness)())[1].hasClass('t-hidden');
return (
(await this.locatorForAll(TuiButtonHarness)())[1]?.hasClass('t-hidden') ??
false
);
}
}

0 comments on commit 4978a21

Please sign in to comment.