mirror of
https://github.com/bitwarden/browser
synced 2025-12-13 23:03:32 +00:00
[EC-7] Org Admin Vault Refresh Client V1 (#3925)
* [EC-8] Restructure Tabs (#3109) * Cherry pick pending PR for tabs component [CL-17] Tabs - Routing * Update organization tabs from 4 to 6 * Create initial 'Members' tab * Create initial 'Groups' tab * Add initial "Reporting" tab * Use correct report label/layout by product type * Create initial 'Billing' tab * Breakup billing payment and billing history pages * Cleanup org routing and nav permission service * More org tab permission cleanup * Refactor organization billing to use a module * Refactor organization reporting to use module * Cherry pick finished/merged tabs component [CL-17] Tabs - Router (#2952) * This partially reverts commit24bb775to fix tracking of people.component.html rename. * Fix people component file rename * Recover lost member page changes * Undo members component rename as it was causing difficult merge conflicts * Fix member and group page container * Remove unnecessary organization lookup * [EC-8] Some PR suggestions * [EC-8] Reuse user billing history for orgs * [EC-8] Renamed user billing history component * [EC-8] Repurpose payment method component Update end user payment method component to be usable for organizations. * [EC-8] Fix missing verify bank condition * [EC-8] Remove org payment method component * [EC-8] Use CL in payment method component * [EC-8] Extend maxWidth Tailwind theme config * [EC-8] Add lazy loading to org reports * [EC-8] Add lazy loading to org billing * [EC-8] Prettier * [EC-8] Cleanup org reporting component redundancy * [EC-8] Use different class for negative margin * [EC-8] Make billing history component "dumb" * Revert "[EC-8] Cleanup org reporting component redundancy" This reverts commiteca337e89b. * [EC-8] Create and export shared reports module * [EC-8] Use shared reports module in orgs * [EC-8] Use takeUntil pattern * [EC-8] Move org reporting module out of old modules folder * [EC-8] Move org billing module out of old modules folder * [EC-8] Fix some remaining merge conflicts * [EC-8] Move maxWidth into 'extend' key for Tailwind config * [EC-8] Remove unused module * [EC-8] Rename org report list component * Prettier Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com> * [EC-451] Org Admin Refresh Permissions Refactor (#3320) * [EC-451] Update new org permissions for new tabs * [EC-451] Remove redudant route guards * [EC-451] Remove canAccessManageTab() * [EC-451] Use canAccess* callbacks in org routing module * Fix org api service refactor and linting after pulling in master * Fix broken org people and group pages after merge * [EC-18] Reporting side nav direction (#3420) * [EC-18] Re-order side nav for org reports according to Figma * [EC-18] Fix rxjs linter errors and redundant org flag * [EC-526] Default to Event Logs page for Reporting Tab (#3470) * [EC-526] Default to the Events Logs page when navigating to the Reporting tab * [EC-526] Undo default routing redirect when the child path is missing. Avoids defaulting to "/events" in case a user/org doesn't have access to event logs. * [EC-19] Update Organization Settings Page (#3251) * [EC-19] Refactor existing organization settings components to its own module * [EC-19] Move SSO page to settings tab * [EC-19] Move Policies page to Settings tab Refactor Policy components into its own module * [EC-19] Move ImageSubscriptionHiddenComponent * [EC-19] Lazy load org settings module * [EC-19] Add SSO Id to SSO config view * [EC-19] Remove SSO identfier from org info page * [EC-19] Update org settings/policies to follow ADR-0011 * [EC-19] Update two-step login setup description * [EC-19] Revert nested policy components folder * [EC-19] Revert nested org setting components folder * [EC-19] Remove left over image component * [EC-19] Prettier * [EC-19] Fix missing i18n * [EC-19] Update SSO form to use CL * [EC-19] Remove unused SSO input components * [EC-19] Fix bad SSO locale identifier * [EC-19] Fix import order linting * [EC-19] Add explicit whitespace check for launch click directive * [EC-19] Add restricted import paths to eslint config * [EC-19] Tag deprecated field with Jira issue to cleanup in future release * [EC-19] Remove out of date comment * [EC-19] Move policy components to policies module * [EC-19] Remove dityRequired validator * [EC-19] Use explicit type for SSO config form * [EC-19] Fix rxjs linter errors * [EC-19] Fix RxJS eslint comments in org settings component * [EC-19] Use explicit ControlsOf<T> helper for nested SSO form groups. * [EC-19] Attribute source of ControlsOf<T> helper * [EC-19] Fix missing settings side nav links * [EC-19] Fix member/user language for policy modals * [EC-551] Update Event Logs Client Column (#3572) * [EC-551] Fix RxJS warnings * [EC-551] Update page to use CL components and Tailwind classes * [EC-551] Update Client column to use text instead of icon. Update language and i18n. * [EC-14] Refactor vault filter (#3440) * [EC-14] initial refactoring of vault filter * [EC-14] return observable trees for all filters with head node * [EC-14] Remove bindings on callbacks * [EC-14] fix formatting on disabled orgs * [EC-14] hide MyVault if personal org policy * [EC-14] add check for single org policy * [EC-14] add policies to org and change node constructor * [EC-14] don't show options if personal vault policy * [EC-14] default to all vaults * [EC-14] add default selection to filters * [EC-14] finish filter model callbacks * [EC-14] finish filter functionality and begin cleaning up * [EC-14] clean up old components and start on org vault * [EC-14] loop through filters for presentation * [EC-14] refactor VaultFilterService and put filter presentation data back into Vault Filter component. Remove VaultService * [EC-14] begin refactoring org vault * [EC-14] Refactor Vault Filter Service to use observables * [EC-14] finish org vault filter * [EC-14] fix vault model tests * [EC-14] fix org service calls * [EC-14] pull refactor out of shared code * [EC-14] include head node for collections even if collections aren't loaded yet * [EC-14] fix url params for vaults * [EC-14] remove comments * [EC-14] Remove unnecesary getter for org on vault filter * [EC-14] fix linter * [EC-14] fix prettier * [EC-14] add deprecated methods to collection service for desktop and browser * [EC-14] simplify cipher type node check * [EC-14] add getters to vault filter model * [EC-14] refactor how we build the filter list into methods * [EC-14] add getters to build filter method * [EC-14] remove param ids if false * [EC-14] fix collapsing nodes * [EC-14] add specific type to search placeholder * [EC-14] remove extra constructor and comment from org vault filter * [EC-14] extract subscription callback to methods * [EC-14] Remove unecessary await * [EC-14] Remove ternary operators while building org filter * [EC-14] remove unnecessary deps array in vault filter service declaration * [EC-14] consolidate new models into one file * [EC-14] initialize nested observable inside of service Signed-off-by: Jacob Fink <jfink@bitwarden.com> * [EC-14] change how we load orgs into the vault filter and select the default filter * [EC-14] remove get from getters name * [EC-14] remove eslint-disable comment * [EC-14] move vault filter service abstraction to angular folder and separate * [EC-14] rename filter types and delete VaultFilterLabel * [EC-14] remove changes to workspace file * [EC-14] remove deprecated service from jslib module * [EC-14] remove any remaining files from common code * [EC-14] consolidate vault filter components into components folder * [EC-14] simplify method call * [EC-14] refactor the vault filter service - orgs now have observable property - BehaviorSubjects have been migrated to ReplaySubjects if they don't need starting value - added unit tests - fix small error when selecting org badge of personal vault - renamed some properties * [EC-14] replace mergeMap with switchMap in vault filter service * [EC-14] early return to prevent nesting * [EC-14] clean up filterCollections method * [EC-14] use isDeleted helper in html * [EC-14] add jsdoc comments to ServiceUtils * [EC-14] fix linter * [EC-14] use array.slice instead of setting length * Update apps/web/src/app/vault/vault-filter/services/vault-filter.service.ts Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com> * [EC-14] add missing high level jsdoc description * [EC-14] fix storybook absolute imports * [EC-14] delete vault-shared.module * [EC-14] change search placeholder text to getter and add missing strings * [EC-14] remove two way binding from search text in vault filter * [EC-14] removed all binding from search text and just use input event * [EC-14] remove async from apply vault filter * [EC-14] remove circular observable calls in vault filter service Co-authored-by: Thomas Rittson <eliykat@users.noreply.github.com> * [EC-14] move collapsed nodes to vault filter section * [EC-14] deconstruct filter section inside component * [EC-14] fix merge conflicts and introduce refactored organization service to vault filter service * [EC-14] remove mutation from filter builders * [EC-14] fix styling on buildFolderTree * [EC-14] remove leftover folder-filters reference and use ternary for collapse icon * [EC-14] remove unecessary checks * [EC-14] stop rebuilding filters when the organization changes * [EC-14] Move subscription out of setter in vault filter section * [EC-14] remove extra policy service methods from vault filter service * [EC-14] remove new methods from old vault-filter.service * [EC-14] Use vault filter service in vault components * [EC-14] reload collections from vault now that we have vault filter service * [EC-14] remove currentFilterCollections in vault filter component * [EC-14] change VaultFilterType to more specific OrganizationFilter in organization-options * [EC-14] include org check in isNodeSelected * [EC-14] add getters to filter function, fix storybook, and add test for All Collections * [EC-14] show org options even if there's a personal vault policy * [EC-14] use !"AllCollections" instead of just !null * [EC-14] Remove extra org Subject in vault filter service * [EC-14] remove null check from vault search text * [EC-14] replace store/build names with set/get. Remove extra call to setOrganizationFilter * [EC-14] add take(1) to subscribe in test * [EC-14] move init logic in org vault filter component to ngOnInit * [EC-14] Fix linter * [EC-14] revert change to vault filter model * [EC-14] be specific about ignoring All Collections * [EC-14] move observable init logic to beforeEach in test * [EC-14] make buildAllFilters return something to reduce side effects Signed-off-by: Jacob Fink <jfink@bitwarden.com> Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com> Co-authored-by: Thomas Rittson <eliykat@users.noreply.github.com> * [EC-97] Organization Billing Language / RxJS Warnings (#3688) * [EC-97] Update copy to use the word members in a few places * [EC-97] Cleanup RxJS warnings and unused properties in org billing components * [EC-599] Access Selector Component (#3717) * Add Access Selector Component and Stories * Cherry pick FormSelectionList * Fix some problems caused from cherry-pick * Fix some Web module problems caused from cherry-pick * Move AccessSelector out of the root components directory. Move UserType pipe to AccessSelectorModule * Fix broken member access selector story * Add organization feature module * Undo changes to messages.json * Fix messages.json * Remove redundant CommonModule * [EC-599] Fix avatar/icon sizing * [EC-599] Remove padding in permission column * [EC-599] Make FormSelectionList operations immutable * [EC-599] Integrate the multi-select component * [EC-599] Handle readonly/access all edge cases * [EC-599] Add initial unit tests Also cleans up public interface for the AccessSelectorComponent. Fixes a bug found during unit test creation. * [EC-599] Include item name in control labels * [EC-599] Cleanup member email display * [EC-599] Review suggestions - Change PermissionMode to Enum - Rename permControl to permissionControl to be more clear - Rename FormSelectionList file to kebab case. - Move permission row boolean logic to named function for readability * [EC-599] Cleanup AccessSelectorComponent tests - Clarify test states - Add tests for column rendering - Add tests for permission mode - Add id to column headers for testing - Fix small permissionControl bug found during testing * [EC-599] Add FormSelectionList unit tests * [EC-599] Fix unit test and linter * [EC-599] Update Enums to Pascal case * [EC-599] Undo change to Enum values * [EC-7] fix: broken build * [EC-646] Org Admin Vault Refresh November Release Prep (#3913) * [EC-646] Remove links from Manage component These links are no longer necessary as they are now located in the new OAVR tabs. * [EC-646] Re-introduce the canAccessManageTab helper * [EC-646] Re-introduce /manage route in Organization routing module - Add the parent /manage route - Add child routes for collections, people, and groups * [EC-646] Adjust Org admin tabs Re-introduce the Manage tab and remove Groups and Members tabs. * [EC-646] Change Members title back to People * [EC-646] Move missing billing components Some billing components were in the org settings module and needed to be moved the org billing module * [EC-646] Fix import file upload button -Update to use click event handler and tailwind class to hide input. Avoids inline styles/js blocked by CSP - Fix broken async pipe * [EC-646] Fix groups and people page overflow Remove the container and page-content wrapper as the pages are no longer on their own tab * [EC-646] Change People to Members Change the text regarding managing members from People to Members to more closely follow changes coming later in the OAVR. Also update the URL to use /manage/members * [EC-646] Cherry-pickae39afeto fix tab text color * [EC-646] Fix org routing permissions helpers - Add canAccessVaultTab helper - Update canAccessOrgAdmin include check for vault tab access - Simplify canManageCollections * [EC-646] Fix Manage tab conditional logic - Add *ngIf condition for rendering Manage tab - Re-introduce dynamic route for Manage tab * Revert "[EC-14] Refactor vault filter (#3440)" (#3926) This reverts commit4d83b81d82. * Remove old reference to bit-submit-button that no longer exists (#3927) * [EC-593] Top align event logs row content (#3813) * [EC-593] Top align event log row contents * [EC-593] Prevent event log timestamp from wrapping * [EC-593] Add alignContent input to bitRow directive * [EC-593] Remove ineffective inline styles (CSP) * [EC-593] Remove templated tailwind classes Tailwind minimizes the bundled stylesheet by removing classes that aren't used in code. Using a string template for the classes causes those classes to be ignored. * [EC-593] Introduce alignContent input to table story * [EC-657] Hide Billing History and Payment Method for selfhosted orgs (#3935) Signed-off-by: Jacob Fink <jfink@bitwarden.com> Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com> Co-authored-by: Andreas Coroiu <andreas.coroiu@gmail.com> Co-authored-by: Jake Fink <jfink@bitwarden.com> Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com> Co-authored-by: Thomas Rittson <eliykat@users.noreply.github.com>
This commit is contained in:
253
libs/angular/src/utils/form-selection-list.spec.ts
Normal file
253
libs/angular/src/utils/form-selection-list.spec.ts
Normal file
@@ -0,0 +1,253 @@
|
||||
import { FormBuilder } from "@angular/forms";
|
||||
|
||||
import { FormSelectionList, SelectionItemId } from "./form-selection-list";
|
||||
|
||||
interface TestItemView extends SelectionItemId {
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
interface TestItemValue extends SelectionItemId {
|
||||
value: string;
|
||||
}
|
||||
|
||||
const initialTestItems: TestItemView[] = [
|
||||
{ id: "1", displayName: "1st Item" },
|
||||
{ id: "2", displayName: "2nd Item" },
|
||||
{ id: "3", displayName: "3rd Item" },
|
||||
];
|
||||
const totalTestItemCount = initialTestItems.length;
|
||||
|
||||
describe("FormSelectionList", () => {
|
||||
let formSelectionList: FormSelectionList<TestItemView, TestItemValue>;
|
||||
let testItems: TestItemView[];
|
||||
|
||||
const formBuilder = new FormBuilder();
|
||||
|
||||
const testCompareFn = (a: TestItemView, b: TestItemView) => {
|
||||
return a.displayName.localeCompare(b.displayName);
|
||||
};
|
||||
|
||||
const testControlFactory = (item: TestItemView) => {
|
||||
return formBuilder.group({
|
||||
id: [item.id],
|
||||
value: [""],
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
formSelectionList = new FormSelectionList<TestItemView, TestItemValue>(
|
||||
testControlFactory,
|
||||
testCompareFn
|
||||
);
|
||||
testItems = [...initialTestItems];
|
||||
});
|
||||
|
||||
it("should create with empty arrays", () => {
|
||||
expect(formSelectionList.selectedItems.length).toEqual(0);
|
||||
expect(formSelectionList.deselectedItems.length).toEqual(0);
|
||||
expect(formSelectionList.formArray.length).toEqual(0);
|
||||
});
|
||||
|
||||
describe("populateItems()", () => {
|
||||
it("should have no selected items when populated without a selection", () => {
|
||||
// Act
|
||||
formSelectionList.populateItems(testItems, []);
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems.length).toEqual(0);
|
||||
});
|
||||
|
||||
it("should have selected items when populated with a list of selected items", () => {
|
||||
// Act
|
||||
formSelectionList.populateItems(testItems, [{ id: "1", value: "test" }]);
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems.length).toEqual(1);
|
||||
expect(formSelectionList.selectedItems).toHaveProperty("[0].id", "1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("selectItem()", () => {
|
||||
beforeEach(() => {
|
||||
formSelectionList.populateItems(testItems);
|
||||
});
|
||||
|
||||
it("should add item to selectedItems, remove from deselectedItems, and create a form control when called with a valid id", () => {
|
||||
// Act
|
||||
formSelectionList.selectItem("1");
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems.length).toEqual(1);
|
||||
expect(formSelectionList.formArray.length).toEqual(1);
|
||||
expect(formSelectionList.deselectedItems.length).toEqual(totalTestItemCount - 1);
|
||||
});
|
||||
|
||||
it("should do nothing when called with a invalid id", () => {
|
||||
// Act
|
||||
formSelectionList.selectItem("bad-id");
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems.length).toEqual(0);
|
||||
expect(formSelectionList.formArray.length).toEqual(0);
|
||||
expect(formSelectionList.deselectedItems.length).toEqual(totalTestItemCount);
|
||||
});
|
||||
|
||||
it("should create a form control with an initial value when called with an initial value and valid id", () => {
|
||||
// Arrange
|
||||
const testValue = "TestValue";
|
||||
const idToSelect = "1";
|
||||
|
||||
// Act
|
||||
formSelectionList.selectItem(idToSelect, { value: testValue });
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.formArray.length).toEqual(1);
|
||||
expect(formSelectionList.formArray.value).toHaveProperty("[0].id", idToSelect);
|
||||
expect(formSelectionList.formArray.value).toHaveProperty("[0].value", testValue);
|
||||
|
||||
expect(formSelectionList.selectedItems.length).toEqual(1);
|
||||
expect(formSelectionList.deselectedItems.length).toEqual(totalTestItemCount - 1);
|
||||
});
|
||||
|
||||
it("should ensure the id value is set for the form control when called with a valid id", () => {
|
||||
// Arrange
|
||||
const testValue = "TestValue";
|
||||
const idToSelect = "1";
|
||||
const idOverride = "some-other-id";
|
||||
|
||||
// Act
|
||||
formSelectionList.selectItem(idToSelect, { value: testValue, id: idOverride });
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.formArray.value).toHaveProperty("[0].id", idOverride);
|
||||
expect(formSelectionList.formArray.value).toHaveProperty("[0].value", testValue);
|
||||
});
|
||||
|
||||
// Ensure Angular's Change Detection will pick up any modifications to the array
|
||||
it("should create new copies of the selectedItems and deselectedItems arrays when called with a valid id", () => {
|
||||
// Arrange
|
||||
const initialSelected = formSelectionList.selectedItems;
|
||||
const initialdeselected = formSelectionList.deselectedItems;
|
||||
|
||||
// Act
|
||||
formSelectionList.selectItem("1");
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems).not.toEqual(initialSelected);
|
||||
expect(formSelectionList.deselectedItems).not.toEqual(initialdeselected);
|
||||
});
|
||||
|
||||
it("should add items to selectedItems array in sorted order when called with a valid id", () => {
|
||||
// Act
|
||||
formSelectionList.selectItems(["2", "3", "1"]); // Use out of order ids
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems).toHaveProperty("[0].id", "1");
|
||||
expect(formSelectionList.selectedItems).toHaveProperty("[1].id", "2");
|
||||
expect(formSelectionList.selectedItems).toHaveProperty("[2].id", "3");
|
||||
|
||||
// Form array values should be in the same order
|
||||
expect(formSelectionList.formArray.value[0].id).toEqual(
|
||||
formSelectionList.selectedItems[0].id
|
||||
);
|
||||
|
||||
expect(formSelectionList.formArray.value[1].id).toEqual(
|
||||
formSelectionList.selectedItems[1].id
|
||||
);
|
||||
|
||||
expect(formSelectionList.formArray.value[2].id).toEqual(
|
||||
formSelectionList.selectedItems[2].id
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deselectItem()", () => {
|
||||
beforeEach(() => {
|
||||
formSelectionList.populateItems(testItems, [
|
||||
{ id: "1", value: "testValue" },
|
||||
{ id: "2", value: "testValue" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should add item to deselectedItems, remove from selectedItems and remove from formArray when called with a valid id", () => {
|
||||
// Act
|
||||
formSelectionList.deselectItem("1");
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems.length).toEqual(1);
|
||||
expect(formSelectionList.formArray.length).toEqual(1);
|
||||
expect(formSelectionList.deselectedItems.length).toEqual(2);
|
||||
|
||||
// Value and View should still be in sync
|
||||
expect(formSelectionList.formArray.value[0].id).toEqual(
|
||||
formSelectionList.selectedItems[0].id
|
||||
);
|
||||
});
|
||||
|
||||
it("should do nothing when called with a invalid id", () => {
|
||||
// Act
|
||||
formSelectionList.deselectItem("bad-id");
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems.length).toEqual(2);
|
||||
expect(formSelectionList.formArray.length).toEqual(2);
|
||||
expect(formSelectionList.deselectedItems.length).toEqual(1);
|
||||
});
|
||||
|
||||
// Ensure Angular's Change Detection will pick up any modifications to the array
|
||||
it("should create new copies of the selectedItems and deselectedItems arrays when called with a valid id", () => {
|
||||
// Arrange
|
||||
const initialSelected = formSelectionList.selectedItems;
|
||||
const initialdeselected = formSelectionList.deselectedItems;
|
||||
|
||||
// Act
|
||||
formSelectionList.deselectItem("1");
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems).not.toEqual(initialSelected);
|
||||
expect(formSelectionList.deselectedItems).not.toEqual(initialdeselected);
|
||||
});
|
||||
|
||||
it("should add items to deselectedItems array in sorted order when called with a valid id", () => {
|
||||
// Act
|
||||
formSelectionList.deselectItems(["2", "1"]); // Use out of order ids
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.deselectedItems).toHaveProperty("[0].id", "1");
|
||||
expect(formSelectionList.deselectedItems).toHaveProperty("[1].id", "2");
|
||||
expect(formSelectionList.deselectedItems).toHaveProperty("[2].id", "3");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deselectAll()", () => {
|
||||
beforeEach(() => {
|
||||
formSelectionList.populateItems(testItems, [
|
||||
{ id: "1", value: "testValue" },
|
||||
{ id: "2", value: "testValue" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should clear the formArray and selectedItems arrays and populate the deselectedItems array when called", () => {
|
||||
// Act
|
||||
formSelectionList.deselectAll();
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems.length).toEqual(0);
|
||||
expect(formSelectionList.formArray.length).toEqual(0);
|
||||
expect(formSelectionList.deselectedItems.length).toEqual(totalTestItemCount);
|
||||
});
|
||||
|
||||
it("should create new arrays for selectedItems and deselectedItems when called", () => {
|
||||
// Arrange
|
||||
const initialSelected = formSelectionList.selectedItems;
|
||||
const initialdeselected = formSelectionList.deselectedItems;
|
||||
|
||||
// Act
|
||||
formSelectionList.deselectAll();
|
||||
|
||||
// Assert
|
||||
expect(formSelectionList.selectedItems).not.toEqual(initialSelected);
|
||||
expect(formSelectionList.deselectedItems).not.toEqual(initialdeselected);
|
||||
});
|
||||
});
|
||||
});
|
||||
201
libs/angular/src/utils/form-selection-list.ts
Normal file
201
libs/angular/src/utils/form-selection-list.ts
Normal file
@@ -0,0 +1,201 @@
|
||||
import { AbstractControl, FormArray } from "@angular/forms";
|
||||
|
||||
export type SelectionItemId = {
|
||||
id: string;
|
||||
};
|
||||
|
||||
function findSortedIndex<T>(sortedArray: T[], val: T, compareFn: (a: T, b: T) => number) {
|
||||
let low = 0;
|
||||
let high = sortedArray.length || 0;
|
||||
let mid = -1,
|
||||
c = 0;
|
||||
while (low < high) {
|
||||
mid = Math.floor((low + high) / 2);
|
||||
c = compareFn(sortedArray[mid], val);
|
||||
if (c < 0) {
|
||||
low = mid + 1;
|
||||
} else if (c > 0) {
|
||||
high = mid;
|
||||
} else {
|
||||
return mid;
|
||||
}
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility to help manage a list of selectable items for use with Reactive Angular forms and FormArrays.
|
||||
*
|
||||
* It supports selecting/deselecting items, keeping items sorted, and synchronizing the selected items
|
||||
* with an array of FormControl.
|
||||
*
|
||||
* The first type parameter TItem represents the item being selected/deselected, it must have an `id`
|
||||
* property for identification/comparison. The second type parameter TControlValue represents the value
|
||||
* type of the form control.
|
||||
*/
|
||||
export class FormSelectionList<
|
||||
TItem extends SelectionItemId,
|
||||
TControlValue extends SelectionItemId
|
||||
> {
|
||||
allItems: TItem[] = [];
|
||||
/**
|
||||
* Sorted list of selected items
|
||||
* Immutable and should be recreated whenever a modification is made
|
||||
*/
|
||||
selectedItems: TItem[] = [];
|
||||
|
||||
/**
|
||||
* Sorted list of deselected items
|
||||
* Immutable and should be recreated whenever a modification is made
|
||||
*/
|
||||
deselectedItems: TItem[] = [];
|
||||
|
||||
/**
|
||||
* Sorted FormArray that corresponds and stays in sync with the selectedItems
|
||||
*/
|
||||
formArray: FormArray<AbstractControl<Partial<TControlValue>, TControlValue>> = new FormArray([]);
|
||||
|
||||
/**
|
||||
* Construct a new FormSelectionList
|
||||
* @param controlFactory - Factory responsible for creating initial form controls for each selected item. It is
|
||||
* provided a copy of the selected item for any form control initialization logic. Specify any additional form
|
||||
* control options or validators here.
|
||||
* @param compareFn - Comparison function used for sorting the items.
|
||||
*/
|
||||
constructor(
|
||||
private controlFactory: (item: TItem) => AbstractControl<Partial<TControlValue>, TControlValue>,
|
||||
private compareFn: (a: TItem, b: TItem) => number
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Select multiple items by their ids at once. Optionally provide an initial form control value.
|
||||
* @param ids - List of ids to select
|
||||
* @param initialValue - Value that will be applied to the corresponding form controls
|
||||
* The provided `id` arguments will be automatically assigned to each form control value
|
||||
*/
|
||||
selectItems(ids: string[], initialValue?: Partial<TControlValue> | undefined) {
|
||||
for (const id of ids) {
|
||||
this.selectItem(id, initialValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deselect multiple items by their ids at once
|
||||
* @param ids - List of ids to deselect
|
||||
*/
|
||||
deselectItems(ids: string[]) {
|
||||
for (const id of ids) {
|
||||
this.deselectItem(id);
|
||||
}
|
||||
}
|
||||
|
||||
deselectAll() {
|
||||
this.formArray.clear();
|
||||
this.selectedItems = [];
|
||||
this.deselectedItems = [...this.allItems];
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a single item by id.
|
||||
*
|
||||
* Maintains list order for both selected items, deselected items, and the FormArray.
|
||||
*
|
||||
* @param id - Id of the item to select
|
||||
* @param initialValue - Value that will be applied to the corresponding form control for the selected item.
|
||||
* The provided `id` argument will be automatically assigned unless explicitly set in the initialValue.
|
||||
*/
|
||||
selectItem(id: string, initialValue?: Partial<TControlValue>) {
|
||||
const index = this.deselectedItems.findIndex((o) => o.id === id);
|
||||
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedOption = this.deselectedItems[index];
|
||||
|
||||
// Note: Changes to the deselected/selected arrays must create a new copy of the array
|
||||
// in order for Angular's Change Detection to pick up the modification (i.e. treat the arrays as immutable)
|
||||
|
||||
// Remove from the list of deselected options
|
||||
this.deselectedItems = [
|
||||
...this.deselectedItems.slice(0, index),
|
||||
...this.deselectedItems.slice(index + 1),
|
||||
];
|
||||
|
||||
// Insert into the sorted selected options list
|
||||
const sortedInsertIndex = findSortedIndex(this.selectedItems, selectedOption, this.compareFn);
|
||||
|
||||
this.selectedItems = [
|
||||
...this.selectedItems.slice(0, sortedInsertIndex),
|
||||
selectedOption,
|
||||
...this.selectedItems.slice(sortedInsertIndex),
|
||||
];
|
||||
|
||||
const newControl = this.controlFactory(selectedOption);
|
||||
|
||||
// Patch the value and ensure the `id` is set
|
||||
newControl.patchValue({
|
||||
id,
|
||||
...initialValue,
|
||||
});
|
||||
|
||||
this.formArray.insert(sortedInsertIndex, newControl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deselect a single item by id.
|
||||
*
|
||||
* Maintains list order for both selected items, deselected items, and the FormArray.
|
||||
*
|
||||
* @param id - Id of the item to deselect
|
||||
*/
|
||||
deselectItem(id: string) {
|
||||
const index = this.selectedItems.findIndex((o) => o.id === id);
|
||||
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const deselectedOption = this.selectedItems[index];
|
||||
|
||||
// Note: Changes to the deselected/selected arrays must create a new copy of the array
|
||||
// in order for Angular's Change Detection to pick up the modification (i.e. treat the arrays as immutable)
|
||||
|
||||
// Remove from the list of selected items (and FormArray)
|
||||
this.selectedItems = [
|
||||
...this.selectedItems.slice(0, index),
|
||||
...this.selectedItems.slice(index + 1),
|
||||
];
|
||||
this.formArray.removeAt(index);
|
||||
|
||||
// Insert into the sorted deselected array
|
||||
const sortedInsertIndex = findSortedIndex(
|
||||
this.deselectedItems,
|
||||
deselectedOption,
|
||||
this.compareFn
|
||||
);
|
||||
|
||||
this.deselectedItems = [
|
||||
...this.deselectedItems.slice(0, sortedInsertIndex),
|
||||
deselectedOption,
|
||||
...this.deselectedItems.slice(sortedInsertIndex),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate the list of deselected items, and optional specify which items should be selected and with what initial
|
||||
* value for their Form Control
|
||||
* @param items - A list of all items. (Will be sorted internally)
|
||||
* @param selectedItems - The items to select initially
|
||||
*/
|
||||
populateItems(items: TItem[], selectedItems: TControlValue[] = []) {
|
||||
this.formArray.clear();
|
||||
this.allItems = [...items].sort(this.compareFn);
|
||||
this.selectedItems = [];
|
||||
this.deselectedItems = [...this.allItems];
|
||||
|
||||
for (const selectedItem of selectedItems) {
|
||||
this.selectItem(selectedItem.id, selectedItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user