Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/guides/migration.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -1183,6 +1183,23 @@ Two fixes with nothing to migrate: the trigger subscribed to the global `ScrollD

Reported by `popover-leave-delay`.

#### Progress spinner

`size` was the last accessor input on the spinner, and the reason the automated signal migration skipped it: its setter stored the size and computed the SVG circle radius in one go. The radius is a `computed` now and `size` is a plain `input()`. `id`, `value` and `mode` became signal inputs back in 20.0.0 and no migration has covered them until now, so this one rewrites their reads as well. A read left un-called is silent rather than loud: `spinner.value > 50` is always false and `{{ spinner.value }}` prints the function source.

| Pattern | Manual migration |
| ------------------------------------ | ----------------------------------------------------------------------- |
| `.size` / `.id` / `.value` / `.mode` | Read as calls — rewritten for you |
| `.size = …` and the other three | Bind them in the template — the inputs are read-only |
| `.percentage` / `.dashOffsetPercent` | Now `protected`; derive what you need from the `value` you already bind |
| `.svgCircleRadius` | Now `protected`; it is the SVG geometry, not a contract |

**`size` no longer accepts an arbitrary string.** It is typed `ProgressSpinnerSize` (`'compact' | 'big'`), resolving a TODO that predates the review. Any other value used to fall through to the compact radius silently; it is a template type error now.

**`value` is a `numberAttribute` input with a `0` fallback.** `value="40"` used to pass the string `"40"`, which the percentage arithmetic coerced by accident; it is a number now. Anything that is not a number reads as `0` rather than reaching the `stroke-dashoffset` percentage as `NaN`, which is not a length at all.

Handled by `progress-spinner-signals`: the reads are rewritten, the rest is reported.

#### Search expandable

Step 4 already renames the `kbq-filter-search` element to `kbq-search-expandable`. That rewrite only ever touched the tag, so the inputs of the removed `KbqFilterBarSearch` survived as attributes the new component does not have — silently, because an unknown attribute on a component is not an error. `v20-upgrade` renames them too now:
Expand Down
17 changes: 17 additions & 0 deletions docs/guides/migration.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -1187,6 +1187,23 @@ bootstrapApplication(App, {

Сообщает `popover-leave-delay`.

#### Progress spinner

`size` был последним входом на геттере и сеттере у спиннера — и именно поэтому автоматическая миграция на сигналы его пропустила: сеттер одновременно сохранял размер и вычислял радиус SVG-круга. Теперь радиус — это `computed`, а `size` — обычный `input()`. `id`, `value` и `mode` стали сигнальными входами ещё в 20.0.0, и до сих пор их не покрывала ни одна миграция, поэтому здесь переписываются и их чтения. Чтение без вызова проявляет себя молча: `spinner.value > 50` всегда ложно, а `{{ spinner.value }}` печатает исходник функции.

| Что было | Как мигрировать вручную |
| ------------------------------------ | ------------------------------------------------------------------------------ |
| `.size` / `.id` / `.value` / `.mode` | Читать как вызовы — переписывается за вас |
| `.size = …` и остальные три | Привязывать в шаблоне — входы доступны только на чтение |
| `.percentage` / `.dashOffsetPercent` | Стали `protected`; вычисляйте нужное из `value`, который вы и так привязываете |
| `.svgCircleRadius` | Стал `protected`; это геометрия SVG, а не контракт |

**`size` больше не принимает произвольную строку.** Он типизирован как `ProgressSpinnerSize` (`'compact' | 'big'`) — это закрывает TODO, который появился до ревью. Любое другое значение раньше молча приводило к компактному радиусу, а теперь это ошибка типизации шаблона.

**`value` стал `numberAttribute`-входом с запасным значением `0`.** `value="40"` раньше передавал строку `"40"`, которую арифметика процентов приводила к числу случайно; теперь это число. Всё, что числом не является, читается как `0` и не доходит до процентного `stroke-dashoffset` в виде `NaN`, который вообще не является длиной.

Закрывается схематиком `progress-spinner-signals`: чтения переписываются, остальное сообщается в отчёте.

#### Search expandable

Шаг 4 уже переименовывает элемент `kbq-filter-search` в `kbq-search-expandable`. Но та замена трогала только тег, поэтому входы удалённого `KbqFilterBarSearch` оставались в разметке атрибутами, которых у нового компонента нет, — и молча, потому что неизвестный атрибут на компоненте не является ошибкой. Теперь `v20-upgrade` переименовывает и их:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
ViewEncapsulation
} from '@angular/core';
import { KbqDefaultSizes } from '@koobiq/components/core';
import { KbqProgressSpinner } from '@koobiq/components/progress-spinner';
import { KbqProgressSpinner, ProgressSpinnerSize } from '@koobiq/components/progress-spinner';

const kbqLoaderOverlayParent = 'kbq-loader-overlay_parent';

Expand Down Expand Up @@ -116,7 +116,7 @@ export class KbqLoaderOverlay implements OnInit, OnDestroy {
return !(!!this.text || this.isExternalText || !!this.caption || this.isExternalCaption);
}

get spinnerSize(): string {
get spinnerSize(): ProgressSpinnerSize {
Comment thread
artembelik marked this conversation as resolved.
return this.size() === 'compact' ? 'compact' : 'big';
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
cy="50%"
stroke-linecap="round"
class="kbq-progress-spinner__circle"
[attr.r]="svgCircleRadius"
[style]="{ 'stroke-dashoffset': mode() === 'determinate' ? dashOffsetPercent : null }"
[attr.r]="svgCircleRadius()"
[style]="{ 'stroke-dashoffset': mode() === 'determinate' ? dashOffsetPercent() : null }"
/>
</svg>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,132 +1,181 @@
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Component, signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { KbqComponentColors, ThemePalette } from '@koobiq/components/core';
import { KbqProgressSpinnerModule } from './index';
import { KbqProgressSpinner, KbqProgressSpinnerModule, ProgressSpinnerMode, ProgressSpinnerSize } from './index';

const percentPairs = [
[40, 0.4],
[-50, 0],
[140, 1]
/** `MAX_DASH_ARRAY - percentage * MAX_DASH_ARRAY`, with `MAX_DASH_ARRAY = 295`. */
const dashOffsetPairs: [value: number, dashOffset: string][] = [
[40, '177%'],
[-50, '295%'],
[140, '0%']
];

describe('KbqProgressSpinner', () => {
let fixture: ComponentFixture<TestApp>;
let testComponent: TestApp;

/** The spinner driven by the test component's signals. */
let host: HTMLElement;
let circle: SVGCircleElement;

/** A spinner with no bindings at all, to assert the defaults. */
let defaultHost: HTMLElement;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [KbqProgressSpinnerModule, TestApp]
}).compileComponents();
TestBed.configureTestingModule({ imports: [KbqProgressSpinnerModule, TestApp] });

fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();

testComponent = fixture.componentInstance;
host = fixture.debugElement.query(By.css('.first')).nativeElement;
circle = host.querySelector('.kbq-progress-spinner__circle')!;
defaultHost = fixture.debugElement.query(By.css('.default')).nativeElement;
});

it('should apply class based on color attribute', () => {
const fixture = TestBed.createComponent(TestApp);
const testComponent = fixture.debugElement.componentInstance;
const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.first'));

Object.keys(ThemePalette).forEach((key) => {
if (ThemePalette[key]) {
testComponent.color = ThemePalette[key];
fixture.detectChanges();

expect(progressSpinnerDebugElement.nativeElement.classList.contains(`kbq-${ThemePalette[key]}`)).toBe(
true
);
}
});
});
if (!ThemePalette[key]) return;

it('should has default Theme color', () => {
const fixture = TestBed.createComponent(TestApp);
const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.default'));
testComponent.color.set(ThemePalette[key]);
fixture.detectChanges();

expect(progressSpinnerDebugElement.nativeElement.classList.contains(`kbq-${KbqComponentColors.Theme}`)).toBe(
true
);
expect(host.classList.contains(`kbq-${ThemePalette[key]}`)).toBe(true);
});
});

it('should return percentage', () => {
const fixture = TestBed.createComponent(TestApp);

const testComponent = fixture.debugElement.componentInstance;
const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.first'));
it(`should have the ${KbqComponentColors.Theme} color by default`, () => {
expect(defaultHost.classList.contains(`kbq-${KbqComponentColors.Theme}`)).toBe(true);
});

percentPairs.forEach(([percent, expected]) => {
testComponent.value = percent;
it('should clamp the value into a stroke offset', () => {
dashOffsetPairs.forEach(([value, dashOffset]) => {
testComponent.value.set(value);
fixture.detectChanges();
expect(progressSpinnerDebugElement.componentInstance.percentage).toBe(expected);

expect(circle.style.strokeDashoffset).toBe(dashOffset);
});
});

it('should return 0 percentage by default', () => {
const fixture = TestBed.createComponent(TestApp);
const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.default'));
it('should render an empty circle by default', () => {
const defaultCircle = defaultHost.querySelector<SVGCircleElement>('.kbq-progress-spinner__circle')!;

expect(progressSpinnerDebugElement.componentInstance.percentage).toBe(0);
expect(defaultCircle.style.strokeDashoffset).toBe('295%');
});

it('should show determinate circle', () => {
const fixture = TestBed.createComponent(TestApp);
const testComponent = fixture.debugElement.componentInstance;
const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.first'));

testComponent.mode = 'determinate';
it('should not offset the stroke in indeterminate mode', () => {
testComponent.value.set(40);
testComponent.mode.set('indeterminate');
fixture.detectChanges();

expect(progressSpinnerDebugElement.query(By.css('.kbq-progress-spinner__circle_indeterminate'))).toBeNull();
expect(progressSpinnerDebugElement.query(By.css('.kbq-progress-spinner__circle'))).not.toBeNull();
expect(circle.style.strokeDashoffset).toBe('');
});

it('should show indeterminate circle', () => {
const fixture = TestBed.createComponent(TestApp);
const testComponent = fixture.debugElement.componentInstance;
it('should mark the host as indeterminate', () => {
expect(host.classList.contains('kbq-progress-spinner_indeterminate')).toBe(false);

testComponent.mode = 'indeterminate';
testComponent.mode.set('indeterminate');
fixture.detectChanges();

const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.kbq-progress-spinner_indeterminate'));
expect(host.classList.contains('kbq-progress-spinner_indeterminate')).toBe(true);
});

expect(progressSpinnerDebugElement).not.toBeNull();
it('should be determinate by default', () => {
expect(defaultHost.classList.contains('kbq-progress-spinner_indeterminate')).toBe(false);
});

it('should show determinate circle by default', () => {
const fixture = TestBed.createComponent(TestApp);
const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.first'));
it('should grow the circle for the big size', () => {
expect(circle.getAttribute('r')).toBe('42.5%');
expect(host.classList.contains('kbq-progress-spinner_big')).toBe(false);

testComponent.size.set('big');
fixture.detectChanges();

expect(progressSpinnerDebugElement.query(By.css('.kbq-progress-spinner_indeterminate'))).toBeNull();
expect(progressSpinnerDebugElement.query(By.css('.kbq-progress-spinner__circle'))).not.toBeNull();
expect(circle.getAttribute('r')).toBe('47%');
expect(host.classList.contains('kbq-progress-spinner_big')).toBe(true);
});

it('should set id attribute', () => {
const fixture = TestBed.createComponent(TestApp);
const testComponent = fixture.debugElement.componentInstance;
const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.first'));
testComponent.id.set('foo');
fixture.detectChanges();

expect(host.getAttribute('id')).toBe('foo');
});

it('should auto generate a unique id', () => {
const generated = fixture.debugElement
.queryAll(By.css('.default'))
.map(({ nativeElement }) => nativeElement.getAttribute('id'));

expect(generated).toHaveLength(2);
generated.forEach((id) => expect(id).toMatch(/^kbq-progress-spinner-/));
expect(new Set(generated).size).toBe(generated.length);
});

it('should coerce a non-numeric value to 0 rather than NaN', () => {
const spinner = fixture.debugElement.query(By.css('.first')).componentInstance as KbqProgressSpinner;

testComponent.id = 'foo';
testComponent.value.set(40);
fixture.detectChanges();

expect(progressSpinnerDebugElement.nativeElement.getAttribute('id')).toBe('foo');
expect(spinner.value()).toBe(40);
expect(circle.style.strokeDashoffset).toBe('177%');

for (const nonNumeric of [null, undefined, '', 'abc', '40px', {}]) {
testComponent.value.set(nonNumeric as unknown as number);
fixture.detectChanges();

// The input value, not the style: jsdom's cssstyle accepts `NaN%` where a real browser rejects
// the declaration and keeps the previous one, so a style assertion would encode the wrong thing.
expect(spinner.value()).toBe(0);
expect(circle.style.strokeDashoffset).toBe('295%');
}
});

it('should auto generate id', () => {
const fixture = TestBed.createComponent(TestApp);
const progressSpinnerDebugElement = fixture.debugElement.query(By.css('.default'));
it('should read a numeric value from a static attribute', () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({ imports: [KbqProgressSpinnerModule, StaticValueTestApp] });

const staticFixture = TestBed.createComponent(StaticValueTestApp);

expect(progressSpinnerDebugElement.nativeElement.getAttribute('id')).toBeDefined();
staticFixture.detectChanges();

const staticCircle = staticFixture.nativeElement.querySelector('.kbq-progress-spinner__circle');

expect(staticCircle.style.strokeDashoffset).toBe('177%');
});
});

@Component({
selector: 'test-app',
imports: [KbqProgressSpinnerModule],
template: `
<kbq-progress-spinner class="first" [id]="id" [color]="color" [value]="value" [mode]="mode" />
<kbq-progress-spinner
class="first"
[id]="id()"
[color]="color()"
[value]="value()"
[mode]="mode()"
[size]="size()"
/>
<kbq-progress-spinner class="default" />
<kbq-progress-spinner class="default" />
`
})
class TestApp {
color: ThemePalette;
value: number = 0;
mode: string;
id: string;
readonly color = signal<ThemePalette>(ThemePalette.Primary);
readonly value = signal(0);
readonly mode = signal<ProgressSpinnerMode>('determinate');
readonly size = signal<ProgressSpinnerSize>('compact');
readonly id = signal('test-spinner');
}

@Component({
selector: 'static-value-test-app',
imports: [KbqProgressSpinnerModule],
template: `
<kbq-progress-spinner value="40" />
`
})
class StaticValueTestApp {}
Loading