Fix searching/filtering bugs #235

- Fix a bug (introduced in 1b9be8fe) preventing the tree view from being
  visible during a search.
- Fix a minor bug where the scripts view does not render based on the
  initial filter.
- Add Vue component tests for `TheScriptView` to prevent regressions.
- Refactor `isSearching` in `TheScriptView` to simplify its logic.
This commit is contained in:
undergroundwires
2023-08-25 00:32:01 +02:00
parent 75c9b51bf2
commit 62f8bfac2f
11 changed files with 613 additions and 31 deletions

View File

@@ -1,6 +1,7 @@
import { IEventSubscription } from './IEventSource'; import { IEventSubscription } from './IEventSource';
import { IEventSubscriptionCollection } from './IEventSubscriptionCollection';
export class EventSubscriptionCollection { export class EventSubscriptionCollection implements IEventSubscriptionCollection {
private readonly subscriptions = new Array<IEventSubscription>(); private readonly subscriptions = new Array<IEventSubscription>();
public register(...subscriptions: IEventSubscription[]) { public register(...subscriptions: IEventSubscription[]) {

View File

@@ -0,0 +1,7 @@
import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
export interface IEventSubscriptionCollection {
register(...subscriptions: IEventSubscription[]);
unsubscribeAll();
}

View File

@@ -1,19 +1,24 @@
<template> <template>
<div class="scripts"> <div class="scripts">
<div v-if="!isSearching"> <div v-if="!isSearching">
<CardList v-if="currentView === ViewType.Cards" /> <template v-if="currentView === ViewType.Cards">
<div class="tree" v-else-if="currentView === ViewType.Tree"> <CardList />
<ScriptsTree /> </template>
</div> <template v-else-if="currentView === ViewType.Tree">
<div class="tree">
<ScriptsTree />
</div>
</template>
</div> </div>
<div v-else> <!-- Searching --> <div v-else> <!-- Searching -->
<div class="search"> <div class="search">
<div class="search__query"> <div class="search__query">
<div>Searching for "{{ trimmedSearchQuery }}"</div> <div>Searching for "{{ trimmedSearchQuery }}"</div>
<div class="search__query__close-button"> <div
<font-awesome-icon class="search__query__close-button"
:icon="['fas', 'times']" v-on:click="clearSearchQuery()"
v-on:click="clearSearchQuery()" /> >
<font-awesome-icon :icon="['fas', 'times']" />
</div> </div>
</div> </div>
<div v-if="!searchHasMatches" class="search-no-matches"> <div v-if="!searchHasMatches" class="search-no-matches">
@@ -41,6 +46,7 @@ import ScriptsTree from '@/presentation/components/Scripts/View/ScriptsTree/Scri
import CardList from '@/presentation/components/Scripts/View/Cards/CardList.vue'; import CardList from '@/presentation/components/Scripts/View/Cards/CardList.vue';
import { ViewType } from '@/presentation/components/Scripts/Menu/View/ViewType'; import { ViewType } from '@/presentation/components/Scripts/Menu/View/ViewType';
import { IReadOnlyUserFilter } from '@/application/Context/State/Filter/IUserFilter'; import { IReadOnlyUserFilter } from '@/application/Context/State/Filter/IUserFilter';
import { IFilterResult } from '@/application/Context/State/Filter/IFilterResult';
export default defineComponent({ export default defineComponent({
components: { components: {
@@ -58,8 +64,8 @@ export default defineComponent({
const { info } = inject(useApplicationKey); const { info } = inject(useApplicationKey);
const repositoryUrl = computed<string>(() => info.repositoryWebUrl); const repositoryUrl = computed<string>(() => info.repositoryWebUrl);
const searchQuery = ref<string>(); const searchQuery = ref<string | undefined>();
const isSearching = ref(false); const isSearching = computed(() => Boolean(searchQuery.value));
const searchHasMatches = ref(false); const searchHasMatches = ref(false);
const trimmedSearchQuery = computed(() => { const trimmedSearchQuery = computed(() => {
const query = searchQuery.value; const query = searchQuery.value;
@@ -72,8 +78,9 @@ export default defineComponent({
onStateChange((newState) => { onStateChange((newState) => {
events.unsubscribeAll(); events.unsubscribeAll();
updateFromInitialFilter(newState.filter.currentFilter);
subscribeToFilterChanges(newState.filter); subscribeToFilterChanges(newState.filter);
}); }, { immediate: true });
function clearSearchQuery() { function clearSearchQuery() {
modifyCurrentState((state) => { modifyCurrentState((state) => {
@@ -82,17 +89,21 @@ export default defineComponent({
}); });
} }
function updateFromInitialFilter(filter?: IFilterResult) {
searchQuery.value = filter?.query;
searchHasMatches.value = filter?.hasAnyMatches();
}
function subscribeToFilterChanges(filter: IReadOnlyUserFilter) { function subscribeToFilterChanges(filter: IReadOnlyUserFilter) {
events.register( events.register(
filter.filterChanged.on((event) => { filter.filterChanged.on((event) => {
event.visit({ event.visit({
onApply: (newFilter) => { onApply: (newFilter) => {
searchQuery.value = newFilter.query; searchQuery.value = newFilter.query;
isSearching.value = true;
searchHasMatches.value = newFilter.hasAnyMatches(); searchHasMatches.value = newFilter.hasAnyMatches();
}, },
onClear: () => { onClear: () => {
isSearching.value = false; searchQuery.value = undefined;
}, },
}); });
}), }),

View File

@@ -2,6 +2,7 @@ import { ref, computed, readonly } from 'vue';
import { IApplicationContext, IReadOnlyApplicationContext } from '@/application/Context/IApplicationContext'; import { IApplicationContext, IReadOnlyApplicationContext } from '@/application/Context/IApplicationContext';
import { ICategoryCollectionState, IReadOnlyCategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState'; import { ICategoryCollectionState, IReadOnlyCategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState';
import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection'; import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscriptionCollection';
import { IEventSubscriptionCollection } from '@/infrastructure/Events/IEventSubscriptionCollection';
export function useCollectionState(context: IApplicationContext) { export function useCollectionState(context: IApplicationContext) {
if (!context) { if (!context) {
@@ -18,13 +19,6 @@ export function useCollectionState(context: IApplicationContext) {
}), }),
); );
type NewStateEventHandler = (
newState: IReadOnlyCategoryCollectionState,
oldState: IReadOnlyCategoryCollectionState | undefined,
) => void;
interface IStateCallbackSettings {
readonly immediate: boolean;
}
const defaultSettings: IStateCallbackSettings = { const defaultSettings: IStateCallbackSettings = {
immediate: false, immediate: false,
}; };
@@ -49,9 +43,6 @@ export function useCollectionState(context: IApplicationContext) {
} }
} }
type StateModifier = (
state: ICategoryCollectionState,
) => void;
function modifyCurrentState(mutator: StateModifier) { function modifyCurrentState(mutator: StateModifier) {
if (!mutator) { if (!mutator) {
throw new Error('missing state mutator'); throw new Error('missing state mutator');
@@ -59,9 +50,6 @@ export function useCollectionState(context: IApplicationContext) {
mutator(context.state); mutator(context.state);
} }
type ContextModifier = (
state: IApplicationContext,
) => void;
function modifyCurrentContext(mutator: ContextModifier) { function modifyCurrentContext(mutator: ContextModifier) {
if (!mutator) { if (!mutator) {
throw new Error('missing context mutator'); throw new Error('missing context mutator');
@@ -75,6 +63,23 @@ export function useCollectionState(context: IApplicationContext) {
onStateChange, onStateChange,
currentContext: context as IReadOnlyApplicationContext, currentContext: context as IReadOnlyApplicationContext,
currentState: readonly(computed<IReadOnlyCategoryCollectionState>(() => currentState.value)), currentState: readonly(computed<IReadOnlyCategoryCollectionState>(() => currentState.value)),
events, events: events as IEventSubscriptionCollection,
}; };
} }
export type NewStateEventHandler = (
newState: IReadOnlyCategoryCollectionState,
oldState: IReadOnlyCategoryCollectionState | undefined,
) => void;
export interface IStateCallbackSettings {
readonly immediate: boolean;
}
export type StateModifier = (
state: ICategoryCollectionState,
) => void;
export type ContextModifier = (
state: IApplicationContext,
) => void;

View File

@@ -0,0 +1,416 @@
import { describe, it, expect } from 'vitest';
import { Wrapper, shallowMount } from '@vue/test-utils';
import TheScriptsView from '@/presentation/components/Scripts/View/TheScriptsView.vue';
import ScriptsTree from '@/presentation/components/Scripts/View/ScriptsTree/ScriptsTree.vue';
import CardList from '@/presentation/components/Scripts/View/Cards/CardList.vue';
import { ViewType } from '@/presentation/components/Scripts/Menu/View/ViewType';
import { useCollectionState } from '@/presentation/components/Shared/Hooks/UseCollectionState';
import { UseCollectionStateStub } from '@tests/unit/shared/Stubs/UseCollectionStateStub';
import { useApplicationKey, useCollectionStateKey } from '@/presentation/injectionSymbols';
import { UseApplicationStub } from '@tests/unit/shared/Stubs/UseApplicationStub';
import { UserFilterMethod, UserFilterStub } from '@tests/unit/shared/Stubs/UserFilterStub';
import { FilterResultStub } from '@tests/unit/shared/Stubs/FilterResultStub';
import { FilterChange } from '@/application/Context/State/Filter/Event/FilterChange';
import { IFilterResult } from '@/application/Context/State/Filter/IFilterResult';
import { IFilterChangeDetails } from '@/application/Context/State/Filter/Event/IFilterChangeDetails';
const DOM_SELECTOR_NO_MATCHES = '.search-no-matches';
const DOM_SELECTOR_CLOSE_BUTTON = '.search__query__close-button';
describe('TheScriptsView.vue', () => {
describe('view types', () => {
describe('initially', () => {
interface IInitialViewTypeTestCase {
readonly initialView: ViewType;
readonly expectedComponent: unknown;
readonly absentComponents: readonly unknown[];
}
const testCases: readonly IInitialViewTypeTestCase[] = [
{
initialView: ViewType.Tree,
expectedComponent: ScriptsTree,
absentComponents: [CardList],
},
{
initialView: ViewType.Cards,
expectedComponent: CardList,
absentComponents: [ScriptsTree],
},
];
testCases.forEach(({ initialView, expectedComponent, absentComponents }) => {
it(`given initial view, renders only ${ViewType[initialView]}`, () => {
// act
const wrapper = mountComponent({
viewType: initialView,
});
// assert
expect(wrapper.findComponent(expectedComponent).exists()).to.equal(true);
expectComponentsToNotExist(wrapper, absentComponents);
});
});
});
describe('toggle view type', () => {
interface IToggleViewTypeTestCase {
readonly originalView: ViewType;
readonly newView: ViewType;
readonly absentComponents: readonly unknown[];
readonly expectedComponent: unknown;
}
const toggleTestCases: IToggleViewTypeTestCase[] = [
{
originalView: ViewType.Tree,
newView: ViewType.Cards,
absentComponents: [ScriptsTree],
expectedComponent: CardList,
},
{
originalView: ViewType.Cards,
newView: ViewType.Tree,
absentComponents: [CardList],
expectedComponent: ScriptsTree,
},
];
toggleTestCases.forEach(({
originalView, newView, absentComponents, expectedComponent,
}) => {
it(`toggles from ${ViewType[originalView]} to ${ViewType[newView]}`, async () => {
// arrange
// act
const wrapper = mountComponent({
viewType: originalView,
});
await wrapper.setProps({ currentView: newView });
// assert
expect(wrapper.findComponent(expectedComponent).exists()).to.equal(true);
expectComponentsToNotExist(wrapper, absentComponents);
});
});
});
});
describe('switching views', () => {
interface ISwitchingViewTestCase {
readonly name: string;
readonly initialView: ViewType;
readonly changeEvents: readonly IFilterChangeDetails[];
readonly componentsToDisappear: readonly unknown[];
readonly expectedComponent: unknown;
readonly setupFilter?: (filter: UserFilterStub) => UserFilterStub;
}
const testCases: readonly ISwitchingViewTestCase[] = [
{
name: 'tree on initial search with card view',
initialView: ViewType.Cards,
setupFilter: (filter: UserFilterStub) => filter
.withCurrentFilterResult(
new FilterResultStub().withQueryAndSomeMatches(),
),
changeEvents: [],
expectedComponent: ScriptsTree,
componentsToDisappear: [CardList],
},
{
name: 'restore card after initial search',
initialView: ViewType.Cards,
setupFilter: (filter: UserFilterStub) => filter
.withCurrentFilterResult(
new FilterResultStub().withQueryAndSomeMatches(),
),
changeEvents: [
FilterChange.forClear(),
],
expectedComponent: CardList,
componentsToDisappear: [ScriptsTree],
},
{
name: 'tree on search',
initialView: ViewType.Cards,
changeEvents: [
FilterChange.forApply(
new FilterResultStub().withQueryAndSomeMatches(),
),
],
expectedComponent: ScriptsTree,
componentsToDisappear: [CardList],
},
{
name: 'return to card after search',
initialView: ViewType.Cards,
changeEvents: [
FilterChange.forApply(
new FilterResultStub().withQueryAndSomeMatches(),
),
FilterChange.forClear(),
],
expectedComponent: CardList,
componentsToDisappear: [ScriptsTree],
},
{
name: 'return to tree after search',
initialView: ViewType.Tree,
changeEvents: [
FilterChange.forApply(
new FilterResultStub().withQueryAndSomeMatches(),
),
FilterChange.forClear(),
],
expectedComponent: ScriptsTree,
componentsToDisappear: [CardList],
},
];
testCases.forEach(({
name, initialView, changeEvents, expectedComponent: componentToAppear,
componentsToDisappear, setupFilter,
}) => {
it(name, async () => {
// arrange
let filterStub = new UserFilterStub();
if (setupFilter) {
filterStub = setupFilter(filterStub);
}
const stateStub = new UseCollectionStateStub()
.withFilter(filterStub);
const wrapper = mountComponent({
useCollectionState: stateStub.get(),
viewType: initialView,
});
// act
for (const changeEvent of changeEvents) {
filterStub.notifyFilterChange(changeEvent);
// eslint-disable-next-line no-await-in-loop
await wrapper.vm.$nextTick();
}
// assert
expect(wrapper.findComponent(componentToAppear).exists()).to.equal(true);
expectComponentsToNotExist(wrapper, componentsToDisappear);
});
});
});
describe('close button', () => {
describe('visibility', () => {
describe('does not show close button when not searching', () => {
it('not searching initially', () => {
// arrange
const filterStub = new UserFilterStub()
.withNoCurrentFilter();
const stateStub = new UseCollectionStateStub()
.withFilter(filterStub);
// act
const wrapper = mountComponent({
useCollectionState: stateStub.get(),
});
// assert
const closeButton = wrapper.find(DOM_SELECTOR_CLOSE_BUTTON);
expect(closeButton.exists()).to.equal(false);
});
it('stop searching', async () => {
// arrange
const filterStub = new UserFilterStub();
const stateStub = new UseCollectionStateStub().withFilter(filterStub);
const wrapper = mountComponent({
useCollectionState: stateStub.get(),
});
// act
filterStub.notifyFilterChange(FilterChange.forApply(
new FilterResultStub().withQueryAndSomeMatches(),
));
await wrapper.vm.$nextTick();
filterStub.notifyFilterChange(FilterChange.forClear());
await wrapper.vm.$nextTick();
// assert
const closeButton = wrapper.find(DOM_SELECTOR_CLOSE_BUTTON);
expect(closeButton.exists()).to.equal(false);
});
});
describe('shows close button when searching', () => {
it('searching initially', () => {
// arrange
const filterStub = new UserFilterStub()
.withCurrentFilterResult(
new FilterResultStub().withQueryAndSomeMatches(),
);
const stateStub = new UseCollectionStateStub()
.withFilter(filterStub);
// act
const wrapper = mountComponent({
useCollectionState: stateStub.get(),
});
// assert
const closeButton = wrapper.find(DOM_SELECTOR_CLOSE_BUTTON);
expect(closeButton.exists()).to.equal(true);
});
it('start searching', async () => {
// arrange
const filterStub = new UserFilterStub()
.withNoCurrentFilter();
const stateStub = new UseCollectionStateStub().withFilter(filterStub);
const wrapper = mountComponent({
useCollectionState: stateStub.get(),
});
// act
filterStub.notifyFilterChange(FilterChange.forApply(
new FilterResultStub().withQueryAndSomeMatches(),
));
await wrapper.vm.$nextTick();
// assert
const closeButton = wrapper.find(DOM_SELECTOR_CLOSE_BUTTON);
expect(closeButton.exists()).to.equal(true);
});
});
});
it('clears search query on close button click', async () => {
// arrange
const filterStub = new UserFilterStub();
const stateStub = new UseCollectionStateStub().withFilter(filterStub);
const wrapper = mountComponent({
useCollectionState: stateStub.get(),
});
filterStub.notifyFilterChange(FilterChange.forApply(
new FilterResultStub().withQueryAndSomeMatches(),
));
await wrapper.vm.$nextTick();
filterStub.callHistory.length = 0;
// act
const closeButton = wrapper.find(DOM_SELECTOR_CLOSE_BUTTON);
await closeButton.trigger('click');
// assert
expect(filterStub.callHistory).to.have.lengthOf(1);
expect(filterStub.callHistory).to.include(UserFilterMethod.ClearFilter);
});
});
describe('no matches text', () => {
interface INoMatchesTextTestCase {
readonly name: string;
readonly filter: IFilterResult;
readonly shouldNoMatchesExist: boolean;
}
const commonTestCases: readonly INoMatchesTextTestCase[] = [
{
name: 'shows text given no matches',
filter: new FilterResultStub()
.withQuery('non-empty query')
.withEmptyMatches(),
shouldNoMatchesExist: true,
},
{
name: 'does not show text given some matches',
filter: new FilterResultStub().withQueryAndSomeMatches(),
shouldNoMatchesExist: false,
},
];
describe('initial state', () => {
const initialStateTestCases: readonly INoMatchesTextTestCase[] = [
...commonTestCases,
{
name: 'does not show text given no filter',
filter: undefined,
shouldNoMatchesExist: false,
},
];
initialStateTestCases.forEach(({ name, filter, shouldNoMatchesExist }) => {
it(name, () => {
// arrange
const expected = shouldNoMatchesExist;
const stateStub = new UseCollectionStateStub()
.withFilterResult(filter);
// act
const wrapper = mountComponent({
useCollectionState: stateStub.get(),
});
// expect
const actual = wrapper.find(DOM_SELECTOR_NO_MATCHES).exists();
expect(actual).to.equal(expected);
});
});
});
describe('on state change', () => {
commonTestCases.forEach(({ name, filter, shouldNoMatchesExist }) => {
it(name, async () => {
// arrange
const expected = shouldNoMatchesExist;
const filterStub = new UserFilterStub();
const stateStub = new UseCollectionStateStub()
.withFilter(filterStub);
const wrapper = mountComponent({
useCollectionState: stateStub.get(),
});
// act
filterStub.notifyFilterChange(FilterChange.forApply(
filter,
));
await wrapper.vm.$nextTick();
// expect
const actual = wrapper.find(DOM_SELECTOR_NO_MATCHES).exists();
expect(actual).to.equal(expected);
});
});
it('shows no text if filter is removed after matches', async () => {
// arrange
const filter = new UserFilterStub();
const stub = new UseCollectionStateStub()
.withFilter(filter);
const wrapper = mountComponent({
useCollectionState: stub.get(),
});
// act
filter.notifyFilterChange(FilterChange.forApply(
new FilterResultStub().withSomeMatches(),
));
filter.notifyFilterChange(FilterChange.forClear());
await wrapper.vm.$nextTick();
// expect
expect(wrapper.find(DOM_SELECTOR_NO_MATCHES).exists()).to.equal(false);
});
});
});
});
function expectComponentsToNotExist(wrapper: Wrapper<Vue>, components: readonly unknown[]) {
const existingUnexpectedComponents = components
.map((component) => wrapper.findComponent(component))
.filter((component) => component.exists());
expect(existingUnexpectedComponents).to.have.lengthOf(0);
}
function mountComponent(options?: {
readonly useCollectionState?: ReturnType<typeof useCollectionState>,
readonly viewType?: ViewType,
}) {
return shallowMount(TheScriptsView, {
provide: {
[useCollectionStateKey as symbol]:
() => options?.useCollectionState ?? new UseCollectionStateStub().get(),
[useApplicationKey as symbol]:
new UseApplicationStub().get(),
},
propsData: {
currentView: options?.viewType === undefined ? ViewType.Tree : options.viewType,
},
});
}

View File

@@ -17,7 +17,7 @@ export class CategoryCollectionStateStub implements ICategoryCollectionState {
public readonly code: IApplicationCode = new ApplicationCodeStub(); public readonly code: IApplicationCode = new ApplicationCodeStub();
public readonly filter: IUserFilter = new UserFilterStub(); public filter: IUserFilter = new UserFilterStub();
public get os(): OperatingSystem { public get os(): OperatingSystem {
return this.collectionStub.os; return this.collectionStub.os;
@@ -42,6 +42,11 @@ export class CategoryCollectionStateStub implements ICategoryCollectionState {
return this; return this;
} }
public withFilter(filter: IUserFilter) {
this.filter = filter;
return this;
}
public withSelectedScripts(initialScripts: readonly SelectedScript[]) { public withSelectedScripts(initialScripts: readonly SelectedScript[]) {
this.selection.withSelectedScripts(initialScripts); this.selection.withSelectedScripts(initialScripts);
return this; return this;

View File

@@ -0,0 +1,14 @@
import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
import { IEventSubscriptionCollection } from '@/infrastructure/Events/IEventSubscriptionCollection';
export class EventSubscriptionCollectionStub implements IEventSubscriptionCollection {
private readonly subscriptions = new Array<IEventSubscription>();
public register(...subscriptions: IEventSubscription[]) {
this.subscriptions.push(...subscriptions);
}
public unsubscribeAll() {
this.subscriptions.length = 0;
}
}

View File

@@ -33,6 +33,12 @@ export class FilterResultStub implements IFilterResult {
return this; return this;
} }
public withQueryAndSomeMatches() {
return this
.withQuery('non-empty query')
.withSomeMatches();
}
public withQuery(query: string) { public withQuery(query: string) {
this.query = query; this.query = query;
return this; return this;

View File

@@ -0,0 +1,19 @@
import { useApplication } from '@/presentation/components/Shared/Hooks/UseApplication';
import { IApplication } from '@/domain/IApplication';
import { ApplicationStub } from './ApplicationStub';
export class UseApplicationStub {
private application: IApplication = new ApplicationStub();
public withState(application: IApplication) {
this.application = application;
return this;
}
public get(): ReturnType<typeof useApplication> {
return {
application: this.application,
info: this.application.info,
};
}
}

View File

@@ -0,0 +1,87 @@
import { ref } from 'vue';
import {
ContextModifier, IStateCallbackSettings, NewStateEventHandler,
StateModifier, useCollectionState,
} from '@/presentation/components/Shared/Hooks/UseCollectionState';
import { ICategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState';
import { IUserFilter } from '@/application/Context/State/Filter/IUserFilter';
import { IApplicationContext } from '@/application/Context/IApplicationContext';
import { IFilterResult } from '@/application/Context/State/Filter/IFilterResult';
import { CategoryCollectionStateStub } from './CategoryCollectionStateStub';
import { EventSubscriptionCollectionStub } from './EventSubscriptionCollectionStub';
import { ApplicationContextStub } from './ApplicationContextStub';
import { UserFilterStub } from './UserFilterStub';
export class UseCollectionStateStub {
private currentContext: IApplicationContext = new ApplicationContextStub();
private readonly currentState = ref<ICategoryCollectionState>(new CategoryCollectionStateStub());
private readonly onStateChangeHandlers = new Array<NewStateEventHandler>();
public withFilter(filter: IUserFilter) {
const state = new CategoryCollectionStateStub()
.withFilter(filter);
const context = new ApplicationContextStub()
.withState(state);
return new UseCollectionStateStub()
.withState(state)
.withContext(context);
}
public withFilterResult(filterResult: IFilterResult | undefined) {
const filter = new UserFilterStub()
.withCurrentFilterResult(filterResult);
return this.withFilter(filter);
}
public withContext(context: IApplicationContext) {
this.currentContext = context;
return this;
}
public withState(state: ICategoryCollectionState) {
this.currentState.value = state;
return this;
}
public get state(): ICategoryCollectionState {
return this.currentState.value;
}
public triggerOnStateChange(newState: ICategoryCollectionState): void {
this.currentState.value = newState;
this.onStateChangeHandlers.forEach(
(handler) => handler(newState, undefined),
);
}
private onStateChange(
handler: NewStateEventHandler,
settings?: Partial<IStateCallbackSettings>,
) {
if (settings?.immediate) {
handler(this.currentState.value, undefined);
}
this.onStateChangeHandlers.push(handler);
}
private modifyCurrentState(mutator: StateModifier) {
mutator(this.currentState.value);
}
private modifyCurrentContext(mutator: ContextModifier) {
mutator(this.currentContext);
}
public get(): ReturnType<typeof useCollectionState> {
return {
modifyCurrentState: this.modifyCurrentState.bind(this),
modifyCurrentContext: this.modifyCurrentContext.bind(this),
onStateChange: this.onStateChange.bind(this),
currentContext: this.currentContext,
currentState: this.currentState,
events: new EventSubscriptionCollectionStub(),
};
}
}

View File

@@ -5,9 +5,16 @@ import { IFilterChangeDetails } from '@/application/Context/State/Filter/Event/I
import { FilterResultStub } from './FilterResultStub'; import { FilterResultStub } from './FilterResultStub';
import { EventSourceStub } from './EventSourceStub'; import { EventSourceStub } from './EventSourceStub';
export enum UserFilterMethod {
ApplyFilter,
ClearFilter,
}
export class UserFilterStub implements IUserFilter { export class UserFilterStub implements IUserFilter {
private readonly filterChangedSource = new EventSourceStub<IFilterChangeDetails>(); private readonly filterChangedSource = new EventSourceStub<IFilterChangeDetails>();
public readonly callHistory = new Array<UserFilterMethod>();
public currentFilter: IFilterResult | undefined = new FilterResultStub(); public currentFilter: IFilterResult | undefined = new FilterResultStub();
public filterChanged: IEventSource<IFilterChangeDetails> = this.filterChangedSource; public filterChanged: IEventSource<IFilterChangeDetails> = this.filterChangedSource;
@@ -26,7 +33,11 @@ export class UserFilterStub implements IUserFilter {
return this; return this;
} }
public applyFilter(): void { /* NO OP */ } public applyFilter(): void {
this.callHistory.push(UserFilterMethod.ApplyFilter);
}
public clearFilter(): void { /* NO OP */ } public clearFilter(): void {
this.callHistory.push(UserFilterMethod.ClearFilter);
}
} }