EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
TS migration
Yurii15756495b929
diff --git a/client/src/model.ts b/client/src/model.tsindex da4fbec860..3e2b182380 100644--- a/client/src/model.ts+++ b/client/src/model.ts@@ -474,7 +474,7 @@ export default class Model<T extends Record<string, unknown> = Record<string, an* @param {{silent?: boolean} & Object.<string, *>} [options] Options.*/clear(- options: {silent?: boolean} & Record<string, any>,+ options?: {silent?: boolean} & Record<string, any>,): this {const attributes = {} as Partial<T>;diff --git a/client/src/search-manager.ts b/client/src/search-manager.tsindex 950e2655e1..685254e323 100644--- a/client/src/search-manager.ts+++ b/client/src/search-manager.ts@@ -37,7 +37,7 @@ import Collection, {WhereItem} from 'collection';* Search data.*/interface Data {- presetName?: string;+ presetName?: string | null;textFilter?: string;primary?: string | null;bool?: Record<string, boolean>;@@ -80,12 +80,19 @@ class SearchManager {private storage: Storageprivate timeZone: string | null = null+private readonly defaultData: InternalData+private readonly scope: string | null+private readonly storageKey: string | null+private readonly useStorage: boolean+private readonly emptyOnReset: boolean+private readonly emptyData: InternalData+private data: InternalData/**@@ -310,7 +317,7 @@ class SearchManager {/*** Get data.*/- get(): Data {+ get(): InternalData {return this.data;}@@ -361,7 +368,7 @@ class SearchManager {** @param data Data.*/- set(data: Data) {+ set(data: InternalData) {this.data = data;if (this.useStorage && this.scope) {diff --git a/client/src/ui/autocomplete.js b/client/src/ui/autocomplete.jsindex 9ca9b77c91..7cb1cce5a6 100644--- a/client/src/ui/autocomplete.js+++ b/client/src/ui/autocomplete.js@@ -36,32 +36,32 @@ import Handlebars from 'handlebars';* @property {string} value*/+/**+ * @typedef {{+ * name?: string,+ * forceHide?: boolean,+ * lookup?: string[],+ * lookupFunction?: function (string): Promise<Array<AutocompleteItem & Record>>,+ * minChars?: Number,+ * formatResult?: function (AutocompleteItem & Record<string, any>): string,+ * onSelect?: function (AutocompleteItem & Record<string, any>): void,+ * beforeRender?: function (HTMLElement): void,+ * triggerSelectOnValidInput?: boolean,+ * autoSelectFirst?: boolean,+ * handleFocusMode?: 1|2|3,+ * focusOnSelect?: boolean,+ * catchFastEnter?: boolean,+ * }} AutocompleteOptions+ */+/*** An autocomplete.*/class Autocomplete {- /**- * @typedef {{- * name?: string,- * forceHide?: boolean,- * lookup?: string[],- * lookupFunction?: function (string): Promise<Array<AutocompleteItem & Record>>,- * minChars?: Number,- * formatResult?: function (AutocompleteItem & Record<string, any>): string,- * onSelect?: function (AutocompleteItem & Record<string, any>): void,- * beforeRender?: function (HTMLElement): void,- * triggerSelectOnValidInput?: boolean,- * autoSelectFirst?: boolean,- * handleFocusMode?: 1|2|3,- * focusOnSelect?: boolean,- * catchFastEnter?: boolean,- * }} module:ui/autocomplete~options- */-/*** @param {HTMLInputElement} element- * @param {module:ui/autocomplete~options} options+ * @param {AutocompleteOptions} options*/constructor(element, options) {/** @private */@@ -201,7 +201,7 @@ class Autocomplete {/*** @private- * @param {module:ui/autocomplete~options} options+ * @param {AutocompleteOptions} options*/initHandleFocus(options) {this.$element.off('focus.autocomplete');diff --git a/client/src/views/fields/base.ts b/client/src/views/fields/base.tsindex c46f462366..5aa39012b1 100644--- a/client/src/views/fields/base.ts+++ b/client/src/views/fields/base.ts@@ -1685,4 +1685,12 @@ export default class BaseFieldView<protected toSkipReRenderOnChange(): boolean {return false;}++ /**+ * @internal+ * @since 10.0.0+ */+ setSearchParams(params: Record<string, any>) {+ this.searchParams = params;+ }}diff --git a/client/src/views/fields/link-parent.ts b/client/src/views/fields/link-parent.tsindex e80bac59b5..0c4b15f742 100644--- a/client/src/views/fields/link-parent.ts+++ b/client/src/views/fields/link-parent.ts@@ -492,7 +492,7 @@ class LinkParentFieldView<triggerSelectOnValidInput: false,forceHide: true,minChars: this.autocompleteOnEmpty ? 0 : 1,- onSelect: async (item: {attributes: any}) => {+ onSelect: async (item: any & {attributes: any}) => {const entityType = this.foreignScope;if (!entityType) {diff --git a/client/src/views/fields/link.ts b/client/src/views/fields/link.tsindex 53ef119554..13e9cbdc27 100644--- a/client/src/views/fields/link.ts+++ b/client/src/views/fields/link.ts@@ -705,7 +705,7 @@ class LinkFieldView<autoSelectFirst: true,triggerSelectOnValidInput: false,forceHide: true,- onSelect: async (item: {attributes: Record<string, any>}) => {+ onSelect: async (item: any & {attributes: Record<string, any>}) => {const model = await this.getModelFactory().create(this.foreignScope);model.setMultiple(item.attributes);@@ -761,8 +761,8 @@ class LinkFieldView<}}- private _transformAutocompleteResult(response: {list: Record<string, any>[]}): Record<string, any[]> {- const list: Record<string, any> = [];+ private _transformAutocompleteResult(response: {list: Record<string, any>[]}): Record<string, any>[] {+ const list: Record<string, any>[] = [];response.list.forEach(item => {const name = item[this.foreignNameAttribute] || item.name || item.id;diff --git a/client/src/views/record/search.js b/client/src/views/record/search.tssimilarity index 56%rename from client/src/views/record/search.jsrename to client/src/views/record/search.tsindex 1abc933ba0..20d017b519 100644--- a/client/src/views/record/search.js+++ b/client/src/views/record/search.ts@@ -26,72 +26,167 @@* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.************************************************************************/-/** @module views/record/search */-import View from 'view';import StoredTextSearch from 'helpers/misc/stored-text-search';import Autocomplete from 'ui/autocomplete';import FilterView from 'views/search/filter';+import SearchManager, {AdvancedFilter} from 'search-manager';+import Utils from 'utils';+import Ui from 'ui';+import BaseFieldView from 'views/fields/base';+import SaveFiltersModalView from 'views/modals/save-filters';+import _ from 'underscore';+import type Model from 'model';+import type Collection from 'collection';++interface BoolFilterDefs {+ name?: string;+ inPortalDisabled?: boolean;+ isPortalOnly?: boolean;+ aux?: boolean;+ accessDataList?: import('utils').AccessDefs[];+}-/**- * @typedef {Object} module:views/record/search~boolFilterDefs- * @property {string} [name]- * @property {boolean} [inPortalDisabled]- * @property {boolean} [isPortalOnly]- * @property {boolean} [aux]- * @property {module:utils~AccessDefs[]} [accessDataList]- */+interface PresetFilter {+ name: string | null;+ label?: string;+ primary?: boolean;+ data?: any;+ style?: string;+}++type CreateFilterCallback = (view: import('views/search/filter').default) => void;++interface SearchViewOptions {+ isWide?: boolean;+ scope?: string;+ filtersLayoutName?: string;+ primaryFiltersDisabled?: boolean;+ searchManager: SearchManager;+ textFilterDisabled?: boolean;+ disableSavePreset?: boolean;+ viewMode: string;+ viewModeList?: string[];+ filterList?: string[];+}++interface ViewSchema {+ model: Model;+ collection: Collection;+ options: SearchViewOptions;+}/*** A search panel view.*/-class SearchView extends View {+class SearchView extends View<ViewSchema> {- template = 'record/search'+ constructor(options: SearchViewOptions & {collection: Collection}) {+ super(options);+ }- scope = ''- entityType = ''- /** @type {module:search-manager} */- searchManager- fieldFilterList = null- /** @type {Object.<string, string>|null}*/- fieldFilterTranslations = null+ protected template: string = 'record/search'- textFilter = ''- /**- * @type {string|null}- */- primary = null- presetFilterList = null- /** @type {{string: import('search-manager').AdvancedFilter}} */- advanced- bool = null- filtersLayoutName = 'filters'-- disableSavePreset = false- textFilterDisabled = false- toShowApplyFiltersButton = false- toShowResetFiltersText = false- isSearchedWithAdvancedFilter = false- primaryFiltersDisabled = false-- viewModeIconClassMap = {+ private scope: string++ private entityType: string++ private searchManager: SearchManager++ private fieldFilterList: string[] | null = null++ private fieldFilterTranslations: Record<string, string>++ private textFilter: string = ''++ private presetName: string | null = null++ private primary: string | null = null++ private presetFilterList: (+ {+ name?: string,+ label?: string,+ id?: string,+ style?: string,+ } | string+ )[]++ private advanced: Record<string, AdvancedFilter | Partial<AdvancedFilter> | Record<string, any> | null>++ private bool: Record<string, boolean> | null = null++ private filtersLayoutName: string = 'filters'++ private disableSavePreset: boolean = false++ private textFilterDisabled: boolean = false++ private toShowApplyFiltersButton: boolean = false++ private toShowResetFiltersText: boolean = false++ private isSearchedWithAdvancedFilter: boolean = false++ private primaryFiltersDisabled: boolean = false++ private viewModeIconClassMap: Record<string, string> = {list: 'fas fa-align-justify',kanban: 'fas fa-align-left fa-rotate-90',}- FIELD_QUICK_SEARCH_COUNT_THRESHOLD = 4+ readonly FIELD_QUICK_SEARCH_COUNT_THRESHOLD = 4++ private autocompleteLimit: number = 7++ private boolFilterList: string[]- autocompleteLimit = 7+ private viewMode: string- data() {+ private viewModeList: string[] | null++ private viewModeDataList: {+ name: string,+ title: string,+ iconClass?: string,+ }[]++ storedTextSearchHelper: StoredTextSearch++ private textSearchStoringDisabled: boolean;++ private currentFilterLabelList: string[] | null = null++ private filtersLabel: HTMLElement | null;++ private applyFiltersContainer: HTMLElement;++ private applyFiltersElement: HTMLElement;++ private filtersButton: HTMLButtonElement;++ private leftDropdownElement: HTMLButtonElement | null;++ private resetButtonElement: HTMLButtonElement | null;++ private addFilterButtonElement: HTMLButtonElement | null;++ private filterListElement: HTMLUListElement | null;++ private fieldQuickSearchInput: HTMLInputElement | null;++ private textFilterInputElement: HTMLInputElement | null;++ private advancedFiltersPanelElement: HTMLElement;++ protected data(): Record<string, any> {return {scope: this.scope,entityType: this.entityType,textFilter: this.textFilter,bool: this.bool || {},boolFilterList: this.boolFilterList,- hasFieldQuickSearch: this.fieldFilterList.length >= this.FIELD_QUICK_SEARCH_COUNT_THRESHOLD,+ hasFieldQuickSearch: this.fieldFilterList!.length >= this.FIELD_QUICK_SEARCH_COUNT_THRESHOLD,filterFieldDataList: this.getFilterFieldDataList(),filterDataList: this.getFilterDataList(),presetName: this.presetName,@@ -108,7 +203,13 @@ class SearchView extends View {};}- setup() {+ protected setup() {+ this.setupEventHandlers();++ if (!this.collection.entityType) {+ throw new Error("No entity type.");+ }+this.entityType = this.collection.entityType;this.scope = this.options.scope || this.entityType;this.filtersLayoutName = this.options.filtersLayoutName || this.filtersLayoutName;@@ -119,10 +220,8 @@ class SearchView extends View {...this.getMetadata().get(`clientDefs.${this.scope}.viewModeIconClassMap`),};- /** @type {module:search-manager} */this.searchManager = this.options.searchManager;- /** @private */this.storedTextSearchHelper = new StoredTextSearch(this.scope, this.getHelper().storage);this.textSearchStoringDisabled = this.getPreferences().get('textSearchStoringDisabled');@@ -131,18 +230,18 @@ class SearchView extends View {this.getMetadata().get(['clientDefs', this.scope, 'textFilterDisabled']);if ('disableSavePreset' in this.options) {- this.disableSavePreset = this.options.disableSavePreset;+ this.disableSavePreset = this.options.disableSavePreset as boolean;}this.viewMode = this.options.viewMode;- this.viewModeList = this.options.viewModeList;+ this.viewModeList = this.options.viewModeList ?? null;this.addReadyCondition(() => {return this.fieldFilterList !== null;});- /** @type {Array<module:views/record/search~boolFilterDefs|string>} */- const boolFilterList = this.getMetadata().get(['clientDefs', this.scope, 'boolFilterList']) ?? [];+ const boolFilterList = (this.getMetadata().get(['clientDefs', this.scope, 'boolFilterList']) ?? []) as+ (BoolFilterDefs | string)[];this.boolFilterList = boolFilterList.filter(item => {@@ -165,7 +264,7 @@ class SearchView extends View {}if (item.accessDataList) {- if (!Espo.Utils.checkAccessDataList(item.accessDataList, this.getAcl(), this.getUser())) {+ if (!Utils.checkAccessDataList(item.accessDataList, this.getAcl(), this.getUser())) {return false;}}@@ -180,7 +279,8 @@ class SearchView extends View {item = item ?? {};return item.name;- });+ })+ .filter(it => it != null)this.fieldFilterTranslations = {};@@ -188,22 +288,23 @@ class SearchView extends View {this.wait(new Promise(resolve => {- this.getHelper().layoutManager.get(this.entityType, this.filtersLayoutName, list => {+ this.getHelper().layoutManager.get(this.entityType, this.filtersLayoutName, (list: string[]) => {this.fieldFilterList = [];- (list || []).forEach(field => {- if (~forbiddenFieldList.indexOf(field)) {+ (list ?? []).forEach(field => {+ if (forbiddenFieldList.includes(field)) {return;}- this.fieldFilterList.push(field);+ this.fieldFilterList!.push(field);this.fieldFilterTranslations[field] = this.translate(field, 'fields', this.entityType);});- resolve();+ resolve(undefined);});}));+this.setupPresetFilters();if (this.getMetadata().get(['scopes', this.entityType, 'stream'])) {@@ -256,15 +357,115 @@ class SearchView extends View {);}- setupPresetFilters() {+ private setupEventHandlers() {+ this.addHandler('keydown', 'input[data-name="textFilter"]', (e) => {+ if (!(e instanceof KeyboardEvent)) {+ throw new Error();+ }++ const key = Utils.getKeyFromKeyEvent(e);++ if (e.key === 'Enter' || key === 'Enter' || key === 'Control+Enter') {+ this.search();++ this.hideApplyFiltersButton();+ }+ });++ this.addHandler('focus', 'input[data-name="textFilter"]', (_, target) => {+ (target as HTMLInputElement).select();+ });++ this.addHandler('click', '.advanced-filters-apply-container a[data-action="applyFilters"]', () => {+ this.search();+ this.hideApplyFiltersButton();++ this.element.querySelector<HTMLButtonElement>('button.search')?.focus();+ });++ this.addHandler('click', 'button[data-action="search"]', () => {+ this.search();+ this.hideApplyFiltersButton();+ });++ this.addHandler('click', 'a[data-action="addFilter"]', (_, target) => {+ const name = target.dataset.name as string;++ target?.closest('li')?.classList.add('hidden');++ this.addFilter(name);+ });++ this.addHandler('click', '.advanced-filters a.remove-filter', (_, target) => {+ const name = target.dataset.name as string;++ this.removeFilter(name);+ });++ this.addActionHandler('reset', () => this.resetFilters());+ this.addActionHandler('refresh', () => this.refresh());++ this.addActionHandler('selectPreset', (_, target) => {+ const presetName = target.dataset.name || null;++ this.selectPreset(presetName);+ });++ this.addHandler('click', '.dropdown-menu a[data-action="savePreset"]', () => this.savePresetHandler())++ this.addHandler('click', '.dropdown-menu a[data-action="removePreset"]', async () => {+ await this.confirm({message: this.translate('confirmation', 'messages')});++ this.removePreset(this.presetName!);+ });++ this.addHandler('change', '.search-row ul.filter-menu input[data-role="boolFilterCheckbox"]', (e) => {+ e.stopPropagation();++ this.search();+ this.manageLabels();+ });++ this.addActionHandler('switchViewMode', (_, target) => {+ const mode = target.dataset.name as string;++ if (mode === this.viewMode) {+ return;+ }++ this._setViewMode(mode, false, true);+ });++ this.addHandler('keyup', 'input.field-filter-quick-search-input', (_, target) => {+ this.processFieldFilterQuickSearch((target as HTMLInputElement).value);+ });++ this.addHandler('keydown', 'input.field-filter-quick-search-input', (e) => {+ if (!(e instanceof KeyboardEvent)) {+ return;+ }++ if (e.code === 'Enter') {+ this.addFirstFieldFilter();++ return;+ }++ if (e.code === 'Escape') {+ this.closeAddFieldDropdown();+ }+ });+ }++ private setupPresetFilters() {if (this.primaryFiltersDisabled) {this.presetFilterList = [];return;}- const filterList = this.options.filterList ||- this.getMetadata().get(['clientDefs', this.scope, 'filterList']) || [];+ const filterList = (this.options.filterList ||+ this.getMetadata().get(['clientDefs', this.scope, 'filterList']) || []) as (string | Record<string, any>)[];this.presetFilterList = filterList.filter(item => {if (typeof item === 'string') {@@ -286,7 +487,7 @@ class SearchView extends View {}if (item.accessDataList) {- if (!Espo.Utils.checkAccessDataList(item.accessDataList, this.getAcl(), this.getUser())) {+ if (!Utils.checkAccessDataList(item.accessDataList, this.getAcl(), this.getUser())) {return false;}}@@ -300,24 +501,25 @@ class SearchView extends View {});}- ((this.getPreferences().get('presetFilters') || {})[this.scope] || [])- .forEach(item => {- this.presetFilterList.push(item);- });+ const presets = ((this.getPreferences().get('presetFilters') ?? {})[this.scope] ?? []) as string[];++ presets.forEach(item => {+ this.presetFilterList.push(item);+ });}- setupViewModeDataList() {+ private setupViewModeDataList() {if (!this.viewModeList) {return [];}- const list = [];+ const list: any = [];this.viewModeList.forEach(item => {const o = {name: item,title: this.translate(item, 'listViewModes'),- iconClass: this.viewModeIconClassMap[item]+ iconClass: this.viewModeIconClassMap[item] ?? null,};list.push(o);@@ -326,19 +528,23 @@ class SearchView extends View {this.viewModeDataList = list;}- setViewMode(mode, preventLoop, toTriggerEvent) {+ /**+ * Set a view mode.+ */+ setViewMode(mode: string) {+ this._setViewMode(mode);+ }++ private _setViewMode(mode: string, preventLoop?: boolean, toTriggerEvent?: boolean) {this.viewMode = mode;if (this.isRendered()) {this.$el.find('[data-action="switchViewMode"]').removeClass('active');- this.$el.find('[data-action="switchViewMode"][data-name="'+mode+'"]').addClass('active');- }- else {- if (this.isBeingRendered() && !preventLoop) {- this.once('after:render', () => {- this.setViewMode(mode, true);- });- }+ this.$el.find(`[data-action="switchViewMode"][data-name="${mode}"]`).addClass('active');+ } else if (this.isBeingRendered() && !preventLoop) {+ this.once('after:render', () => {+ this._setViewMode(mode, true);+ });}this.collection.offset = 0;@@ -348,26 +554,27 @@ class SearchView extends View {}}- hasLeftDropdown() {+ private hasLeftDropdown(): boolean {if (this.primaryFiltersDisabled && !this.boolFilterList.length) {return false;}- return this.presetFilterList.length ||+ return !!(+ this.presetFilterList.length ||this.boolFilterList.length ||- Object.keys(this.advanced || {}).length;+ Object.keys(this.advanced || {}).length+ );}- handleLeftDropdownVisibility() {+ private handleLeftDropdownVisibility() {if (this.hasLeftDropdown()) {- this.$leftDropdown.removeClass('hidden');- }- else {- this.$leftDropdown.addClass('hidden');+ this.leftDropdownElement?.classList.remove('hidden');+ } else {+ this.leftDropdownElement?.classList.add('hidden');}}- createFilters(callback) {+ private createFilters(callback?: () => void) {let i = 0;const count = Object.keys(this.advanced || {}).length;@@ -378,7 +585,7 @@ class SearchView extends View {}for (const field in this.advanced) {- this.createFilter(field, this.advanced[field], () => {+ this.createFilter(field, this.advanced[field]!, () => {i++;if (i === count) {@@ -390,135 +597,17 @@ class SearchView extends View {}}- events = {- /** @this SearchView */- 'keydown input[data-name="textFilter"]': function (e) {- const key = Espo.Utils.getKeyFromKeyEvent(e);-- if (e.key === 'Enter' || key === 'Enter' || key === 'Control+Enter') {- this.search();-- this.hideApplyFiltersButton();- }- },- /** @this SearchView */- 'focus input[data-name="textFilter"]': function (e) {- e.currentTarget.select();- },- /** @this SearchView */- 'click .advanced-filters-apply-container a[data-action="applyFilters"]': function () {- this.search();- this.hideApplyFiltersButton();-- this.$el.find('button.search').focus();- },- /** @this SearchView */- 'click button[data-action="search"]': function () {- this.search();- this.hideApplyFiltersButton();- },- /** @this SearchView */- 'click a[data-action="addFilter"]': function (e) {- const $target = $(e.currentTarget);- const name = $target.data('name');-- $target.closest('li').addClass('hidden');-- this.addFilter(name);- },- /** @this SearchView */- 'click .advanced-filters a.remove-filter': function (e) {- const $target = $(e.currentTarget);-- const name = $target.data('name');-- this.removeFilter(name);- },- /** @this SearchView */- 'click button[data-action="reset"]': function () {- this.resetFilters();- },- /** @this SearchView */- 'click button[data-action="refresh"]': function () {- this.refresh();- },- /** @this SearchView */- 'click a[data-action="selectPreset"]': function (e) {- const $target = $(e.currentTarget);-- const presetName = $target.data('name') || null;-- this.selectPreset(presetName);- },- /** @this SearchView */- 'click .dropdown-menu a[data-action="savePreset"]': function () {- this.createView('savePreset', 'views/modals/save-filters', {}, view => {- view.render();-- this.listenToOnce(view, 'save', (name) => {- this.savePreset(name);-- view.close();-- this.removeFilters();-- this.createFilters(() => {- this.render();- });- });- });- },- /** @this SearchView */- 'click .dropdown-menu a[data-action="removePreset"]': function () {- const id = this.presetName;-- this.confirm(this.translate('confirmation', 'messages'), () => {- this.removePreset(id);- });- },- /** @this SearchView */- 'change .search-row ul.filter-menu input[data-role="boolFilterCheckbox"]': function (e) {- e.stopPropagation();-- this.search();- this.manageLabels();- },- /** @this SearchView */- 'click [data-action="switchViewMode"]': function (e) {- const mode = $(e.currentTarget).data('name');-- if (mode === this.viewMode) {- return;- }-- this.setViewMode(mode, false, true);- },- /** @this SearchView */- 'keyup input.field-filter-quick-search-input': function (e) {- this.processFieldFilterQuickSearch(e.currentTarget.value);- },- /** @this SearchView */- 'keydown input.field-filter-quick-search-input': function (e) {- if (e.code === 'Enter') {- this.addFirstFieldFilter();-- return;- }-- if (e.code === 'Escape') {- this.closeAddFieldDropdown();- }- },- }-- removeFilter(name) {- this.$el.find('ul.filter-list li[data-name="' + name + '"]').removeClass('hidden');+ private removeFilter(name: string) {+ this.element.querySelector(`ul.filter-list li[data-name="${name}"]`)+ ?.classList.remove('hidden');- const container = this.getView('filter-' + name).$el.closest('div.filter');+ //+ const container = this.getView(`filter-${name}`)?.element?.closest('div.filter');+ //.$el.closest('div.filter');- this.clearView('filter-' + name);+ this.clearView(`filter-${name}`);- container.remove();+ container?.remove();delete this.advanced[name];@@ -536,7 +625,7 @@ class SearchView extends View {this.showApplyFiltersButton() :this.showResetFiltersButton();- this.$applyFilters.focus();+ this.applyFiltersElement.focus();return;}@@ -546,7 +635,7 @@ class SearchView extends View {}}- addFilter(name) {+ private addFilter(name: string) {this.advanced[name] = {};this.presetName = this.primary;@@ -557,7 +646,7 @@ class SearchView extends View {this.fetch();this.updateSearch();- if (view.getFieldView().initialSearchIsNotIdle) {+ if (view.getFieldView()?.initialSearchIsNotIdle) {this.showApplyFiltersButton();}});@@ -569,18 +658,18 @@ class SearchView extends View {this.controlResetButtonVisibility();}- refresh() {- Espo.Ui.notifyWait();+ private refresh() {+ Ui.notifyWait();this.collection.abortLastFetch();this.collection.reset();this.collection.fetch().then(() => {- Espo.Ui.notify(false);+ Ui.notify(false);});}- selectPreset(presetName, forceClearAdvancedFilters) {+ private selectPreset(presetName: string | null, forceClearAdvancedFilters?: boolean) {const wasPreset = !(this.primary === this.presetName);this.presetName = presetName;@@ -599,28 +688,25 @@ class SearchView extends View {this.updateSearch();this.manageLabels();- this.createFilters(() => {- this.reRender()- .then(() => {- // noinspection JSUnresolvedReference- this.$el.find('.filters-button')- .get(0)- .focus({preventScroll: true});- })+ this.createFilters(async () => {+ await this.reRender();++ this.element.querySelector<HTMLElement>('.filters-button')+ ?.focus({preventScroll: true});});this.updateCollection();}- removeFilters() {- this.$advancedFiltersPanel.empty();+ private removeFilters() {+ this.advancedFiltersPanelElement.innerHTML = '';for (const name in this.advanced) {this.clearView('filter-' + name);}}- resetFilters() {+ private resetFilters() {this.trigger('reset');this.collection.resetOrderToDefault();@@ -632,7 +718,7 @@ class SearchView extends View {this.trigger('update-ui');}- savePreset(name) {+ private savePreset(name: string) {const id = 'f' + (Math.floor(Math.random() * 1000001)).toString();this.fetch();@@ -666,14 +752,14 @@ class SearchView extends View {this.presetName = id;}- removePreset(id) {+ private removePreset(id: string) {const presetFilters = this.getPreferences().get('presetFilters') || {};if (!(this.scope in presetFilters)) {presetFilters[this.scope] = [];}- let list;+ let list: any[];list = presetFilters[this.scope];@@ -705,43 +791,39 @@ class SearchView extends View {this.updateCollection();}- updateAddFilterButton() {- const $ul = this.$el.find('ul.filter-list');+ private updateAddFilterButton() {+ const noFields = !Array.from(this.filterListElement?.children ?? [])+ .some(li => {+ return !li.classList.contains('hidden') &&+ !li.classList.contains('dropdown-header') &&+ !li.classList.contains('quick-search-list-item');+ });- if (- $ul.children()- .not('.hidden')- .not('.dropdown-header')- .not('.quick-search-list-item').length === 0- ) {- this.$addFilterButton.addClass('disabled');- }- else {- this.$addFilterButton.removeClass('disabled');+ if (noFields) {+ this.addFilterButtonElement?.classList.add('disabled');+ } else {+ this.addFilterButtonElement?.classList.remove('disabled');}this.trigger('update-ui');}- afterRender() {- this.$filtersLabel = this.$el.find('.search-row span.filters-label');- this.$filtersButton = this.$el.find('.search-row button.filters-button');- this.$leftDropdown = this.$el.find('div.search-row div.left-dropdown');- this.$resetButton = this.$el.find('[data-action="reset"]');- this.$applyFiltersContainer = this.$el.find('.advanced-filters-apply-container');- this.$applyFilters = this.$applyFiltersContainer.find('[data-action="applyFilters"]');- /** @type {JQuery} */- this.$filterList = this.$el.find('ul.filter-list');- /** @type {JQuery} */- this.$fieldQuickSearch = this.$filterList.find('input.field-filter-quick-search-input');- /** @type {JQuery} */- this.$addFilterButton = this.$el.find('button.add-filter-button');- /** @type {JQuery} */- this.$textFilter = this.$el.find('input.text-filter');+ protected afterRender() {+ this.filtersLabel = this.element.querySelector<HTMLElement>('.search-row span.filters-label');+ this.applyFiltersContainer = this.element.querySelector('.advanced-filters-apply-container')!;+ this.applyFiltersElement = this.applyFiltersContainer.querySelector('[data-action="applyFilters"]')!;+ this.filtersButton = this.element.querySelector<HTMLButtonElement>('.search-row button.filters-button')!;+ this.leftDropdownElement = this.element.querySelector('div.search-row div.left-dropdown');+ this.resetButtonElement = this.element.querySelector('[data-action="reset"]');+ this.filterListElement = this.element.querySelector<HTMLUListElement>('ul.filter-list');+ this.fieldQuickSearchInput = this.filterListElement+ ?.querySelector<HTMLInputElement>('input.field-filter-quick-search-input') ?? null;+ this.addFilterButtonElement = this.element.querySelector<HTMLButtonElement>('button.add-filter-button');+ this.textFilterInputElement = this.element.querySelector<HTMLInputElement>('input.text-filter');this.updateAddFilterButton();- this.$advancedFiltersPanel = this.$el.find('.advanced-filters');+ this.advancedFiltersPanelElement = this.element.querySelector<HTMLElement>('.advanced-filters')!;this.manageLabels();this.controlResetButtonVisibility();@@ -749,12 +831,12 @@ class SearchView extends View {this.initTextSearchAutocomplete();}- initTextSearchAutocomplete() {- if (this.textSearchStoringDisabled) {+ private initTextSearchAutocomplete() {+ if (this.textSearchStoringDisabled || !this.textFilterInputElement) {return;}- const autocomplete = new Autocomplete(this.$textFilter.get(0), {+ const autocomplete = new Autocomplete(this.textFilterInputElement, {triggerSelectOnValidInput: false,focusOnSelect: true,onSelect: () => {@@ -767,6 +849,7 @@ class SearchView extends View {);},formatResult: item => {+ // @todo Refactor.return $('<span>').append($('<a>')@@ -779,9 +862,10 @@ class SearchView extends View {$('<span>').text(item.value))- .get(0).innerHTML;+ .get(0)!.innerHTML as string;},beforeRender: container => {+ // @todo Refactor.const $container = $(container);$container.addClass('text-search-suggestions');@@ -790,11 +874,12 @@ class SearchView extends View {e.preventDefault();const text = e.currentTarget.getAttribute('data-value');- this.storedTextSearchHelper.remove(text);+ this.storedTextSearchHelper?.remove(text as string);autocomplete.hide();// 200 is hardcoded in autocomplete lib.- setTimeout(() => this.$textFilter.focus(), 201);++ setTimeout(() => this.textFilterInputElement?.focus(), 201);});},});@@ -802,40 +887,55 @@ class SearchView extends View {this.once('render remove', () => autocomplete.dispose());}- initQuickSearchUi() {- this.$addFilterButton.parent().on('show.bs.dropdown', () => {+ private initQuickSearchUi() {+ if (!this.addFilterButtonElement) {+ return;+ }++ const parent = this.addFilterButtonElement.parentElement;++ // @ts-ignore+ $(parent).on('show.bs.dropdown', () => {setTimeout(() => {- this.$fieldQuickSearch.focus();+ if (!this.fieldQuickSearchInput) {+ return;+ }- const width = this.$fieldQuickSearch.outerWidth();+ this.fieldQuickSearchInput.focus();- this.$fieldQuickSearch.css('minWidth', width);+ const width = this.fieldQuickSearchInput?.offsetWidth;++ this.fieldQuickSearchInput.style.minWidth = width.toString() + 'px';}, 1);});- this.$addFilterButton.parent().on('hide.bs.dropdown', () => {+ // @ts-ignore+ $(parent).on('hide.bs.dropdown', () => {this.resetFieldFilterQuickSearch();- this.$fieldQuickSearch.css('minWidth', '');+ this.fieldQuickSearchInput!.style.minWidth = '';});}- manageLabels() {- this.$el.find('ul.dropdown-menu > li.preset-control').addClass('hidden');+ private manageLabels() {+ this.element.querySelectorAll<HTMLLIElement>('ul.dropdown-menu > li.preset-control')+ .forEach(li => li.classList.add('hidden'))this.currentFilterLabelList = [];this.managePresetFilters();this.manageBoolFilters();- this.$filtersLabel.html(this.currentFilterLabelList.join(' · '));+ if (!this.filtersLabel) {+ return;+ }++ this.filtersLabel.innerHTML = this.currentFilterLabelList+ .map(it => this.getHelper().escapeString(it))+ .join(' · ');}- /**- * @private- * @return {boolean}- */- toShowResetButton() {+ private toShowResetButton(): boolean {if (this.textFilter) {return true;}@@ -859,45 +959,49 @@ class SearchView extends View {return false;}- controlResetButtonVisibility() {+ private controlResetButtonVisibility() {+ if (!this.resetButtonElement) {+ return;+ }+if (this.toShowResetButton()) {- this.$resetButton.css('visibility', 'visible');+ this.resetButtonElement.style.visibility = 'visible'return;}- this.$resetButton.css('visibility', 'hidden');+ this.resetButtonElement.style.visibility = 'hidden';}- managePresetFilters() {+ private managePresetFilters() {let presetName = this.presetName || null;const primary = this.primary;this.$el.find('ul.filter-menu a.preset span').remove();let filterLabel = this.translate('all', 'presetFilters', this.entityType);- let filterStyle = 'default';+ let filterStyle: string | null = 'default';if (!presetName && primary) {presetName = primary;}if (presetName && presetName !== primary) {- this.$advancedFiltersPanel.addClass('hidden');+ this.advancedFiltersPanelElement.classList.add('hidden');let label = null;let style = 'default';let id = null;this.presetFilterList.forEach(item => {- if (item.name === presetName) {+ if (typeof item !== 'string' && item.name === presetName) {label = item.label || false;style = item.style || 'default';id = item.id;}});- label = label || this.translate(this.presetName, 'presetFilters', this.entityType);+ label = label || this.translate(this.presetName!, 'presetFilters', this.entityType);filterLabel = label;filterStyle = style;@@ -906,9 +1010,8 @@ class SearchView extends View {this.$el.find('ul.dropdown-menu > li.divider.preset-control').removeClass('hidden');this.$el.find('ul.dropdown-menu > li.preset-control.remove-preset').removeClass('hidden');}- }- else {- this.$advancedFiltersPanel.removeClass('hidden');+ } else {+ this.advancedFiltersPanelElement.classList.remove('hidden');if (Object.keys(this.advanced).length !== 0) {if (!this.disableSavePreset) {@@ -927,16 +1030,12 @@ class SearchView extends View {}}- this.currentFilterLabelList.push(filterLabel);+ this.currentFilterLabelList!.push(filterLabel);- this.$filtersButton- .removeClass('btn-default')- .removeClass('btn-primary')- .removeClass('btn-danger')- .removeClass('btn-success')- .removeClass('btn-info');+ this.filtersButton.classList+ .remove('btn-default', 'btn-primary', 'btn-danger', 'btn-success', 'btn-info', 'btn-info');- this.$filtersButton.addClass('btn-' + filterStyle);+ this.filtersButton.classList.add(`btn-${filterStyle}`);presetName = presetName || '';@@ -946,11 +1045,11 @@ class SearchView extends View {}manageBoolFilters() {- (this.boolFilterList || []).forEach((item) => {- if (this.bool[item]) {+ (this.boolFilterList ?? []).forEach((item) => {+ if (this.bool && this.bool[item]) {const label = this.translate(item, 'boolFilters', this.entityType);- this.currentFilterLabelList.push(label);+ this.currentFilterLabelList!.push(label);}});}@@ -969,12 +1068,12 @@ class SearchView extends View {return Object.keys(this.advanced).length > 0;}- getFilterDataList() {+ private getFilterDataList() {const list = [];for (const field in this.advanced) {list.push({- key: 'filter-' + field,+ key: `filter-${field}`,name: field,});}@@ -982,63 +1081,64 @@ class SearchView extends View {return list;}- updateCollection() {+ private async updateCollection() {this.collection.abortLastFetch();this.collection.reset();this.collection.where = this.searchManager.getWhere();this.collection.offset = 0;- Espo.Ui.notifyWait();+ Ui.notifyWait();- this.collection.fetch().then(() => {- Espo.Ui.notify(false);- });+ await this.collection.fetch();++ Ui.notify(false);}- getPresetFilterList() {- const arr = [];+ private getPresetFilterList(): PresetFilter[] {+ const output: any = [];- this.presetFilterList.forEach((item) => {+ this.presetFilterList.forEach(item => {if (typeof item == 'string') {item = {name: item};}- arr.push(item);+ output.push(item);});- return arr;+ return output;}- getPresetData() {+ private getPresetData() {let data = {};this.getPresetFilterList().forEach(item => {if (item.name === this.presetName) {- data = Espo.Utils.clone(item.data || {});+ data = Utils.clone(item.data || {});}});return data;}- getPrimaryFilterName() {+ private getPrimaryFilterName() {let primaryFilterName = null;this.getPresetFilterList().forEach(item => {- if (item.name === this.presetName) {- if (!('data' in item)) {- primaryFilterName = item.name;- }- else if (item.primary) {- primaryFilterName = item.primary;- }+ if (item.name !== this.presetName) {+ return;+ }++ if (!('data' in item)) {+ primaryFilterName = item.name;+ } else if (item.primary) {+ primaryFilterName = item.primary;}});return primaryFilterName;}- getPrimaryFilterStyle() {+ private getPrimaryFilterStyle(): string | null {let style = null;this.getPresetFilterList().forEach(item => {@@ -1050,19 +1150,19 @@ class SearchView extends View {return style;}- loadSearchData() {+ private loadSearchData() {const searchData = this.searchManager.get();- this.textFilter = searchData.textFilter;+ this.textFilter = searchData.textFilter ?? '';if ('presetName' in searchData) {- this.presetName = searchData.presetName;+ this.presetName = searchData.presetName ?? null;}let primaryIsSet = false;if ('primary' in searchData) {- this.primary = searchData.primary;+ this.primary = searchData.primary ?? null;if (!this.presetName) {this.presetName = this.primary;@@ -1072,31 +1172,26 @@ class SearchView extends View {}if (this.presetName) {- this.advanced = _.extend(Espo.Utils.clone(this.getPresetData()), searchData.advanced);+ this.advanced = _.extend(Utils.clone(this.getPresetData()), searchData.advanced);if (!primaryIsSet) {this.primary = this.getPrimaryFilterName();}- }- else {- this.advanced = Espo.Utils.clone(searchData.advanced);+ } else {+ this.advanced = Utils.clone(searchData.advanced ?? {});}- this.bool = searchData.bool;+ this.bool = searchData.bool ?? null;}- /**- * @callback SearchView~createFilterCallback- * @param {module:views/search/filter} view- */- /**- * @param {string} name- * @param {Object.<string, *>} params- * @param {SearchView~createFilterCallback} callback- * @param {boolean} [noRender]- */- async createFilter(name, params, callback, noRender) {+ private async createFilter(+ name: string,+ params: Record<string, any>,+ callback: CreateFilterCallback,+ noRender?: boolean,+ ) {+params = params || {};let rendered = false;@@ -1104,8 +1199,13 @@ class SearchView extends View {if (this.isRendered()) {rendered = true;- this.$advancedFiltersPanel.append(- `<div data-name="${name}" class="filter filter-${name}" />`+ this.advancedFiltersPanelElement.append(+ (() => {+ const div = document.createElement('div');+ div.dataset.name = name;+ div.className = `filter filter-${name}`+ return div;+ })());}@@ -1129,7 +1229,7 @@ class SearchView extends View {let toShowApply = this.isSearchedWithAdvancedFilter;if (!toShowApply) {- const data = view.getFieldView().fetchSearch();+ const data = view.getFieldView()?.fetchSearch();if (data) {toShowApply = true;@@ -1149,43 +1249,48 @@ class SearchView extends View {});}- fetch() {- this.textFilter = (this.$el.find('input[data-name="textFilter"]').val() || '').trim();+ private fetch() {+ let value = this.textFilterInputElement?.value ?? '';+ value = value.trim();++ this.textFilter = value;this.bool = {};this.boolFilterList.forEach(name => {- this.bool[name] = this.$el- .find('input[data-name="' + name + '"][data-role="boolFilterCheckbox"]')- .prop('checked');+ this.bool![name] = this.element+ .querySelector<HTMLInputElement>(`input[data-name="${name}"][data-role="boolFilterCheckbox"]`)+ ?.checked == true;});for (const field in this.advanced) {- const view = /** @type {module:views/fields/base} */- this.getView('filter-' + field).getView('field');+ const view = this.getView(`filter-${field}`)+ ?.getView<BaseFieldView>('field');++ if (!view) {+ continue;+ }this.advanced[field] = view.fetchSearch();- view.searchParams = Espo.Utils.clone(this.advanced[field] || {});+ view.setSearchParams(Utils.clone(this.advanced[field] ?? {}));}}- updateSearch() {+ private updateSearch() {this.searchManager.set({textFilter: this.textFilter,- advanced: this.advanced,- bool: this.bool,- presetName: this.presetName,+ advanced: this.advanced as Record<string, AdvancedFilter>,+ bool: this.bool ?? {},+ presetName: this.presetName ?? null,primary: this.primary,});}- getFilterFieldDataList() {+ private getFilterFieldDataList() {const defs = [];- for (const i in this.fieldFilterList) {- const field = this.fieldFilterList[i];-+ for (const field of this.fieldFilterList!) {const o = {name: field,checked: (field in this.advanced),@@ -1198,35 +1303,34 @@ class SearchView extends View {return defs;}- showResetFiltersButton() {+ private showResetFiltersButton() {this.toShowApplyFiltersButton = true;this.toShowResetFiltersText = true;- this.$applyFiltersContainer.removeClass('hidden');-- this.$applyFiltersContainer.find('.text-apply').addClass('hidden');- this.$applyFiltersContainer.find('.text-reset').removeClass('hidden');+ this.applyFiltersContainer.classList.remove('hidden');+ this.applyFiltersContainer.querySelector('.text-apply')?.classList.add('hidden');+ this.applyFiltersContainer.querySelector('.text-reset')?.classList.remove('hidden');}- showApplyFiltersButton() {+ private showApplyFiltersButton() {this.toShowApplyFiltersButton = true;this.toShowResetFiltersText = false;- this.$applyFiltersContainer.removeClass('hidden');+ this.applyFiltersContainer.classList.remove('hidden');- this.$applyFiltersContainer.find('.text-reset').addClass('hidden');- this.$applyFiltersContainer.find('.text-apply').removeClass('hidden');+ this.applyFiltersContainer.querySelector('.text-reset')?.classList.add('hidden');+ this.applyFiltersContainer.querySelector('.text-apply')?.classList.remove('hidden');}- hideApplyFiltersButton() {+ private hideApplyFiltersButton() {this.toShowApplyFiltersButton = false;this.toShowResetFiltersText = false;- this.$applyFiltersContainer.addClass('hidden');+ this.applyFiltersContainer.classList.add('hidden');}selectPreviousPreset() {- const list = Espo.Utils.clone(this.getPresetFilterList());+ const list = Utils.clone(this.getPresetFilterList());list.unshift({name: null});@@ -1246,7 +1350,7 @@ class SearchView extends View {}selectNextPreset() {- const list = Espo.Utils.clone(this.getPresetFilterList());+ const list = Utils.clone(this.getPresetFilterList());list.unshift({name: null});@@ -1265,26 +1369,21 @@ class SearchView extends View {this.selectPreset(preset.name);}- /**- * @private- * @param {string} text- */- processFieldFilterQuickSearch(text) {+ private processFieldFilterQuickSearch(text: string) {text = text.trim();text = text.toLowerCase();- /** @type {JQuery} */- const $li = this.$filterList.find('li.filter-item');+ const lis = this.filterListElement!.querySelectorAll<HTMLLIElement>('li.filter-item');if (text === '') {- $li.removeClass('search-hidden');+ lis.forEach(element => element.classList.remove('search-hidden'));return;}- $li.addClass('search-hidden');+ lis.forEach(element => element.classList.add('search-hidden'));- this.fieldFilterList.forEach(field => {+ this.fieldFilterList!.forEach(field => {let label = this.fieldFilterTranslations[field] || field;label = label.toLowerCase();@@ -1299,40 +1398,57 @@ class SearchView extends View {}if (matched) {- $li.filter(`[data-name="${field}"]`).removeClass('search-hidden');+ Array.from(lis)+ .filter(li => li.dataset.name === field)+ .forEach(li => li.classList.remove('search-hidden'));}});}- resetFieldFilterQuickSearch() {- this.$fieldQuickSearch.val('');- this.$filterList.find('li.filter-item').removeClass('search-hidden');+ private resetFieldFilterQuickSearch() {+ if (!this.fieldQuickSearchInput) {+ return;+ }++ this.fieldQuickSearchInput.value = ''++ this.filterListElement?.querySelectorAll('li.filter-item')+ .forEach(li => li.classList.remove('search-hidden'));}- addFirstFieldFilter() {- const $first = this.$filterList.find('li.filter-item:not(.hidden):not(.search-hidden)').first();+ private addFirstFieldFilter() {+ const first = this.filterListElement+ ?.querySelectorAll<HTMLLIElement>('li.filter-item:not(.hidden):not(.search-hidden)')[0] ?? null;- if (!$first.length) {+ if (!first) {return;}- const name = $first.attr('data-name');+ const name = first.dataset.name!;- $first.addClass('hidden');+ first.classList.add('hidden');this.closeAddFieldDropdown();this.addFilter(name);this.resetFieldFilterQuickSearch();}- closeAddFieldDropdown() {- // noinspection JSUnresolvedReference- this.$addFilterButton.parent()- .find('[data-toggle="dropdown"]')- .dropdown('toggle');+ private closeAddFieldDropdown() {+ if (!this.addFilterButtonElement) {+ return;+ }++ const dropdown = this.addFilterButtonElement.parentElement?.querySelector('[data-toggle="dropdown"]');++ if (!dropdown) {+ return;+ }++ // @ts-ignore+ $(dropdown).dropdown('toggle');}- storeTextSearch() {+ private storeTextSearch() {if (!this.textFilter) {return;}@@ -1343,6 +1459,22 @@ class SearchView extends View {this.storedTextSearchHelper.store(this.textFilter);}++ private async savePresetHandler() {+ const view = new SaveFiltersModalView();++ await this.assignView('savePreset', view);++ this.listenToOnce(view, 'save', (name: string) => {+ this.savePreset(name);++ view.close();+ this.removeFilters();+ this.createFilters(() => this.render());+ });++ await view.render();+ }}export default SearchView;