From a78ef2df393e332a18129501b19ac1caf8d75d00 Mon Sep 17 00:00:00 2001 From: cl Date: Wed, 25 Nov 2026 17:00:03 +0800 Subject: [PATCH] isPromiseLike and resolve partial of Grid. --- lib/app/communications/customer.js | 11 +- lib/global.d.ts | 11 +- lib/types.d.ts | 942 ++++++++++++++++++++++++++++- lib/ui/grid/column.js | 197 +++--- lib/ui/grid/grid.js | 788 +++++++++--------------- lib/ui/popup.js | 15 +- lib/utility.js | 14 + 7 files changed, 1359 insertions(+), 619 deletions(-) diff --git a/lib/app/communications/customer.js b/lib/app/communications/customer.js index ac590f3..95c968d 100644 --- a/lib/app/communications/customer.js +++ b/lib/app/communications/customer.js @@ -1,5 +1,5 @@ import { Grid, GridColumn, createElement, setTooltip, createIcon, createCheckbox, createRadiobox, showAlert, showConfirm, Popup, requestAnimationFrame } from "../../ui"; -import { r as lang, nullOrEmpty, formatUrl, escapeEmoji, isEmail, isPhone } from "../../utility"; +import { r as lang, nullOrEmpty, formatUrl, escapeEmoji, isEmail, isPhone, isPromiseLike } from "../../utility"; import { createBox, appendMedia, fileSupported, insertFile, getMessageSendTo, getMessageStatus, updateCustomerName, createHideMessageTitleButton, createHideMessageCommentTail } from "./lib"; import { Contact, CustomerRecordContact } from "./contact"; import Follower from "./follower"; @@ -764,7 +764,7 @@ export default class CustomerCommunication { if (typeof option.onOpenSelectCRContacts === 'function') { const result = option.onOpenSelectCRContacts(); - if (typeof result?.then === 'function') { + if (isPromiseLike(result)) { return result.then(r => { r.map(c => { for (let cc of this._var.data.contacts) { @@ -822,7 +822,7 @@ export default class CustomerCommunication { } if (typeof option.onSave === 'function') { const result = option.onSave(item, true); - if (typeof result?.then === 'function') { + if (isPromiseLike(result)) { return result.then(r => { this._var.gridContact.source = r.filter(c => c.Id >= 0).map(c => { if (c.OptOut || c.OptOut_BC) { @@ -944,7 +944,7 @@ export default class CustomerCommunication { } if (typeof option.onSave === 'function') { const result = option.onSave(item); - if (typeof result?.then === 'function') { + if (isPromiseLike(result)) { return result.then(r => { This._var.gridContact.source = r.filter(c => c.Id >= 0).map(c => { if (c.OptOut || c.OptOut_BC) { @@ -1205,9 +1205,10 @@ export default class CustomerCommunication { onOk: list => { if (typeof option.onAddFollower === 'function') { const result = option.onAddFollower(list); - if (typeof result?.then === 'function') { + if (isPromiseLike(result)) { return result.then(r => { // this.followers = r; + // TODO: ?? maybe a bug? doing nothing... return r; }); } diff --git a/lib/global.d.ts b/lib/global.d.ts index 28985dc..4685c8d 100644 --- a/lib/global.d.ts +++ b/lib/global.d.ts @@ -4,11 +4,12 @@ declare global { interface Window { GetTextByKey?: (key: string, defaultValue?: string | null) => string; consts?: { - resver: number, - path: string, - prefix: string, - cookie?: { lang: string }, - user?: { language: string } + resver: number; + path: string; + prefix: string; + modulePath?: string; + cookie?: { lang: string }; + user?: { language: string }; }; _network?: { root: string }; _net?: { root: string }; diff --git a/lib/types.d.ts b/lib/types.d.ts index a57fde4..10ed38c 100644 --- a/lib/types.d.ts +++ b/lib/types.d.ts @@ -1,3 +1,5 @@ +import { GridColumn } from "./ui"; + export type GetTextCallback = (key: string, defaultValue?: string | null) => string; export interface LanguageResource { @@ -83,7 +85,7 @@ export interface Popup { close(result?: any, animation?: boolean): void; create(): HTMLDivElement; - show(parent?: HTMLElement, hidden?: boolean): Promise | undefined; + show(parent?: HTMLElement, hidden?: boolean): PromiseLike | undefined; } export interface PopupButton { @@ -98,7 +100,7 @@ export interface PopupButton { * @param button 触发的按钮 * @returns 返回 false 则阻止窗口关闭 */ - trigger?: (this: PopupButton, popup: Popup) => boolean | string | number | Promise | undefined; + trigger?: (this: PopupButton, popup: Popup) => boolean | string | number | PromiseLike | undefined; } export interface PopupOptions { @@ -291,9 +293,943 @@ export interface DropdownOptions { /** 是否固定为向下展开 */ slideFixed?: boolean; /** 父元素,默认添加到头元素之后 */ - wrapper?: HTMLElement; + wrapper?: HTMLElement | null; /** 是否忽略 All 选项 */ ignoreAll?: boolean; /** 获取文本的代理函数 */ getText?: GetTextCallback; } + +export interface ValueItem { + Value: any; + DisplayValue: string; + __checked?: boolean; +} + +export type GridRowItem = Record; + +export interface GridSourceItemBase { + value?: string; + text?: string; +} +export type GridSourceItem = GridSourceItemBase & Record; + +export interface GridExpandableObject { + element: HTMLElement; +} + +export type GridExpandableObjectCallback = (this: Grid, item: GridRowItem) => GridExpandableObject; + +/** 行数据包装接口 */ +export interface GridItemWrapper { + /** 真实数据对象 */ + values: GridRowItem; + /** 下拉数据源缓存对象 */ + source?: Record; + /** 缩进层级 */ + __level: number; + /** 行索引 */ + __index?: number; + /** 批量删除时暂存的索引偏移量 */ + __offset?: number; + /** 正在编辑的列的原始值字典 */ + __editing?: Record; + /** 行数据是否发生改变 */ + __changed?: boolean; + /** 行是否已展开 */ + __expanded?: boolean; + /** 行扩展对象 */ + __expandable_object?: GridExpandableObject; +} + +/** + * 列定义基类 + * + * _函数调用流程图示_
+ * Column Refresh + * @static + * @hideconstructor + */ +export interface GridColumn { + /** + * 该属性返回 `true` 后,在任意事件中修改行包装对象的 `__editing` 值,则会在行列元素变动时及时触发 [onChanged]{@linkcode GridColumnDefinition#onChanged} 方法,避免例如文本框和日期框还未触发事件就被移除元素而导致的问题 + * + * @see 更多例子参考 {@linkcode GridInputColumn} {@linkcode GridDateColumn} 中的代码实现 + */ + static readonly editing?: boolean; + /** 标记该类型是否可编辑 */ + static readonly canEdit?: boolean; + /** 标记该类型是否支持列头批量操作 */ + static readonly headerEditing?: boolean; + + /** + * 创建显示单元格时调用的方法 + * @param col 列定义对象 + * @param index 行元素索引(需要配合 [startIndex]{@linkcode Grid#startIndex} 相加得到真实数据索引) + * @param grid Grid 实例 + * @returns 返回创建的单元格元素 + * @virtual + */ + static create(col: GridColumnDefinition, index: number, grid: Grid): HTMLElement; + + /** + * 创建编辑单元格时调用的方法 + * + * 元素修改后设置行包装对象的 `__editing` 后,支持在离开编辑状态时及时触发 [leaveEdit]{@linkcode GridColumn.leaveEdit} 方法
+ * 更多例子参考代码中 {@linkcode GridDropdownColumn} 的实现。 + * @param trigger 编辑事件回调函数,参数会传递给 [getValue]{@linkcode GridColumn.getValue} 方法 + * @param col 列定义对象 + * @param container 父容器元素 + * @param wrapper 行包装对象,其 `values` 属性为行数据对象 + * @returns 返回创建的编辑状态的单元格元素 + * @virtual + */ + static createEdit?(trigger: (e: any) => void, col: GridColumnDefinition, container?: HTMLElement, wrapper?: GridItemWrapper): HTMLElement; + + /** + * 创建列头时调用的方法 + * @param col 列定义对象 + * @returns 返回创建的列头元素 + * @virtual + */ + static createCaption?(col: GridColumnDefinition): HTMLElement; + + /** + * 获取用于判断文本大小的元素 + * @param element 单元格主内容元素 + * @returns 返回文本元素 + * @virtual + */ + static getElement?(element: HTMLElement): Element; + + /** + * 获取编辑状态单元格值时调用的方法 + * @param e 由 [createEdit]{@linkcode GridColumn.createEdit} 方法中 `trigger` 函数传递来的对象 + * @param col 列定义对象 + * @returns 返回单元格的值 + * @virtual + */ + static getValue?(e: any, col: GridColumnDefinition): TValue; + + /** + * 设置单元格值时调用的方法 + * @param element 单元格元素 + * @param val 待设置的单元格值 + * @param wrapper 行包装对象 + * @param col 列定义对象 + * @param grid Grid 对象 + * @virtual + */ + static setValue(element: HTMLElement, val: TValue, wrapper: GridItemWrapper, col: GridColumnDefinition, grid: Grid): void; + + /** + * 设置单元格样式时调用的方法 + * @param element 单元格元素 + * @param style 样式对象 + * @virtual + */ + static setStyle(element: HTMLElement, style: Record): void; + + /** + * 设置单元格类名时调用的方法 + * @param element 单元格元素 + * @param name 要设置的类名 + * @virtual + */ + static setClass(element: HTMLElement, name: string): void; + + /** + * 设置单元格可用性时调用的方法 + * @param element 单元格元素 + * @param enabled 启用值,为 `false` 时代表禁用 + * @param editing 是否处于编辑状态 + * @virtual + */ + static setEnabled(element: HTMLElement, enabled: boolean, editing: boolean): void; + + /** + * 单元格编辑状态发生改变时调用的方法 + * @param element 单元格元素 + * @param editing 是否处于编辑状态 + * @virtual + */ + static setEditing?(element: HTMLElement, editing: boolean): void; + + /** + * 单元格离开编辑元素时调用的方法,需要由行包装对象的 `__editing` 来确定是否触发。 + * @param element 单元格元素 + * @param container 父容器元素 + * @virtual + */ + static leaveEdit?(element: HTMLElement, container: HTMLElement): void; + + /** @ignore */ + static toString(): 'GridCommon'; +} + +export interface GridInputColumn extends GridColumn { + static readonly editing: true; + static readonly canEdit: true; + + static createEdit(trigger: (this: HTMLInputElement, e: Event) => any, col: GridColumnDefinition, container: HTMLElement, wrapper: GridItemWrapper): HTMLInputElement; + + /** @ignore */ + static toString(): 'GridInput'; +} + +export interface GridTextColumn extends GridInputColumn { + static createEdit(trigger: (this: HTMLTextAreaElement, ev: Event) => any, col: GridColumnDefinition, container: HTMLElement, wrapper: GridItemWrapper): HTMLTextAreaElement; + + /** @ignore */ + static toString(): 'GridText'; +} + +export interface GridDropdownColumn extends GridColumn { + static readonly canEdit: true; + + static createEdit(trigger: (this: Dropdown, it?: DropdownItem) => void, col: GridColumnDefinition, container: HTMLElement, wrapper: GridItemWrapper): HTMLDivElement; + static getElement(element: HTMLElement): Element; + static getValue(e: GridSourceItem, col: GridColumnDefinition): Required; + static leaveEdit(element: HTMLDivElement, container: HTMLElement): void; + + /** @ignore */ + static toString(): 'GridDropdown'; +} + +export interface GridCheckboxColumn extends GridColumn { + static readonly canEdit: true; + + static createEdit(trigger: (this: HTMLInputElement, ev: Event) => any, col: GridColumnDefinition): HTMLLabelElement; + static getValue(e: Event): boolean; + + /** @ignore */ + static toString(): 'GridCheckbox'; +} + +export interface GridRadioboxColumn extends GridCheckboxColumn { + /** @ignore */ + static toString(): 'GridRadiobox'; +} + +export interface GridIconColumn extends GridColumn { + /** @ignore */ + static toString(): 'GridIcon'; +} + +export interface GridDateColumn extends GridColumn { + static readonly editing: true; + static readonly canEdit: true; + + static createEdit(trigger: (this: HTMLInputElement, e: FocusEvent) => any, col: GridColumnDefinition, container: HTMLElement, wrapper: GridItemWrapper): HTMLElement; + static getValue(e: Event, col: GridColumnDefinition): string | GridSourceItemBase; + + /** + * 格式化日期字符串 + * @param date 要格式化的日期值 + * + * 支持以下几种数据类型 + * * `"2024-01-26"` + * * `"1/26/2024"` + * * `"638418240000000000"` + * * `new Date('2024-01-26')` + * @param formatter 格式化格式,默认为 `"m/d/Y"` + * + * * Y - 年,例如 `2024` + * * y - 年的后两位,例如 `"24"` + * * n - 月,例如 `2` + * * m - 格式化成两位的月,例如 `"02"` + * * j - 日,例如 `4` + * * d - 格式化成两位的日,例如 `"04"` + * * t - 日期当月总天数,例如 `29` + * * L - 是否为闰年,例如 `1` + * * G - 小时,例如 `15` + * * g - 12 小时制的小时,例如 `3` + * * H - 格式化成两位的小时,例如 `"15"` + * * h - 格式化成两位的 12 小时制的小时,例如 `"03"` + * * A - 上下午,例如 `"PM"` + * * a - 小写的上下午,例如 `"pm"` + * * i - 格式化成两位的分钟,例如 `"39"` + * * s - 格式化成两位的秒,例如 `"20"` + * * u - 格式化成六位的毫秒,例如 `"023040"` + * * e - 时区描述字符串,例如 `"China Standard Time"` + * * O - 时区偏移字符串,例如 `"+0800"` + * * P - `"+08:00"` 这种格式的时区偏移字符串 + * @returns 格式化为 M/d/yyyy 的日期字符串 + */ + static formatDate(date: string | number | Date, formatter: string): string; + + /** @ignore */ + static toString(): 'GridDate'; +} + +export interface GridColumnNameMap { + 0: GridColumn; + 1: GridInputColumn; + 2: GridDropdownColumn; + 3: GridCheckboxColumn; + 4: GridIconColumn; + 5: GridTextColumn; + 6: GridDateColumn; + 7: GridRadioboxColumn; +} + +type GridItemCallbackBase = (this: GridColumnDefinition, item: GridRowItem) => T; + +export type GridItemObjectCallback = GridItemCallbackBase>; +export type GridItemStringCallback = GridItemCallbackBase; + +interface GridColumnDefinitionBase { + /** 列关键字,默认以该关键字从行数据中提取单元格值,行数据的关键字属性值里包含 DisplayValue 则优先显示此值 */ + key: string; + /** + * 列的类型,可以为 {@linkcode GridColumn} 的子类,或者如下内置类型 {@linkcode Grid.ColumnTypes} + * * Grid.ColumnTypes.Common - 0: 通用列(只读) + * * Grid.ColumnTypes.Input - 1: 单行文本列 + * * Grid.ColumnTypes.Dropdown - 2: 下拉选择列 + * * Grid.ColumnTypes.Checkbox - 3: 复选框列 + * * Grid.ColumnTypes.Icon - 4: 图标列 + * * Grid.ColumnTypes.Text - 5: 多行文本列 + * * Grid.ColumnTypes.Date - 6: 日期选择列 + * * Grid.ColumnTypes.Radio - 7: 单选框列 + * @default Grid.ColumnTypes.Common + */ + type?: keyof GridColumnNameMap | typeof GridColumn; + /** 列标题文本 */ + caption?: string; + /** 列标题的元素样式 */ + captionStyle?: Record; + /** 列标题的帮助文本 */ + captionTooltip?: string; + /** 大于 0 则设置为该宽度,否则根据列内容自动调整列宽 */ + width?: number; + /** + * 列对齐方式 + * @default "left" + */ + align?: "left" | "center" | "right"; + /** + * 列是否可用(可编辑),允许以下类型 + * + * * `boolean` 则直接使用该值 + * * `string` 则以该值为关键字从行数据中取值作为判断条件 + * * 函数则调用回调,以返回值作为判断条件 + * @param item 行数据对象 + */ + enabled?: boolean | string | ((this: GridColumnDefinition, item: GridRowItem) => boolean); + /** + * 单元格取值采用该函数返回的值 + * @param item 行数据对象 + * @param editing 是否处于编辑状态 + * @param body Grid 控件的 `` 部分 + * @param index 所在行索引(不可依赖此值,除了呈现时,其他时候该值不会传递) + * @returns 返回过滤后的显示或编辑值 + */ + filter?: (this: GridColumnDefinition, item: GridRowItem, editing: boolean, body?: HTMLElement, index?: number) => ValueItem; + /** 单元格以该值填充内容,忽略 filter 与关键字属性 */ + text?: string; + /** + * 列是否可见 + * @default true + */ + visible?: boolean; + /** + * 列是否允许调整宽度 + * @default true + */ + resizable?: boolean; + /** + * 列是否允许排序 + * @default true + */ + sortable?: boolean; + /** + * 列是否允许重排顺序 + * @default true + */ + orderable?: boolean; + /** 列为复选框类型时是否在列头增加全选复选框 */ + allcheck?: boolean; + /** 列为收缩列,禁用自动调整大小 */ + shrink?: boolean; + /** 单元格元素的额外样式类型字符串(仅在重建行元素时设置) */ + class?: string; + /** 单元格文本是否换行(仅在重建行元素时设置) */ + contentWrap?: boolean; + /** 大于 0 时限制显示最大行数 */ + maxLines?: number; + /** 单元格css样式对象(仅在重建行元素时读取) */ + css?: Record; + /** 合计行样式(仅在重建合计行元素时读取) */ + totalCss?: Record; + /** 单元格样式(填充行列数据时读取),支持直接返回样式对象或调用函数返回 */ + style?: Record | GridItemObjectCallback; + /** 设置单元格背景色(填充行列数据时读取),支持直接设置颜色字符串或调用函数返回 */ + background?: string | GridItemStringCallback; + /** 复选框为 `ui-switch` 样式 *@since* 1.0.6 */ + switch?: boolean; + /** 根据返回值设置单元格元素的附加属性,允许直接设置对象也支持调用函数返回对象 */ + attrs?: Record | ((this: GridColumnDefinition, item: GridRowItem) => Record); + /** 给单元格元素附加事件(事件函数上下文为数据行对象) */ + events?: Record void>; + /** 是否允许进行列头过滤 */ + allowFilter?: boolean; + /** 过滤值的数组 */ + filterValues?: any[]; + /** 是否区分 `null` 与空字符串 */ + filterAllowNull?: boolean; + /** 自定义列过滤器的数据源,支持调用函数返回数据源 */ + filterSource?: ValueItem[] | ((this: Grid, col: GridColumnDefinition) => ValueItem[]); + /** 列头过滤强制使用 `Value` 字段 */ + filterAsValue?: boolean; + /** 列头过滤项的模板函数 */ + filterTemplate?: (this: GridColumnDefinition, item: ValueItem) => HTMLElement; + /** 自定义列排序函数 */ + sortFilter?: (a: GridRowItem, b: GridRowItem) => number; + /** 按照 `DisplayValue` 排序 */ + sortAsText?: boolean; + /** 额外设置单元格的 tooltip,支持直接使用字符串或者使用函数返回的字符串 */ + tooltip?: string | GridItemStringCallback; + + /** 列头复选框改变时触发的事件 */ + onAllChecked?: (this: Grid, col: GridColumnDefinition, flag: boolean) => void; + /** 单元格变化时触发事件 */ + onChanged?: (this: Grid, item: GridRowItem, value: boolean | string | number, oldValue: boolean | string | number, e: any, expandableObject: GridExpandableObject) => void; + /** 列过滤点击 `OK` 时触发的事件 */ + onFilterOk?: (this: Grid, col: GridColumnDefinition, selected: ValueItem[]) => void; + /** 列过滤后触发的事件 */ + onFiltered?: (this: Grid, col: GridColumnDefinition) => void; + /** 列为下拉框类型时在下拉列表展开时触发的事件 */ + onDropExpanded?: (this: GridColumnDefinition, item: GridRowItem, drop: Dropdown) => void; + /** 列为下拉框类型时在下拉列表关闭时触发的事件 */ + onDropCollapsed?: (this: GridColumnDefinition, item: GridRowItem, drop: Dropdown) => void; +} + +interface DropdownGridColumnDefinitionPart { + /** 列为下拉列表类型时以该值设置下拉框的参数 */ + dropOptions?: DropdownOptions; + /** 下拉列表是否区分大小写 */ + dropRestrictCase?: boolean; + /** 列为下拉列表类型时以该值设置下拉列表数据源,支持返回异步对象,也支持调用函数返回 */ + source?: GridSourceItem[] | PromiseLike | ((item: GridRowItem) => GridSourceItem[] | PromiseLike); + /** 下拉列表数据源是否缓存结果(即行数据未发生变化时仅从 source 属性获取一次值) */ + sourceCache?: boolean; +} +export type DropdownGridColumnDefinition = GridColumnDefinitionBase & DropdownGridColumnDefinitionPart; + +interface IconGridColumnDefinitionPart { + /** + * 列为图标类型时以该值设置图标样式 + * @default "fa-light" + */ + iconType?: "fa-light" | "fa-regular" | "fa-solid" | ((item: GridRowItem) => "fa-light" | "fa-regular" | "fa-solid"); +} +export type IconGridColumnDefinition = GridColumnDefinitionBase & IconGridColumnDefinitionPart; + +export interface DateGridColumnDefinitionPart { + /** 列为日期类型时以该值作为最小可选日期值 */ + dateMin?: string; + /** 列为日期类型时以该值作为最大可选日期值 */ + dateMax?: string; + /** 列为日期类型时日期显示的格式化字符串 */ + dateDisplayFormatter?: string; + /** 列为日期类型时自定义日期格式化字符串或函数 */ + dateValueFormatter?: string | ((date: Date) => string); +} +export type DateGridColumnDefinition = GridColumnDefinitionBase & DateGridColumnDefinitionPart; + +/** + * 列定义接口 + * + * Column Types
+ * 代码参考页面下方的示例 + * @example + * [ + * { + * key: 'name', + * // type: Grid.ColumnTypes.Common, + * caption: 'Name', + * captionStyle: { + * 'font-style': 'italic' + * }, + * width: 150, + * allowFilter: true + * }, + * { + * key: 'birthday', + * type: Grid.ColumnTypes.Date, + * caption: 'Birthday', + * width: 120, + * dateMin: '1900-01-01', + * dateMax: '2025-01-01', + * dateValueFormatter: toDateValue + * }, + * { + * key: 'age', + * type: Grid.ColumnTypes.Input, + * caption: 'Age', + * enabled: false, + * align: 'right', + * filter: item => { + * const ms = new Date() - new Date(item.birthday); + * const age = Math.floor(ms / 1000 / 60 / 60 / 24 / 365); + * return String(age); + * } + * }, + * { + * key: 'sex', + * type: Grid.ColumnTypes.Dropdown, + * caption: 'Sex', + * source: [ + * { value: 'male', text: 'Male' }, + * { value: 'female', text: 'Female' }, + * { value: 'other', text: 'Other' } + * ] + * }, + * { + * key: 'active', + * type: Grid.ColumnTypes.Checkbox, + * caption: 'Active' + * }, + * { + * key: 'remove', + * type: Grid.ColumnTypes.Icon, + * text: 'times', + * resizable: false, + * sortable: false, + * orderable: false, + * tooltip: 'Remove', + * events: { + * onclick: () => { + * showConfirm('Remove', 'Are you sure you want to remove this person?', [ + * { + * key: 'yes', + * text: 'Yes', + * trigger: () => { + * console.log('yes'); + * return true; + * } + * }, + * { + * key: 'no', + * text: 'No' + * } + * ], 'question') + * } + * } + * } + * ] + */ +export type GridColumnDefinition = GridColumnDefinitionBase & DropdownGridColumnDefinitionPart & IconGridColumnDefinitionPart & DateGridColumnDefinitionPart; + + +/** 多语言资源接口 */ +export interface GridLanguages { + all?: string; + ok?: string; + yes?: string; + reset?: string; + cancel?: string; + null?: string; + addLevel?: string; + deleteLevel?: string; + copyLevel?: string; + sortBy?: string; + thenBy?: string; + updateLayout?: string; + asc?: string; + desc?: string; + column?: string; + order?: string; + sort?: string; + sortArrayExists?: string; + requirePrompt?: string; + duplicatePrompt?: string; +} + +/** + * 列排序定义接口 + */ +export interface GridColumnSortDefinition { + column: string; + order: "asc" | "desc"; +} + +/** Grid 数据导出对象 */ +export interface GridExportData { + /** 导出数据 */ + data: Uint8Array; + /** 导出类型,`"compressed"` 意为压缩数据 */ + type?: string; + /** 压缩中的异常信息提示 */ + error?: string; +} + +/** + * Grid 控件基础类 + * + * Grid Sample
+ * 函数调用流程图
+ * Grid + * @example 基础示例 + *
+ * @example + * #grid>.ui-grid { + * width: 600px; + * height: 400px; + * } + * @example + * const grid = new Grid('#grid', GetTextByKey); + * grid.columns = [ + * { + * key: 'name', + * caption: 'Name', + * width: 140, + * allowFilter: true + * }, + * { + * key: 'age', + * caption: 'Age', + * type: Grid.ColumnTypes.Input, + * width: 80 + * }, + * { + * key: 'study', + * caption: 'Study', + * type: Grid.ColumnTypes.Dropdown, + * width: 120, + * source: [ + * { value: 'a', text: 'A' }, + * { value: 'b', text: 'B' }, + * { value: 'c', text: 'C' } + * ] + * } + * ]; + * grid.multiSelect = true; + * grid.init(); + * grid.source = [ + * { name: '张三', age: '19', study: 'a' }, + * { name: '李四', age: '24', study: 'a' }, + * { name: '王五', age: '20', study: 'c' } + * ]; + */ +export interface Grid { + /** 列定义的数组 */ + columns: GridColumnDefinition[]; + /** 多语言资源对象 */ + langs: GridLanguages; + /** + * 区域字符串 + * @default "en" + */ + lgid: string; + /** + * 行数大于等于该值则启用虚模式 + * @default 100 + */ + virtualCount: number; + /** + * 未设置宽度的列自动调整列宽 + * @default true + */ + autoResize: boolean; + /** + * 表格行高 + * @default 36 + */ + rowHeight: number; + /** + * 文本行高(多行文本列计算高度时使用) + * @default 18 + */ + lineHeight: number; + /** + * 列头未过滤时的图标 + * @default "ellipsis-h" + */ + filterIcon: string; + /** + * 列头已过滤时的图标 + * @default "filter" + */ + filteredIcon: string; + /** 列表底部留出额外的空白行 */ + extraRows: number; + /** + * 过滤条件列表的行高 + * @default 30 + */ + filterRowHeight: number; + /** + * 列表高度值,为 0 时列表始终显示全部内容(自增高),为非数字或者小于 0 则根据容器高度来确定虚模式的渲染行数 + * @default null + */ + height: number | null; + /** 是否允许多选 */ + multiSelect: boolean; + /** + * 为 `false` 时只有点击在单元格内才会选中行 + * @default true + */ + fullrowClick: boolean; + /** 单元格 tooltip 是否禁用 */ + tooltipDisabled: boolean; + /** + * 列头是否显示 + * @default true + */ + headerVisible: boolean; + /** + * 列头是否允许换行 + * @default true + */ + headerWrap: boolean; + /** 是否允许行间拖拽 */ + rowDraggable: boolean; + /** + * 监听事件的窗口载体 + * @default window + */ + window?: Window | HTMLElement; + /** + * 排序列的索引 + * @default -1 + */ + sortIndex: number; + /** + * 排序方式,正数升序,负数倒序 + * @default GridColumnDirection.Ascending + */ + sortDirection: number; + /** 排序列数组 */ + sortArray: GridColumnSortDefinition[] | null; + /** 是否支持点击扩展,或行数据中支持点击扩展的字段 */ + expandable: boolean | string; + /** 扩展行生成器 */ + expandableGenerator?: GridExpandableObjectCallback; + + /** + * 即将选中行时触发 + * @param index 即将选中的行索引 + * @param colIndex 即将选中的列索引 + * @returns 返回 `false`、`null`、`undefined`、`0` 等则取消选中动作 + */ + willSelect?: (this: Grid, index: number, colIndex: number) => boolean | PromiseLike; + /** + * 单元格单击时触发,colIndex 为 -1 则表示点击的是行的空白处 + * @param index 点击的行索引 + * @param colIndex 点击的列索引 + * @returns 返回 false 则取消事件冒泡 + */ + cellClicked?: (this: Grid, index: number, colIndex: number) => boolean; + + /** + * 选中行发生变化时触发的事件 + * @param index 选中的行索引 + */ + onSelectedRowChanged?: (this: Grid, index: number | number[]) => void; + /** + * 单元格双击时触发的事件,colIndex 为 -1 则表示点击的是行的空白处 + * @param index 双击的行索引 + * @param colIndex 双击的列索引 + */ + onCellDblClicked?: (this: Grid, index: number, colIndex: number) => void; + /** + * 行双击时触发的事件 + * @param index 双击的行索引 + */ + onRowDblClicked?: (this: Grid, index: number) => void; + /** + * 列发生变化时触发的事件 + * @param type 事件类型 + * + * * "reorder" 为发生列重排事件,此时 value 为目标列索引 + * * "resize" 为发生列宽调整事件,此时 value 为列宽度值 + * * "sort" 为发生列排序事件,此时 value 为 1(升序)或 -1(倒序) + * @param colIndex 发生变化事件的列索引 + * @param value 变化的值 + */ + onColumnChanged?: (this: Grid, type: "reorder" | "resize" | "sort", colIndex: number, value: number) => void; + /** + * 列滚动时触发的事件 + * @param e 滚动事件对象 + * @param index 起始行 + * @param count 显示行数 + */ + onBodyScrolled?: (this: Grid, e: Event | null, index: number, count: number) => void; + /** + * 扩展行展开时触发的事件 + * @param item 行数据对象 + * @param expandableObject 由 [expandableGenerator]{@linkcode Grid#expandableGenerator} 产生的行扩展对象 + */ + onRowExpanded?: (this: Grid, item: GridRowItem, expandableObject: GridExpandableObject) => void; + /** + * 扩展行收缩时触发的事件 + * @param item 行数据对象 + * @param expandableObject 由 [expandableGenerator]{@linkcode Grid#expandableGenerator} 产生的行扩展对象 + */ + onRowCollapsed?: (this: Grid, item: GridRowItem, expandableObject: GridExpandableObject) => void; + /** + * 行发生变化时触发的事件 + * @param action 变动类型 + * @param items 发生变动的行对象 + * @param indexes 变动的索引集合 + */ + onRowChanged?: (this: Grid, action: "update" | "add" | "remove" | "drag", items: GridRowItem[], indexes: number | number[]) => void; + + /** 获取全局是否可支持点击扩展 */ + readonly isExpandable: boolean; + /** 获取 Grid 的页面元素 */ + readonly element: HTMLDivElement | null; + /** 获取当前 Grid 是否已修改 */ + readonly changed: boolean; + /** 返回所有数据的数据(未过滤) */ + readonly allSource?: GridRowItem[]; + /** 获取已过滤的数据中的扩展对象数组 */ + readonly sourceExpandable?: (GridExpandableObject | undefined)[]; + /** 获取当前是否为虚模式状态 */ + readonly virtual: boolean; + /** 获取当前排序的列关键字,为 null 则当前无排序列 */ + readonly sortKey: string | null; + /** 获取当前选中的行对象 */ + readonly currentItem: GridRowItem | null; + /** 获取虚模式起始索引 */ + readonly startIndex: number; + /** 获取当前选中行的索引,为 -1 则当前没有选中行 */ + readonly selectedIndex: number; + + /** 获取或设置 Grid 是否为只读 */ + readonly: boolean; + /** 获取已过滤的数据数组,或者设置数据并刷新列表 */ + source: GridRowItem[]; + /** 获取或设置合计行数据 */ + total: GridRowItem | null; + /** 获取或设置当前选中的行索引的数组,设置后会刷新列表 */ + selectedIndexes: number[]; + /** 获取或设置 Grid 当前的加载状态 */ + loading: boolean; + /** 获取或设置 Grid 当前滚动的偏移量 */ + scrollTop?: number; + + /** + * 初始化Grid控件 + * @param container 父容器元素,若未传值则采用构造方法中传入的父容器元素 + * @default .ctor#container + */ + init(container: HTMLElement | null): void; + /** + * 设置数据列表,该方法为 [source]{@linkcode Grid#source} 属性的语法糖 + * @param source 待设置的数据列表 + */ + setData(source: GridRowItem[]): void; + /** + * 滚动到指定行的位置 + * @param index 待滚动至的行索引 + */ + scrollToIndex(index: number): void; + /** + * 调整 Grid 元素的大小,一般需要在宽度变化时(如页面大小发生变化时)调用 + * @param force 是否强制 [reload]{@linkcode Grid#reload},默认只有待渲染的行数发生变化时才会调用 + * @param keep 是否保持当前滚动位置 + * @param callback 计算大小后的回调函数,上下文为 Grid + */ + resize(force?: boolean, keep?: boolean, callback?: (this: Grid) => void): void; + /** + * 重新计算需要渲染的行,并载入元素,一般需要在高度变化时调用 + * @param keep 是否保持当前滚动位置 + */ + reload(keep?: boolean): void; + /** + * 重新填充Grid单元格数据 + */ + refresh(): void; + /** + * 把所有行重置为未修改的状态 + */ + resetChange(): void; + /** + * 根据当前排序字段进行列排序 + * @param reload 为 `true` 则在列排序后调用 [reload]{@linkcode Grid#reload} 方法 + */ + sortColumn(reload?: boolean): void; + /** + * 根据当前排序列数组进行多列排序 + * @param reload 为 `true` 则在多列排序后调用 [reload]{@linkcode Grid#reload} 方法 + */ + sort(reload?: boolean): void; + /** + * 清除列头复选框的选中状态 + */ + clearHeaderCheckbox(): void; + /** + * 显示多列排序设置面板 + * @param callback 更新回调函数 + * @param layout 是否显示更新 layout 复选框 + */ + showSortPanel(callback?: (this: Grid, array: GridColumnSortDefinition[] | null, checked?: boolean) => void, layout?: boolean): void; + /** + * 设置单行数据 + * @param index 行索引 + * @param item 待设置的行数据对象 + */ + setItem(index: number, item: GridRowItem): void; + /** + * 添加行数据 + * @param item 待添加的行数据值 + * @param index 待添加的行索引 + * @returns 返回已添加的行数据 + */ + addItem(item: GridRowItem, index?: number): GridRowItem; + /** + * 批量添加行数据 + * @param array 待添加的行数据数组 + * @param index 待添加的行索引 + * @returns 返回已添加的行数据数组 + */ + addItems(array: GridRowItem[], index?: number): GridRowItem[]; + /** + * 删除行数据 + * @param index 待删除的行索引 + * @returns 返回已删除的行数据 + */ + removeItem(index: number): GridRowItem; + /** + * 批量删除行数据 + * @param indexes 待删除的行索引数组,未传值时删除所有行 + * @returns 返回已删除的行数据数组 + */ + removeItems(indexes?: number[]): GridRowItem[]; + + /** + * 导出已压缩的数据源,结构为 + * ``` + * { + * columns: [], + * source: [], + * rowHeight: number, + * sortDirection: number, + * sortKey?: string, + * sortArray?: Array<{ + * column: string, + * order: "asc" | "desc" + * }> + * } + * ``` + * @param compressed 压缩编码,传入 false 则取消压缩 @default deflate + * @param module 压缩模块,默认采用 wasm_flate.deflate 编码,自定义模块需要实现以下消息事件 + * * `onmessage` - 接收消息 + * * `{ type: 'init', path: string}` - 初始化消息,参数 `path` 为 `ui.min.js` 脚本所在路径 + * * `{ type: 'compress', data: Uint8Array }` - 压缩消息,参数 `data` 为原始数据 + * * `postMessage` - 返回消息 + * * `{ type: 'init', result?: 0, error?: string}` - 初始化事件中的消息反馈,没有 `error` 意为成功 + * * `{ error: string }` - 压缩事件中的消息反馈,`error` 值为错误信息 + * * `Uint8Array` - 反馈压缩后的数据 + */ + export(compressed?: string | boolean, module?: string): Promise; + + /** + * 展开/收折所有行 + * @param expanded 是否展开,传 null 则切换展开状态 + * @returns 返回展开状态 + */ + expandAll(expanded?: boolean): boolean | undefined; +} diff --git a/lib/ui/grid/column.js b/lib/ui/grid/column.js index ebddef9..72757dd 100644 --- a/lib/ui/grid/column.js +++ b/lib/ui/grid/column.js @@ -1,4 +1,4 @@ -import { global } from "../../utility"; +import { global, isPromiseLike, isTag } from "../../utility"; import { createElement } from "../../functions"; import { createIcon } from "../icon"; import { createCheckbox, createRadiobox } from "../checkbox"; @@ -6,16 +6,8 @@ import { createCheckbox, createRadiobox } from "../checkbox"; import { Dropdown } from "../dropdown"; import { convertCssStyle } from "../extension"; import { createDateInput, formatDate, setDateValue, getDateValue } from "../date"; -// definition -/** @import { GridRowItem, DropdownOptions, GridColumnDefinition, GridSourceItem, GridItemWrapper, Grid } from "./grid" */ -/** - * @ignore - * @callback DropExpandedCallback - * @param {GridRowItem} item - 行数据对象 - * @param {Dropdown} drop - 下拉框对象 - * @this GridColumnDefinition - */ +/** @import { DropdownOptions, DropdownItem, Dropdown as IDropdown, GridSourceItemBase, GridSourceItem, GridItemWrapper, GridColumnDefinition, Grid } from '../../types' */ /** * 列定义基类 @@ -47,20 +39,19 @@ export class GridColumn { /** * 标记该类型是否支持列头批量操作 * @member - * @name GridColumn.headerEditing - * @readonly * @type {boolean} */ + static get headerEditing() { return false; } /** * 创建显示单元格时调用的方法 - * @param {GridColumnDefinition} col - 列定义对象 - * @param {number} index - 行元素索引(需要配合 [startIndex]{@linkcode Grid#startIndex} 相加得到真实数据索引) - * @param {Grid} grid - Grid 实例 + * @param {GridColumnDefinition} _col - 列定义对象 + * @param {number} [_index] - 行元素索引(需要配合 [startIndex]{@linkcode Grid#startIndex} 相加得到真实数据索引) + * @param {Grid} [_grid] - Grid 实例 * @returns {HTMLElement} 返回创建的单元格元素 * @virtual */ - static create() { + static create(_col, _index, _grid) { return createElement('span'); } @@ -71,11 +62,10 @@ export class GridColumn { * 更多例子参考代码中 {@linkcode GridDropdownColumn} 的实现。 * @method * @name GridColumn.createEdit - * @param {Function} trigger - 编辑事件回调函数 - * @param {any} trigger.e - 该参数会传递给 [getValue]{@linkcode GridColumn.getValue} 方法 - * @param {GridColumnDefinition} col - 列定义对象 - * @param {HTMLElement} [container] - 父容器元素 - * @param {GridItemWrapper} [wrapper] - 行包装对象,其 `values` 属性为行数据对象 + * @param {(e: any) => void} _trigger - 编辑事件回调函数,参数会传递给 [getValue]{@linkcode GridColumn.getValue} 方法 + * @param {GridColumnDefinition} _col - 列定义对象 + * @param {HTMLElement} [_container] - 父容器元素 + * @param {GridItemWrapper} [_wrapper] - 行包装对象,其 `values` 属性为行数据对象 * @returns {HTMLElement} 返回创建的编辑状态的单元格元素 * @virtual */ @@ -104,27 +94,27 @@ export class GridColumn { * @name GridColumn.getValue * @param {any} e - 由 [createEdit]{@linkcode GridColumn.createEdit} 方法中 `trigger` 函数传递来的对象 * @param {GridColumnDefinition} col - 列定义对象 - * @returns {(string | boolean | number)} 返回单元格的值 + * @returns {(string | boolean | number | Date)} 返回单元格的值 * @virtual */ /** * 设置单元格值时调用的方法 * @param {HTMLElement} element - 单元格元素 - * @param {(string | boolean | number)} val - 待设置的单元格值 - * @param {GridItemWrapper} wrapper - 行包装对象 - * @param {GridColumnDefinition} col - 列定义对象 - * @param {Grid} grid - Grid 对象 + * @param {(string | boolean | number | Date)} val - 待设置的单元格值 + * @param {GridItemWrapper} [_wrapper] - 行包装对象 + * @param {GridColumnDefinition} [_col] - 列定义对象 + * @param {Grid} [_grid] - Grid 对象 * @virtual */ - static setValue(element, val) { - element.innerText = val; + static setValue(element, val, _wrapper, _col, _grid) { + element.innerText = String(val); } /** * 设置单元格样式时调用的方法 * @param {HTMLElement} element - 单元格元素 - * @param {object} style - 样式对象 + * @param {Object.} style - 样式对象 * @virtual */ static setStyle(element, style) { @@ -148,10 +138,11 @@ export class GridColumn { * 设置单元格可用性时调用的方法 * @param {HTMLElement} element - 单元格元素 * @param {boolean} enabled - 启用值,为 `false` 时代表禁用 - * @param {boolean} editing - 是否处于编辑状态 + * @param {boolean} [_editing] - 是否处于编辑状态 * @virtual */ - static setEnabled(element, enabled) { + static setEnabled(element, enabled, _editing) { + /** @type {HTMLElement | null} */ const tooltip = element.querySelector('.ui-tooltip-wrapper'); if (tooltip != null) { tooltip.style.display = enabled === false ? 'none' : ''; @@ -221,7 +212,7 @@ export class GridInputColumn extends GridColumn { /** * @ignore - * @param {Function} trigger + * @param {(this: HTMLElement, e: Event) => any} trigger * @param {GridColumnDefinition} col * @param {HTMLElement} _container * @param {GridItemWrapper} wrapper @@ -239,9 +230,12 @@ export class GridInputColumn extends GridColumn { * @ignore * @param {HTMLElement} element * @param {string} val + * @param {GridItemWrapper} [_wrapper] + * @param {GridColumnDefinition} [_col] + * @param {Grid} [_grid] */ - static setValue(element, val) { - if (element.tagName !== 'INPUT') { + static setValue(element, val, _wrapper, _col, _grid) { + if (!isTag(element, 'input')) { super.setValue(element, val); } else { element.value = val; @@ -253,7 +247,12 @@ export class GridInputColumn extends GridColumn { * @param {Event} e * @returns {string} */ - static getValue(e) { return e.target.value } + static getValue(e) { + if (e.target && isTag(/** @type {Element} */(e.target), 'input')) { + return e.target.value + } + return ''; + } /** * @ignore @@ -262,7 +261,9 @@ export class GridInputColumn extends GridColumn { */ static setEnabled(element, enabled) { super.setEnabled(element, enabled); - element.disabled = enabled === false; + if (isTag(element, 'input')) { + element.disabled = enabled === false; + } } /** @@ -282,11 +283,11 @@ export class GridInputColumn extends GridColumn { export class GridTextColumn extends GridInputColumn { /** * @ignore - * @param {Function} trigger + * @param {(this: HTMLTextAreaElement, ev: Event) => any} trigger * @param {GridColumnDefinition} col * @param {HTMLElement} _container * @param {GridItemWrapper} wrapper - * @returns {HTMLElement} + * @returns {HTMLTextAreaElement} */ static createEdit(trigger, col, _container, wrapper) { const input = createElement('textarea'); @@ -304,7 +305,7 @@ export class GridTextColumn extends GridInputColumn { * @param {Grid} grid */ static setValue(element, val, _wrapper, _col, grid) { - if (element.tagName !== 'TEXTAREA') { + if (!isTag(element, 'textarea')) { super.setValue(element, val); } else { element.value = val; @@ -322,7 +323,7 @@ export class GridTextColumn extends GridInputColumn { static toString() { return 'GridText' } } -const SymbolDropdown = Symbol.for('ui-dropdown'); +const SymbolDropdown = Symbol.for('ui-grid-dropdown'); /** * 下拉选择列 @@ -344,11 +345,11 @@ export class GridDropdownColumn extends GridColumn { /** * @ignore - * @param {Function} trigger + * @param {(this: IDropdown, it?: DropdownItem) => void} trigger * @param {GridColumnDefinition} col * @param {HTMLElement} container * @param {GridItemWrapper} wrapper - * @returns {HTMLElement} + * @returns {HTMLDivElement} */ static createEdit(trigger, col, container, wrapper) { const drop = new Dropdown({ @@ -379,10 +380,10 @@ export class GridDropdownColumn extends GridColumn { /** * @ignore * @param {HTMLElement} element - * @returns {HTMLElement} + * @returns {Element} */ static getElement(element) { - if (element.tagName === 'DIV') { + if (isTag(element, 'div')) { return element.children[0].children[0]; } return element.children[0]; @@ -391,17 +392,20 @@ export class GridDropdownColumn extends GridColumn { /** * @private * @param {HTMLElement} element - * @returns {Dropdown} + * @returns {Dropdown | null} */ static _getDrop(element) { /** - * @type {Map} + * @type {Object.} */ - const dropGlobal = global[SymbolDropdown]; + const dropGlobal = /** @type {Record} */ (/** @type {unknown} */ (global))[SymbolDropdown]; if (dropGlobal == null) { return null; } const dropId = element.dataset.dropId; + if (dropId == null) { + return null; + } const drop = dropGlobal[dropId]; if (drop == null) { return null; @@ -413,7 +417,7 @@ export class GridDropdownColumn extends GridColumn { * @private * @param {GridItemWrapper} wrapper * @param {GridColumnDefinition} col - * @returns {GridSourceItem[]} + * @returns {GridSourceItem[] | PromiseLike | null} */ static _getSource(wrapper, col) { let source; @@ -427,45 +431,58 @@ export class GridDropdownColumn extends GridColumn { if (typeof source === 'function') { source = source(wrapper.values); } - if (col.sourceCache !== false) { - if (wrapper.source == null) { - wrapper.source = { [col.key]: source }; - } else { - wrapper.source[col.key] = source; + if (source) { + if (col.sourceCache !== false) { + if (isPromiseLike(source)) { + source.then(s => { + if (wrapper.source == null) { + wrapper.source = { [col.key]: s }; + } else { + wrapper.source[col.key] = s; + } + }); + } else { + if (wrapper.source == null) { + wrapper.source = { [col.key]: source }; + } else { + wrapper.source[col.key] = source; + } + } } + return source; } - return source; + return null; } /** * @private * @param {GridSourceItem[]} source * @param {HTMLElement} element - * @param {any} val - * @param {DropdownOptions} opts + * @param {string} val + * @param {DropdownOptions} [opts] */ static _setValue(source, element, val, opts) { const data = source?.find(v => v[opts?.valueKey ?? 'value'] === val); if (data != null) { val = data[opts?.textKey ?? 'text']; } - element.children[0].innerText = val; + /** @type {HTMLElement} */ (element.children[0]).innerText = val; } /** * @ignore * @param {HTMLElement} element - * @param {any} val + * @param {string} val * @param {GridItemWrapper} wrapper * @param {GridColumnDefinition} col * @param {Grid} grid */ static setValue(element, val, wrapper, col, grid) { - if (element.tagName !== 'DIV') { + if (!isTag(element, 'div')) { let source = this._getSource(wrapper, col); - if (source instanceof Promise) { + if (isPromiseLike(source)) { source.then(s => this._setValue(s, element, val, col.dropOptions)); - } else { + } else if (source) { this._setValue(source, element, val, col.dropOptions); } return; @@ -477,7 +494,7 @@ export class GridDropdownColumn extends GridColumn { const ignoreCase = col.dropRestrictCase !== true; if (drop.source == null || drop.source.length === 0) { let source = this._getSource(wrapper, col); - if (source instanceof Promise) { + if (isPromiseLike(source)) { source.then(s => { drop.source = s; drop.select(val, true, ignoreCase); @@ -499,6 +516,7 @@ export class GridDropdownColumn extends GridColumn { if (item == null) { let text; if (col.text == null && typeof col.filter === 'function') { + // @ts-ignore text = col.filter(wrapper.values, false, grid._var.refs.body); } else { text = val; @@ -516,7 +534,7 @@ export class GridDropdownColumn extends GridColumn { * @ignore * @param {GridSourceItem} e * @param {GridColumnDefinition} col - * @returns {any} + * @returns {Required} */ static getValue(e, col) { return { @@ -531,7 +549,7 @@ export class GridDropdownColumn extends GridColumn { * @param {string} name */ static setClass(element, name) { - if (element.tagName === 'DIV') { + if (isTag(element, 'div')) { element.className = `ui-drop-wrapper ${name ?? ''}`; } else { super.setClass(element, name); @@ -554,11 +572,11 @@ export class GridDropdownColumn extends GridColumn { /** * @ignore - * @param {HTMLElement} element + * @param {HTMLDivElement} element * @param {HTMLElement} container */ static leaveEdit(element, container) { - container.parentElement.querySelectorAll('.ui-drop-box.active').forEach(e => { + container.parentElement?.querySelectorAll('.ui-drop-box.active').forEach(e => { if (e != null) { e.classList.remove('active'); } @@ -591,11 +609,12 @@ export class GridCheckboxColumn extends GridColumn { /** * @ignore - * @param {Function} trigger + * @param {(this: HTMLInputElement, ev: Event) => any} trigger * @param {GridColumnDefinition} col - * @returns {HTMLElement} + * @param {number} [_index] + * @returns {HTMLLabelElement} */ - static createEdit(trigger, col) { + static createEdit(trigger, col, _index) { const check = createCheckbox({ switch: col.switch, onchange: trigger @@ -610,7 +629,9 @@ export class GridCheckboxColumn extends GridColumn { */ static setValue(element, val) { // element.querySelector('input').checked = val; - element.children[0].checked = val; + if (isTag(element.children[0], 'input')) { + element.children[0].checked = val; + } } /** @@ -618,7 +639,12 @@ export class GridCheckboxColumn extends GridColumn { * @param {Event} e * @returns {boolean} */ - static getValue(e) { return e.target.checked } + static getValue(e) { + if (e.target && isTag(/** @type {Element} */(e.target), 'input')) { + return e.target.checked; + } + return false; + } /** * @ignore @@ -626,7 +652,7 @@ export class GridCheckboxColumn extends GridColumn { * @param {string} name */ static setClass(element, name) { - if (element.tagName === 'LABEL') { + if (isTag(element, 'label')) { element.className = `ui-check-wrapper ${name ?? ''}`; } else { super.setClass(element, name); @@ -641,7 +667,9 @@ export class GridCheckboxColumn extends GridColumn { static setEnabled(element, enabled) { super.setEnabled(element, enabled); // element.querySelector('input').disabled = enabled === false; - element.children[0].disabled = enabled === false; + if (isTag(element.children[0], 'input')) { + element.children[0].disabled = enabled === false; + } } /** @@ -661,10 +689,10 @@ export class GridCheckboxColumn extends GridColumn { export class GridRadioboxColumn extends GridCheckboxColumn { /** * @ignore - * @param {Function} trigger + * @param {(this: HTMLInputElement, ev: Event) => any} trigger * @param {GridColumnDefinition} _col * @param {number} index - * @returns {HTMLElement} + * @returns {HTMLLabelElement} */ static createEdit(trigger, _col, index) { const check = createRadiobox({ @@ -769,7 +797,7 @@ export class GridDateColumn extends GridColumn { /** * @ignore - * @param {Function} trigger + * @param {(this: HTMLInputElement, ev: FocusEvent) => any} trigger * @param {GridColumnDefinition} col * @param {HTMLElement} _container * @param {GridItemWrapper} wrapper @@ -779,11 +807,11 @@ export class GridDateColumn extends GridColumn { let enabled = col.enabled; if (typeof enabled === 'string') { enabled = wrapper.values[enabled]; - } else if (typeof enabled === 'function') { + } else if (typeof col.enabled === 'function') { enabled = col.enabled(wrapper.values); } if (enabled === false) { - return super.create(); + return super.create(col); } const date = createDateInput(col.dateMin, col.dateMax); date.addEventListener('change', () => super._changeValue(col.key, wrapper, date.value)); @@ -806,10 +834,13 @@ export class GridDateColumn extends GridColumn { * @ignore * @param {Event} e * @param {GridColumnDefinition} col - * @returns {string} + * @returns {string | GridSourceItemBase} */ static getValue(e, col) { - if (e.target.tagName === 'INPUT') { + if (!(e.target instanceof HTMLElement)) { + return ''; + } + if (isTag(e.target, 'input')) { return { value: getDateValue(e.target, col.dateValueFormatter), text: getDateValue(e.target, col.dateDisplayFormatter) @@ -824,7 +855,7 @@ export class GridDateColumn extends GridColumn { * @param {string} name */ static setClass(element, name) { - if (element.tagName === 'INPUT') { + if (isTag(element, 'input')) { element.className = `ui-date-cell ${name ?? ''}`; } else { super.setClass(element, name); @@ -837,7 +868,9 @@ export class GridDateColumn extends GridColumn { * @param {boolean} enabled */ static setEnabled(element, enabled) { - element.disabled = enabled === false; + if (isTag(element, 'input')) { + element.disabled = enabled === false; + } } /** diff --git a/lib/ui/grid/grid.js b/lib/ui/grid/grid.js index b3a03db..c808640 100644 --- a/lib/ui/grid/grid.js +++ b/lib/ui/grid/grid.js @@ -1,5 +1,5 @@ import '../css/grid.scss'; -import { global, isPositive, isMobile, throttle, debounce, truncate } from "../../utility"; +import { global, isPositive, isMobile, throttle, debounce, truncate, isPromiseLike } from "../../utility"; import { r as lang } from "../../utility/lgres"; import { nullOrEmpty } from "../../utility/strings"; import { createElement } from "../../functions"; @@ -11,14 +11,19 @@ import { convertCssStyle } from "../extension"; import { GridColumn, GridInputColumn, GridTextColumn, GridDropdownColumn, GridCheckboxColumn, GridRadioboxColumn, GridIconColumn, GridDateColumn } from "./column"; import { requestAnimationFrame } from '../../ui'; +/** @import { + * Dropdown, ValueItem, GridRowItem, GridItemWrapper, GridExpandableObject, + * GridColumnDefinition, GridColumnSortDefinition, GridExpandableObjectCallback, + * GridExportData, Grid as IGrid + * } from '../../types' */ + /** * @author Tsanie Lily * @license MIT * @version 1.0.7 */ -const ScriptPath = import.meta.url.replace(/\/[^?/]+(\?[a-f0-9]+)?$/, '/'); -const Encoder = new TextEncoder('utf-8'); +const Encoder = new TextEncoder(); const ColumnChangedType = { Reorder: 'reorder', @@ -35,15 +40,14 @@ const ExpandableWidth = 24; /** * @private - * @param {Event} e - * @returns {number} + * @param {MouseEvent} e + * @returns {number | null} */ function getClientX(e) { if (e == null) { return null; } - const cx = e.touches && e.touches[0]?.clientX; - return cx ?? e.clientX; + return e.clientX; } /** @@ -53,7 +57,7 @@ function getClientX(e) { */ function indexOfParent(target) { // return [...target.parentElement.children].indexOf(target); - return Array.prototype.indexOf.call(target.parentElement.children, target); + return Array.prototype.indexOf.call(target.parentElement?.children, target); } const ColumnTypeDefs = { @@ -69,301 +73,6 @@ const ColumnTypeDefs = { let r = lang; -/** - * 键值字典 - * @template T - * @typedef {Object.} KeyMap - */ - -/** - * 索引字典 - * @template T - * @typedef {Object.} IndexMap - */ - -/** - * 数据项 - * @typedef ValueItem - * @property {any} Value - 值 - * @property {string} DisplayValue - 显示值 - * @property {boolean} [__checked] - 已选中 - * @interface - */ - -/** - * 行数据对象 - * @typedef GridRowItem - * @type {KeyMap} - * @property {(ValueItem | any)} {key} - 数据项 - * @extends {KeyMap} - * @interface - */ - -/** - * 行数据包装接口 - * @typedef GridItemWrapper - * @property {GridRowItem} values - 真实数据对象 - * @property {KeyMap} source - 下拉数据源缓存对象 - * @property {number} __index - 行索引 - * @property {number} __offset - 批量删除时暂存的索引偏移量 - * @property {KeyMap} __editing - 正在编辑的列的原始值字典 - * @property {boolean} __changed - 行数据是否发生改变 - * @property {boolean} __expanded - 行是否已展开 - * @property {GridExpandableObject} __expandable_object - 行扩展对象 - * @interface - */ - -/** - * 下拉框数据源接口 - * @typedef GridSourceItem - * @property {string} value - 值 - * @property {string} text - 显示文本 - * @interface - */ - -/** - * 行数据可用性回调函数 - * @callback GridItemBooleanCallback - * @param {GridRowItem} item - 行数据对象 - * @returns {boolean} 返回是否可用 - * @this GridColumnDefinition - */ - -/** - * 行数据过滤回调函数 - * @callback GridItemFilterCallback - * @param {GridRowItem} item - 行数据对象 - * @param {boolean} editing - 是否处于编辑状态 - * @param {HTMLElement} [body] - Grid 控件的 `` 部分 - * @param {number} [index] - 所在行索引(不可依赖此值,除了呈现时,其他时候该值不会传递) - * @returns {ValueItem} - 返回过滤后的显示或编辑值 - * @this GridColumnDefinition - */ - -/** - * 行数据处理回调函数 - * @callback GridItemObjectCallback - * @param {GridRowItem} item - 行数据对象 - * @returns {any} 返回任意对象 - * @this GridColumnDefinition - */ - -/** - * 行数据过滤项模板回调函数 - * @callback GridItemHtmlCallback - * @param {ValueItem} item - 行数据对象 - * @returns {HTMLElement} 返回过滤项元素对象 - * @this GridColumnDefinition - */ - -/** - * 行数据字符串回调函数 - * @callback GridItemStringCallback - * @param {GridRowItem} item - 行数据对象 - * @returns {string} 返回字符串 - * @this GridColumnDefinition - */ - -/** - * 列过滤器数据源回调函数 - * @callback GridColumnFilterSourceCallback - * @param {GridColumnDefinition} col - 列定义对象 - * @returns {ValueItem[]} 返回过滤器的数据数组 - * @this Grid - */ - -/** - * 行数据排序回调函数 - * @callback GridItemSortCallback - * @param {GridRowItem} a - 对比行数据1 - * @param {GridRowItem} b - 对比行数据2 - * @returns {number} 返回大小对比结果 - */ - -/** - * 下拉列表数据源回调函数 - * @callback GridDropdownSourceCallback - * @param {GridRowItem} item - 行数据对象 - * @returns {GridSourceItem[]} 行下拉列表数据源 - */ - -/** - * 下拉列表参数对象 - * @typedef DropdownOptions - * @property {string} [textKey=text] - 文本关键字 - * @property {string} [valueKey=value] - 值关键字 - * @property {string} [htmlKey=html] - 源码显示的关键字 - * @property {number} [maxLength=500] - 最大输入长度 - * @property {boolean} [multiSelect] - 是否允许多选 - * @property {string} [selected] - 选中值 - * @property {string[]} [selectedList] - 选中的数组 - * @property {boolean} [disabled] - 是否禁用 - * @property {boolean} [input] - 是否支持输入 - * @property {boolean} [search] - 是否支持搜索 - * @property {string[]} [searchKeys] - 搜索的关键字数组 - * @property {string} [searchPlaceholder] - 搜索提示文本,默认值取语言资源 `searchHolder` "Search..." - * @property {number} [tabIndex] - 焦点索引 - * @property {string} [placeholder] - 输入框的提示文本 - * @property {boolean} [slideFixed] - 是否固定为向下展开 - * @property {HTMLElement} [wrapper] - 父元素,默认添加到头元素之后 - * @interface - */ - -/** - * 自定义日期格式化回调函数 - * @callback DateFormatterCallback - * @param {Date} date - 日期值 - * @returns {any} 返回格式化后的结果 - */ - -/** - * 列定义接口 - * - * Column Types
- * 代码参考页面下方的示例 - * @typedef GridColumnDefinition - * @property {string} key - 列关键字,默认以该关键字从行数据中提取单元格值,行数据的关键字属性值里包含 DisplayValue 则优先显示此值 - * @property {(GridColumnTypeEnum | GridColumn)} [type=Grid.ColumnTypes.Common] - 列的类型,可以为 {@linkcode GridColumn} 的子类,或者如下内置类型 {@linkcode Grid.ColumnTypes} - * * Grid.ColumnTypes.Common - 0: 通用列(只读) - * * Grid.ColumnTypes.Input - 1: 单行文本列 - * * Grid.ColumnTypes.Dropdown - 2: 下拉选择列 - * * Grid.ColumnTypes.Checkbox - 3: 复选框列 - * * Grid.ColumnTypes.Icon - 4: 图标列 - * * Grid.ColumnTypes.Text - 5: 多行文本列 - * * Grid.ColumnTypes.Date - 6: 日期选择列 - * * Grid.ColumnTypes.Radio - 7: 单选框列 - * @property {string} [caption] - 列标题文本 - * @property {any} [captionStyle] - 列标题的元素样式 - * @property {string} [captionTooltip] - 列标题的帮助文本 - * @property {number} [width] - 大于 0 则设置为该宽度,否则根据列内容自动调整列宽 - * @property {("left" |"center" | "right")} [align=left] 列对齐方式 - * @property {(boolean | string | GridItemBooleanCallback)} [enabled] - 列是否可用(可编辑),允许以下类型 - * - * * `boolean` 则直接使用该值 - * * `string` 则以该值为关键字从行数据中取值作为判断条件 - * * `GridItemBooleanCallback` 则调用回调,以返回值作为判断条件 - * @property {GridItemFilterCallback} [filter] - 单元格取值采用该函数返回的值 - * @property {string} [text] - 单元格以该值填充内容,忽略filter与关键字属性 - * @property {boolean} [visible=true] - 列是否可见 - * @property {boolean} [resizable=true] - 列是否允许调整宽度 - * @property {boolean} [sortable=true] - 列是否允许排序 - * @property {boolean} [orderable=true] - 列是否允许重排顺序 - * @property {boolean} [allcheck=false] - 列为复选框类型时是否在列头增加全选复选框 - * @property {boolean} [shrink=false] - 列为收缩列,禁用自动调整大小 - * @property {string} [class] - 单元格元素的额外样式类型字符串(仅在重建行元素时设置) - * @property {boolean} [contentWrap=false] - 单元格文本是否换行(仅在重建行元素时设置) - * @property {number} [maxLines=0] - 大于 0 时限制显示最大行数 - * @property {any} [css] - 单元格css样式对象(仅在重建行元素时读取) - * @property {any} [totalCss] - 合计行样式(仅在重建合计行元素时读取) - * @property {(any | GridItemObjectCallback)} [style] - 单元格样式(填充行列数据时读取),支持直接返回样式对象或调用函数返回(若赋值则忽略 [styleFilter]{@linkcode GridColumnDefinition#styleFilter}) - * @property {GridItemObjectCallback} [styleFilter] - **已过时**
_根据返回值填充单元格样式(填充行列数据时读取)_ - * @property {(string | GridItemStringCallback)} [background] - 设置单元格背景色(填充行列数据时读取),支持直接设置颜色字符串或调用函数返回(若赋值则忽略 [bgFilter]{@linkcode GridColumnDefinition#bgFilter}) - * @property {GridItemStringCallback} [bgFilter] - **已过时**
_根据返回值设置单元格背景色_ - * @property {boolean} [switch=false] - 复选框为 `ui-switch` 样式 *@since* 1.0.6 - * @property {(any | GridItemObjectCallback)} [attrs] - 根据返回值设置单元格元素的附加属性,允许直接设置对象也支持调用函数返回对象 - * @property {KeyMap} [events] - 给单元格元素附加事件(事件函数上下文为数据行对象) - * @property {boolean} [allowFilter=false] - 是否允许进行列头过滤 - * @property {any[]} [filterValues] - 过滤值的数组 - * @property {boolean} [filterAllowNull=false] - 是否区分 `null` 与空字符串 - * @property {(ValueItem[] | GridColumnFilterSourceCallback)} [filterSource] - 自定义列过滤器的数据源,支持调用函数返回数据源 - * @property {boolean} [filterAsValue=false] - 列头过滤强制使用 `Value` 字段 - * @property {GridItemHtmlCallback} [filterTemplate] - 列头过滤项的模板函数 - * @property {GridItemSortCallback} [sortFilter] - 自定义列排序函数 - * @property {boolean} [sortAsText=false] - 按照 `DisplayValue` 排序 - * @property {DropdownOptions} [dropOptions] - 列为下拉列表类型时以该值设置下拉框的参数 - * @property {boolean} [dropRestrictCase=false] - 下拉列表是否区分大小写 - * @property {(GridSourceItem[] | Promise | GridDropdownSourceCallback)} [source] - 列为下拉列表类型时以该值设置下拉列表数据源,支持返回异步对象,也支持调用函数返回 - * @property {boolean} [sourceCache=false] - 下拉列表数据源是否缓存结果(即行数据未发生变化时仅从source属性获取一次值) - * @property {("fa-light" | "fa-regular" | "fa-solid")} [iconType=fa-light] - 列为图标类型时以该值设置图标样式 - * @property {string} [dateMin] - 列为日期类型时以该值作为最小可选日期值 - * @property {string} [dateMax] - 列为日期类型时以该值作为最大可选日期值 - * @property {string} [dateDisplayFormatter] - 列为日期类型时日期显示的格式化字符串 - * @property {(string | DateFormatterCallback)} [dateValueFormatter] - 列为日期类型时自定义日期格式化字符串或函数 - * @property {(string | GridItemStringCallback)} [tooltip] - 额外设置单元格的 tooltip,支持直接使用字符串或者使用函数返回的字符串 - * @property {Function} [onAllChecked] - 列头复选框改变时触发事件 - * @property {Function} [onChanged] - 单元格变化时触发事件 - * @property {Function} [onFilterOk] - 列过滤点击 `OK` 时触发的事件 - * @property {Function} [onFiltered] - 列过滤后触发的事件 - * @property {Function} [onDropExpanded] - 列为下拉框类型时在下拉列表展开时触发的事件 - * @property {Function} [onDropCollapsed] - 列为下拉框类型时在下拉列表关闭时触发的事件 - * @interface - * @example - * [ - * { - * key: 'name', - * // type: Grid.ColumnTypes.Common, - * caption: 'Name', - * captionStyle: { - * 'font-style': 'italic' - * }, - * width: 150, - * allowFilter: true - * }, - * { - * key: 'birthday', - * type: Grid.ColumnTypes.Date, - * caption: 'Birthday', - * width: 120, - * dateMin: '1900-01-01', - * dateMax: '2025-01-01', - * dateValueFormatter: toDateValue - * }, - * { - * key: 'age', - * type: Grid.ColumnTypes.Input, - * caption: 'Age', - * enabled: false, - * align: 'right', - * filter: item => { - * const ms = new Date() - new Date(item.birthday); - * const age = Math.floor(ms / 1000 / 60 / 60 / 24 / 365); - * return String(age); - * } - * }, - * { - * key: 'sex', - * type: Grid.ColumnTypes.Dropdown, - * caption: 'Sex', - * source: [ - * { value: 'male', text: 'Male' }, - * { value: 'female', text: 'Female' }, - * { value: 'other', text: 'Other' } - * ] - * }, - * { - * key: 'active', - * type: Grid.ColumnTypes.Checkbox, - * caption: 'Active' - * }, - * { - * key: 'remove', - * type: Grid.ColumnTypes.Icon, - * text: 'times', - * resizable: false, - * sortable: false, - * orderable: false, - * tooltip: 'Remove', - * events: { - * onclick: () => { - * showConfirm('Remove', 'Are you sure you want to remove this person?', [ - * { - * key: 'yes', - * text: 'Yes', - * trigger: () => { - * console.log('yes'); - * return true; - * } - * }, - * { - * key: 'no', - * text: 'No' - * } - * ], 'question') - * } - * } - * } - * ] - */ /** * 列头复选框改变时触发的事件 * @name onAllChecked @@ -424,7 +133,7 @@ let r = lang; /** * 判断列是否始终编辑的回调函数 * @callback ColumnTypesEnumIsAlwaysEditing - * @param {number | GridColumn} type - 列类型 + * @param {number | typeof GridColumn} type - 列类型 * @returns {boolean} 返回是否始终编辑 */ @@ -454,7 +163,10 @@ const GridColumnTypeEnum = { * @type {ColumnTypesEnumIsAlwaysEditing} */ isAlwaysEditing(type) { - return type?.headerEditing || type === 3 || type === 7; + if (typeof type === 'number') { + return type === 3 || type === 7; + } + return type?.headerEditing; } }; @@ -495,42 +207,10 @@ const GridColumnDirection = { * @interface */ -/** - * Grid 数据导出对象 - * @typedef GridExportData - * @property {Uint8Array} data - 导出数据 - * @property {string} [type] - 导出类型,`"compressed"` 意为压缩数据 - * @property {string} [error] - 压缩中的异常信息提示 - * @interface - */ - -/** - * 列排序定义接口 - * @typedef GridColumnSortDefinition - * @property {string} column - 排序列的关键字 - * @property {("asc" | "desc")} order - 升序或降序 - * @interface - */ - -/** - * 扩展行对象接口 - * @typedef GridExpandableObject - * @property {HTMLElement} element - 扩展行元素 - * @interface - */ - -/** - * 扩展行生成回调函数 - * @callback GridExpandableObjectCallback - * @param {GridRowItem} item - 行数据对象 - * @returns {GridExpandableObject} 返回扩展行对象 - * @this Grid - */ - /** * @typedef GridVirtualRow * @property {boolean} editing - 行处于编辑状态 - * @property {KeyMap} cells - 虚拟单元格数组 + * @property {Object.} cells - 虚拟单元格数组 * @private */ @@ -547,20 +227,93 @@ const GridColumnDirection = { /** * @typedef GridColumnAttr - * @property {boolean} dragging - 列正在拖拽 - * @property {number} offset - 列拖拽偏移 - * @property {Function} mousemove - 拖拽或调整大小移动回调函数 - * @property {Function} mouseup - 拖拽或调整大小鼠标释放回调函数 - * @property {number} resizing - 列临时大小 - * @property {boolean} sizing - 列已进入修改大小的状态 - * @property {boolean} autoResize - 列需要自动调整大小 - * @property {any} style - 列样式对象 - * @property {ValueItem[]} filterSource - 列过滤面板数据源 - * @property {number} filterHeight - 列过滤面板高度 - * @property {number} filterTop - 列过滤面板滚动头部间距 + * @property {boolean} [dragging] - 列正在拖拽 + * @property {number} [offset] - 列拖拽偏移 + * @property {Function} [mousemove] - 拖拽或调整大小移动回调函数 + * @property {Function} [mouseup] - 拖拽或调整大小鼠标释放回调函数 + * @property {number} [resizing] - 列临时大小 + * @property {boolean} [sizing] - 列已进入修改大小的状态 + * @property {boolean} [autoResize] - 列需要自动调整大小 + * @property {any} [style] - 列样式对象 + * @property {ValueItem[]} [filterSource] - 列过滤面板数据源 + * @property {number} [filterHeight] - 列过滤面板高度 + * @property {number} [filterTop] - 列过滤面板滚动头部间距 + * @property {boolean} [filterSearched] * @private */ +/** @typedef {{ __filtered: boolean; __filtering: boolean; __orderIndex: number; } & Object.} ColumnAttr */ + +/** + * @private + * @param {ColumnAttr} attr + * @param {string} key + * @returns {GridColumnAttr | undefined} + */ +function getAttr(attr, key) { + if (key === '__filtered' || key === '__filtering' || key === '__orderIndex') { + return; + } + return /** @type {GridColumnAttr} */ (attr[key]); +} + +const defaultRefs = { + /** + * 表格引用 - table.ui-grid-table + * @type {HTMLTableElement | null} + * @private + */ + table: null, + /** + * 表格正文引用 - tbody + * @type {HTMLTableSectionElement | null} + * @private + */ + body: null, + /** + * 表格头部引用 - thead>tr + * @type {HTMLTableSectionElement | null} + * @private + */ + header: null, + /** + * 表格合计行引用 - tfooter>tr + * @type {HTMLTableSectionElement | null} + * @private + */ + footer: null, + /** + * 加载状态元素引用 - div.ui-loading + * @type {HTMLDivElement | null} + * @private + */ + loading: null, + /** + * 大小计算元素引用 - span.ui-grid-sizer + * @type {HTMLSpanElement | null} + * @private + */ + sizer: null, + /** + * 包装元素引用 - div.ui-grid-wrapper + * @type {HTMLDivElement | null} + * @private + */ + wrapper: null, + /** + * 拖拽块引用 - div.dragger + * @type {HTMLDivElement | null} + * @private + */ + dragger: null, + /** + * 拖拽光标引用 - layer.dragger-cursor + * @type {HTMLElement | null} + * @private + */ + draggerCursor: null, +}; + /** * Grid 控件基础类 * @@ -609,6 +362,7 @@ const GridColumnDirection = { * { name: '李四', age: '24', study: 'a' }, * { name: '王五', age: '20', study: 'c' } * ]; + * @implements IGrid */ export class Grid { @@ -619,31 +373,31 @@ export class Grid { _var = { /** * 父容器元素 - * @type {HTMLElement} + * @type {HTMLElement | undefined | null} * @private */ parent: null, /** * Grid 包裹元素 - * @type {HTMLDivElement} + * @type {HTMLDivElement | null} * @private */ container: null, /** * Grid 元素 - `div.ui-grid` - * @type {HTMLDivElement} + * @type {HTMLDivElement | null} * @private */ el: null, /** * 全部数据数组 - * @type {GridItemWrapper[]} + * @type {GridItemWrapper[] | null} * @private */ source: null, /** * 当前已过滤显示的数据数组 - * @type {GridItemWrapper[]} + * @type {GridItemWrapper[] | null} * @private */ currentSource: null, @@ -655,13 +409,13 @@ export class Grid { expanded: false, /** * 列可用性的关联字典 - * @type {KeyMap} + * @type {Object. | null} * @private */ enabledDict: null, /** * 合计行数据 - * @type {GridRowItem} + * @type {GridRowItem | null} * @private */ total: null, @@ -682,7 +436,7 @@ export class Grid { * @type {number[]} * @private */ - selectedIndexes: null, + selectedIndexes: [], /** * 虚模式头部索引 * @type {number} @@ -715,19 +469,19 @@ export class Grid { rowCount: -1, /** * 虚拟单元格字典 - * @type {IndexMap} + * @type {Object.} * @private */ virtualRows: {}, /** * 列类型缓存字典 - * @type {KeyMap} + * @type {Object.} * @private */ colTypes: {}, /** * 列属性字典 - * @type {KeyMap} + * @type {ColumnAttr} * @private */ colAttrs: { @@ -761,109 +515,55 @@ export class Grid { * @type {number} * @private */ - headerHeight: null, + headerHeight: 0, /** * 正文高度 * @type {number} * @private */ - containerHeight: null, + containerHeight: -1, /** * 合计行高度 * @type {number} * @private */ - footerHeight: null, + footerHeight: 0, /** * 合计行底边距偏移量 * @type {number} * @private */ - footerOffset: null, + footerOffset: 0, /** * 容器宽度 * @type {number} * @private */ - wrapClientWidth: null, + wrapClientWidth: 0, /** * 正文宽度 * @type {number} * @private */ - bodyClientWidth: null, + bodyClientWidth: 0, /** * 是否需要 resize * @type {boolean} * @private */ - needResize: null, + needResize: false, /** * 提示条消失的 Timer * @type {number} * @private */ - tooltipTimer: null, + tooltipTimer: 0, /** * 页面元素引用 + * @type {typeof defaultRefs} * @private */ - refs: { - /** - * 表格引用 - table.ui-grid-table - * @type {HTMLTableElement} - * @private - */ - table: null, - /** - * 表格正文引用 - tbody - * @type {HTMLTableSectionElement} - * @private - */ - body: null, - /** - * 表格头部引用 - thead>tr - * @type {HTMLTableSectionElement} - * @private - */ - header: null, - /** - * 表格合计行引用 - tfooter>tr - * @type {HTMLTableSectionElement} - * @private - */ - footer: null, - /** - * 加载状态元素引用 - div.ui-loading - * @type {HTMLDivElement} - * @private - */ - loading: null, - /** - * 大小计算元素引用 - span.ui-grid-sizer - * @type {HTMLSpanElement} - * @private - */ - sizer: null, - /** - * 包装元素引用 - div.ui-grid-wrapper - * @type {HTMLDivElement} - * @private - */ - wrapper: null, - /** - * 拖拽块引用 - div.dragger - * @type {HTMLDivElement} - * @private - */ - dragger: null, - /** - * 拖拽光标引用 - layer.dragger-cursor - * @type {HTMLElement} - * @private - */ - draggerCursor: null, - } + refs: defaultRefs }; /** @@ -946,7 +646,7 @@ export class Grid { * @type {number | null} * @ignore */ - height; + height = null; /** * 是否允许多选 * @type {boolean} @@ -991,7 +691,7 @@ export class Grid { rowDraggable = false; /** * 监听事件的窗口载体 - * @type {(Window | HTMLElement)} + * @type {Window | HTMLElement | undefined} * @default window * @ignore */ @@ -1012,7 +712,7 @@ export class Grid { sortDirection = GridColumnDirection.Ascending; /** * 排序列数组 - * @type {GridColumnSortDefinition[]} + * @type {GridColumnSortDefinition[] | null} * @default null * @ignore */ @@ -1023,25 +723,27 @@ export class Grid { * @default false * @ignore */ - expandable; + expandable = false; /** * 扩展行生成器 - * @type {GridExpandableObjectCallback} + * @type {GridExpandableObjectCallback | undefined} * @ignore */ expandableGenerator; /** * 即将选中行时触发 + * @type {((this: IGrid, index: number, colIndex: number) => boolean | PromiseLike) | undefined} * @event * @param {number} index - 即将选中的行索引 * @param {number} colIndex - 即将选中的列索引 - * @returns {boolean} 返回 `false`、`null`、`undefined`、`0` 等则取消选中动作 + * @returns {boolean | PromiseLike} 返回 `false`、`null`、`undefined`、`0` 等则取消选中动作 * @this Grid */ willSelect; /** * 单元格单击时触发,colIndex 为 -1 则表示点击的是行的空白处 + * @type {((this: IGrid, index: number, colIndex: number) => boolean) | undefined} * @event * @param {number} index - 点击的行索引 * @param {number} colIndex - 点击的列索引 @@ -1052,13 +754,15 @@ export class Grid { /** * 选中行发生变化时触发的事件 + * @type {((this: IGrid, index: number | number[]) => void) | undefined} * @event - * @param {number} index - 选中的行索引 + * @param {number | number[]} index - 选中的行索引 * @this Grid */ onSelectedRowChanged; /** * 单元格双击时触发的事件,colIndex 为 -1 则表示点击的是行的空白处 + * @type {((this: IGrid, index: number, colIndex: number) => void) | undefined} * @event * @param {number} index - 双击的行索引 * @param {number} colIndex - 双击的列索引 @@ -1067,6 +771,7 @@ export class Grid { onCellDblClicked; /** * 行双击时触发的事件 + * @type {((this: IGrid, index: number) => void) | undefined} * @event * @param {number} index - 双击的行索引 * @this Grid @@ -1074,6 +779,7 @@ export class Grid { onRowDblClicked; /** * 列发生变化时触发的事件 + * @type {((this: IGrid, type: "reorder" | "resize" | "sort", colIndex: number, value: number | GridColumnDirection) => void) | undefined} * @event * @param {("reorder" | "resize" | "sort")} type - 事件类型 * @@ -1087,8 +793,9 @@ export class Grid { onColumnChanged; /** * 列滚动时触发的事件 + * @type {((this: IGrid, e: Event | null, index: number, count: number) => void) | undefined} * @event - * @param {Event} [e] - 滚动事件对象 + * @param {Event | null} e - 滚动事件对象 * @param {number} index - 起始行 * @param {number} count - 显示行数 * @this Grid @@ -1096,6 +803,7 @@ export class Grid { onBodyScrolled; /** * 扩展行展开时触发的事件 + * @type {((this: IGrid, item: GridRowItem, expandableObject: GridExpandableObject) => void) | undefined} * @event * @param {GridRowItem} item - 行数据对象 * @param {GridExpandableObject} expandableObject - 由 [expandableGenerator]{@linkcode Grid#expandableGenerator} 产生的行扩展对象 @@ -1105,6 +813,7 @@ export class Grid { onRowExpanded; /** * 扩展行收缩时触发的事件 + * @type {((this: IGrid, item: GridRowItem, expandableObject: GridExpandableObject) => void) | undefined} * @event * @param {GridRowItem} item - 行数据对象 * @param {GridExpandableObject} expandableObject - 由 [expandableGenerator]{@linkcode Grid#expandableGenerator} 产生的行扩展对象 @@ -1114,10 +823,11 @@ export class Grid { onRowCollapsed; /** * 行发生变化时触发的事件 + * @type {((this: IGrid, action: "update" | "add" | "remove" | "drag", items: GridRowItem[], indexes: number | number[]) => void) | undefined} * @event - * @param {("update" | "add" | "remove" | "drag")} action - 变动类型 + * @param {"update" | "add" | "remove" | "drag"} action - 变动类型 * @param {GridRowItem[]} items - 发生变动的行对象 - * @param {(number | number[])} indexes - 变动的索引集合 + * @param {number | number[]} indexes - 变动的索引集合 * @this Grid * @since 1.0.3 */ @@ -1125,7 +835,7 @@ export class Grid { /** * 列类型枚举 - * @type {GridColumnTypeEnum} + * @type {typeof GridColumnTypeEnum} * @property {number} Common=0 - 通用列(只读) * @property {number} Input=1 - 单行文本列 * @property {number} Dropdown=2 - 下拉选择列 @@ -1139,11 +849,8 @@ export class Grid { /** * Grid 控件构造函数 - * @param {(string | HTMLElement)?} container Grid 控件所在的父容器,可以是 string 表示选择器,也可以是 HTMLElement 对象
_**构造时可以不进行赋值,但是调用 init 函数时则必须进行赋值**_ - * @param {Function} [getText] 获取多语言文本的函数代理 - * @param {string} getText.id - 资源 ID - * @param {string} [getText.def] - 默认资源 - * @param {string} getText.{returns} 返回的多语言 + * @param {string | HTMLElement} [container] Grid 控件所在的父容器,可以是 string 表示选择器,也可以是 HTMLElement 对象
_**构造时可以不进行赋值,但是调用 init 函数时则必须进行赋值**_ + * @param {(key: string, defaultValue?: string | null) => string} [getText] 获取多语言文本的函数代理 * @property {GridColumnDefinition[]} columns - 列定义的数组 * @property {GridLanguages} [langs] - 多语言资源对象 * @property {string} [lgid=en] - 区域字符串 @@ -1190,7 +897,7 @@ export class Grid { /** * 获取 Grid 的页面元素 - * @type {HTMLDivElement} + * @type {HTMLDivElement | null} */ get element() { return this._var.el } @@ -1208,13 +915,13 @@ export class Grid { /** * 返回所有数据的数据(未过滤) - * @type {GridRowItem[]} + * @type {GridRowItem[] | undefined} */ get allSource() { return this._var.source?.map(s => s.values) } /** * 获取已过滤的数据中的扩展对象数组 - * @type {GridExpandableObject[]} + * @type {(GridExpandableObject | undefined)[] | undefined} * @property {HTMLElement} element - 扩展行元素 */ get sourceExpandable() { return this._var.currentSource?.map(s => s.__expandable_object) } @@ -1223,7 +930,7 @@ export class Grid { * 获取当前是否为虚模式状态 * @type {boolean} */ - get virtual() { return this._var.currentSource?.length > this.virtualCount } + get virtual() { return this._var.currentSource ? this._var.currentSource.length > this.virtualCount : false } /** * 获取当前排序的列关键字,为 null 则当前无排序列 @@ -1250,7 +957,10 @@ export class Grid { * @type {HTMLTableRowElement[]} */ get _tableRows() { - return Array.from(this._var.refs.body.children).filter(r => r.classList.contains('ui-grid-row')); + if (!this._var.refs.body) { + return []; + } + return /** @type {HTMLTableRowElement[]} */ (Array.from(this._var.refs.body.children)).filter(r => r.classList.contains('ui-grid-row')); } /** @@ -1258,7 +968,10 @@ export class Grid { * @type {HTMLTableCellElement[]} */ get _headerCells() { - return Array.from(this._var.refs.header.children).filter(h => h.tagName === 'TH' && h.classList.contains('column')); + if (!this._var.refs.header) { + return []; + } + return /** @type {HTMLTableCellElement[]} */ (Array.from(this._var.refs.header.children)).filter(h => h.tagName === 'TH' && h.classList.contains('column')); } /** @@ -1266,7 +979,10 @@ export class Grid { * @type {HTMLTableCellElement[]} */ get _footerCells() { - return Array.from(this._var.refs.footer.children).filter(f => f.classList.contains('ui-grid-cell')); + if (!this._var.refs.footer) { + return []; + } + return /** @type {HTMLTableCellElement[]} */ (Array.from(this._var.refs.footer.children)).filter(f => f.classList.contains('ui-grid-cell')); } /** @@ -1279,7 +995,7 @@ export class Grid { * 获取当前选中行的索引,为 -1 则当前没有选中行 * @type {number} */ - get selectedIndex() { return (this._var.selectedIndexes && this._var.selectedIndexes[0]) ?? -1 } + get selectedIndex() { return this._var.selectedIndexes[0] ?? -1 } /** * 获取或设置 Grid 是否为只读 @@ -1300,36 +1016,43 @@ export class Grid { if (!Array.isArray(list)) { throw new Error('source is not an Array.') } - list = list.reduce((array, item) => { - array.push({ - __level: 0, - values: item - }); - if (Array.isArray(item.__children)) { - array.push(...item.__children.map(c => ({ - __level: 1, - values: c - }))); - } - return array; - }, []); - list = list.map((it, index) => { + let lst = list.reduce( + /** + * @private + * @param {GridItemWrapper[]} array + * @param {GridRowItem} item + * @returns {GridItemWrapper[]} + */ + (array, item) => { + array.push({ + __level: 0, + values: item + }); + if (Array.isArray(item.__children)) { + array.push(...item.__children.map(c => ({ + __level: 1, + values: c + }))); + } + return array; + }, []); + lst = lst.map((it, index) => { return { __index: index, ...it }; }); - this._var.source = list; + this._var.source = lst; this._var.scrollLeft = 0; if (this._var.el != null) { this._var.el.scrollLeft = 0; } - this._refreshSource(list); + this._refreshSource(lst); } /** * 获取或设置合计行数据 - * @type {GridRowItem} + * @type {GridRowItem | null} * @since 1.0.1 */ get total() { return this._var.total } @@ -1358,7 +1081,7 @@ export class Grid { this.refresh(); } if (typeof this.onSelectedRowChanged === 'function') { - this.onSelectedRowChanged(); + this.onSelectedRowChanged(indexes); } } @@ -1373,37 +1096,40 @@ export class Grid { } if (flag === false) { this._var.refs.loading.style.visibility = 'hidden'; - this._var.refs.loading.style.opacity = 0; - this._var.el.style.overflow = ''; + this._var.refs.loading.style.opacity = '0'; + this._var.el && (this._var.el.style.overflow = ''); } else { this._var.refs.loading.style.visibility = 'visible'; - this._var.refs.loading.style.opacity = 1; - this._var.el.style.overflow = 'hidden'; + this._var.refs.loading.style.opacity = '1'; + this._var.el && (this._var.el.style.overflow = 'hidden'); } } /** * 获取或设置 Grid 当前滚动的偏移量 - * @type {number} + * @type {number | undefined} */ get scrollTop() { return this._var.el?.scrollTop; } set scrollTop(top) { if (this._var.el == null) { return; } - this._var.el.scrollTop = top; - this.reload(true); + if (top) { + this._var.el.scrollTop = top; + this.reload(true); + } } /** * 初始化Grid控件 - * @param {HTMLElement} [container=.ctor#container] - 父容器元素,若未传值则采用构造方法中传入的父容器元素 + * @param {HTMLElement | null} [container='.ctor#container'] - 父容器元素,若未传值则采用构造方法中传入的父容器元素 */ init(container = this._var.parent) { if (container == null) { throw new Error('no specified parent.'); } if (!(container instanceof HTMLElement)) { + /** @type {any} */ const ele = container[0]; if (!(ele instanceof HTMLElement)) { throw new Error(`parent type not supported. ${JSON.stringify(Object.getPrototypeOf(container))}`); @@ -1438,7 +1164,7 @@ export class Grid { }; } this._var.el = null; - this._var.refs = {}; + this._var.refs = defaultRefs; this._var.rendering = true; this._var.parent = container; this._var.isFirefox = /Firefox\//i.test(navigator.userAgent); @@ -1446,7 +1172,7 @@ export class Grid { const c = createElement('div', 'ui-grid-container'); this._var.container = c; const grid = createElement('div', 'ui-grid'); - grid.setAttribute('tabindex', 0); + grid.setAttribute('tabindex', '0'); grid.addEventListener('keydown', e => { let index = this.selectedIndex; let flag = false; @@ -1475,6 +1201,9 @@ export class Grid { } }); grid.addEventListener('mousedown', async e => { + if (!(e.target instanceof HTMLElement)) { + return; + } if (e.target === this._var.el) { if (e.offsetX < 0 || e.offsetX > e.target.clientWidth || e.offsetY < 0 || e.offsetY > e.target.clientHeight) { // except scroll bars @@ -1482,7 +1211,7 @@ export class Grid { } if (typeof this.willSelect === 'function') { let result = this.willSelect(-1, -1); - if (result instanceof Promise) { + if (isPromiseLike(result)) { result = await result; } if (!result) { @@ -1491,7 +1220,7 @@ export class Grid { } // cancel selections const selectedIndexes = this._var.selectedIndexes; - if (selectedIndexes?.length > 0) { + if (selectedIndexes.length > 0) { selectedIndexes.splice(0); } if (this.readonly) { @@ -1526,12 +1255,12 @@ export class Grid { grid.addEventListener('dragover', e => { e.preventDefault(); e.stopPropagation(); - e.dataTransfer.dropEffect = e.ctrlKey ? 'copy' : 'move'; + e.dataTransfer && (e.dataTransfer.dropEffect = e.ctrlKey ? 'copy' : 'move'); }); grid.addEventListener('drop', e => { e.preventDefault(); e.stopPropagation(); - const src = Number(e.dataTransfer.getData('text')); + const src = Number(e.dataTransfer?.getData('text')); if (isNaN(src) || src < 0) { return; } @@ -1540,7 +1269,7 @@ export class Grid { return; } const row = e.ctrlKey ? - Object.assign({}, this._var.currentSource[src]?.values) : + Object.assign({}, this._var.currentSource?.[src]?.values) : this.removeItem(src); this.addItem(row, target); this.selectedIndexes = [e.ctrlKey ? target : target - 1]; @@ -1576,6 +1305,9 @@ export class Grid { ); holder.addEventListener('mousedown', e => { const holder = e.currentTarget; + if (!(holder instanceof HTMLElement)) { + return; + } const row = Number(holder.dataset.row); const col = Number(holder.dataset.col); if (holder.classList.contains('active')) { @@ -1599,7 +1331,7 @@ export class Grid { this._var.rendering = false; if (this._var.source != null) { - if (this.sortArray?.length > 0) { + if (this.sortArray && this.sortArray.length > 0) { this.sort(true); } else if (this.sortIndex >= 0) { this.sortColumn(true); @@ -1622,6 +1354,9 @@ export class Grid { * @param {number} index - 待滚动至的行索引 */ scrollToIndex(index) { + if (this._var.el == null) { + return; + } const top = this._scrollToTop(index * (this.rowHeight + 1), true); this._var.el.scrollTop = top; } @@ -1630,19 +1365,19 @@ export class Grid { * 调整 Grid 元素的大小,一般需要在宽度变化时(如页面大小发生变化时)调用 * @param {boolean} [force] - 是否强制 [reload]{@linkcode Grid#reload},默认只有待渲染的行数发生变化时才会调用 * @param {boolean} [keep] - 是否保持当前滚动位置 - * @param {Function} [callback] - 计算大小后的回调函数,上下文为 Grid + * @param {(this: IGrid) => void} [callback] - 计算大小后的回调函数,上下文为 Grid */ resize(force, keep, callback) { if (this._var.rendering || this._var.el == null) { return; } const body = this._var.refs.body; - const top = this.headerVisible === false ? 0 : (this._var.refs.header.offsetHeight || this.rowHeight); + const top = this.headerVisible === false ? 0 : (this._var.refs.header?.offsetHeight || this.rowHeight); let height = this.height; if (height === 0) { height = this._var.containerHeight; - } else if (isNaN(height) || height < 0) { + } else if (height == null || isNaN(height) || height < 0) { height = this._var.el.offsetHeight - top; } const count = truncate((height - 1) / (this.rowHeight + 1)) + (RedumCount * 2) + 1; @@ -1662,8 +1397,12 @@ export class Grid { this.reload(keep); } } - this._var.wrapClientWidth = this._var.refs.wrapper.clientWidth; - this._var.bodyClientWidth = body.clientWidth; + if (this._var.refs.wrapper != null) { + this._var.wrapClientWidth = this._var.refs.wrapper.clientWidth; + } + if (body != null) { + this._var.bodyClientWidth = body.clientWidth; + } } /** @@ -1675,9 +1414,12 @@ export class Grid { return; } const filtered = this.columns.some(c => c.filterValues != null); - if ((filtered ^ this._var.colAttrs.__filtered) === 1) { + if (filtered !== this._var.colAttrs.__filtered) { this._var.colAttrs.__filtered = filtered; const headers = this._headerCells; + if (headers == null) { + return; + } for (let i = 0; i < this.columns.length; ++i) { const ele = headers[i].querySelector('.filter'); if (ele == null) { @@ -1695,17 +1437,19 @@ export class Grid { return; } else if (filtered) { const headers = this._headerCells; - for (let i = 0; i < this.columns.length; ++i) { - const ele = headers[i].querySelector('.filter'); - if (ele == null) { - continue; - } - if (this.columns[i].filterValues != null) { - ele.replaceChildren(createIcon('fa-solid', this.filteredIcon)); - ele.classList.add('active'); - } else { - ele.replaceChildren(createIcon('fa-solid', this.filterIcon)); - ele.classList.remove('active'); + if (headers != null) { + for (let i = 0; i < this.columns.length; ++i) { + const ele = headers[i].querySelector('.filter'); + if (ele == null) { + continue; + } + if (this.columns[i].filterValues != null) { + ele.replaceChildren(createIcon('fa-solid', this.filteredIcon)); + ele.classList.add('active'); + } else { + ele.replaceChildren(createIcon('fa-solid', this.filterIcon)); + ele.classList.remove('active'); + } } } } @@ -1718,11 +1462,16 @@ export class Grid { this._var.scrollTop = 0; this._var.startIndex = 0; this._var.el.scrollTop = 0; - this._var.refs.table.style.top = '0px'; + this._var.refs.table && (this._var.refs.table.style.top = '0px'); } - this._adjustRows(this._var.refs.body); + this._var.refs.body && this._adjustRows(this._var.refs.body); this.refresh(); // size adjustment + if (this._var.refs.wrapper == null || + this._var.refs.table == null || + this._var.refs.footer?.parentElement == null) { + return; + } const headerHeight = this._var.headerHeight || this.rowHeight; if (this.total != null) { const footerHeight = this._var.footerHeight || this.rowHeight; @@ -1873,7 +1622,7 @@ export class Grid { /** * 显示多列排序设置面板 - * @param {Function} [callback] - 更新回调函数 *@since* 1.0.3 + * @param {(this: IGrid, array: GridColumnSortDefinition[] | null, checked?: boolean) => void} [callback] - 更新回调函数 *@since* 1.0.3 * @param {boolean} [layout] - 是否显示更新 layout 复选框 *@since* 1.0.3 * @since 1.0.1 */ @@ -2110,7 +1859,7 @@ export class Grid { this.sort(); } if (typeof callback === 'function') { - callback.call(this, this.sortArray, pop.container.querySelector('.ui-sort-layout>input')?.checked); + callback.call(this, this.sortArray, pop.container?.querySelector('.ui-sort-layout>input')?.checked); } return true; } @@ -2468,11 +2217,14 @@ export class Grid { return Promise.resolve(Encoder.encode(json)); } return new Promise(resolve => { + /** @type {boolean} */ let working; let url; - let path = ScriptPath; - if (nullOrEmpty(path) && typeof consts !== 'undefined') { - path = consts.modulePath; + let path; + if (typeof global.consts !== 'undefined') { + path = `${location.origin}${global.consts.modulePath}`; + } else { + path = ''; } if (typeof module === 'string') { url = `${path}${module}`; @@ -2529,7 +2281,7 @@ export class Grid { /** * 展开/收折所有行 * @param {boolean} [expanded] - 是否展开,传 null 则切换展开状态 - * @returns {boolean} 展开状态 + * @returns {boolean | undefined} 展开状态 */ expandAll(expanded) { if (this._var.currentSource == null) { @@ -3054,7 +2806,7 @@ export class Grid { cell.appendChild(element); if (col.events != null) { for (let ev of Object.entries(col.events)) { - element[ev[0]] = e => { + element[ev[0]] = (/** @type {any} */ e) => { const item = this._var.currentSource[this._var.startIndex + exists + i].values; ev[1].call(item, e); }; @@ -3383,7 +3135,7 @@ export class Grid { } val ??= ''; const element = cell.children[0]; - GridColumn.setValue(element, val); + GridColumn.setValue(/** @type {HTMLElement} */(element), val); // auto resize if (this._var.needResize && this._get(col.key, 'autoResize')) { const width = element.scrollWidth + 12; @@ -3632,7 +3384,7 @@ export class Grid { * @private * @param {number} top * @param {boolean} [reload] - * @returns {number} + * @returns {{top: number; index: number}} */ _topToIndex(top, reload) { const rowHeight = (this.rowHeight + 1); @@ -3683,7 +3435,7 @@ export class Grid { * @returns {any} */ _get(key, name) { - const attr = this._var.colAttrs[key]; + const attr = getAttr(this._var.colAttrs, key); if (attr == null) { return null; } @@ -3697,7 +3449,7 @@ export class Grid { * @param {any} value */ _set(key, name, value) { - const attr = this._var.colAttrs[key]; + const attr = getAttr(this._var.colAttrs, key); if (attr == null) { this._var.colAttrs[key] = { [name]: value }; } else { @@ -4215,7 +3967,7 @@ export class Grid { } } }; - let attr = this._var.colAttrs[col.key]; + let attr = getAttr(this._var.colAttrs, col.key); if (attr == null) { attr = this._var.colAttrs[col.key] = {}; } else { @@ -4280,7 +4032,7 @@ export class Grid { } } }; - let attr = this._var.colAttrs[col.key]; + let attr = getAttr(this._var.colAttrs, col.key); if (attr == null) { attr = this._var.colAttrs[col.key] = {}; } else { @@ -4422,15 +4174,15 @@ export class Grid { * 清除 tooltip 显示框,并延时后设置 `display: none` * 不设置 display 的话会导致元素依然被算入滚动范围,从而影响滚动条显示 * @private - * @param {HTMLDivElement} holder + * @param {HTMLElement} holder */ _clearHolder(holder) { - if (this._var.tooltipTimer != null) { + if (this._var.tooltipTimer > 0) { clearTimeout(this._var.tooltipTimer); } this._var.tooltipTimer = setTimeout(() => { holder.style.display = 'none'; - this._var.tooltipTimer = null; + this._var.tooltipTimer = 0; }, 120); } @@ -4599,7 +4351,7 @@ export class Grid { if (typeof this.willSelect === 'function') { const selectedIndex = this._var.startIndex + index; let result = this.willSelect(selectedIndex, colIndex); - if (result instanceof Promise) { + if (isPromiseLike(result)) { result = await result; } if (!result) { diff --git a/lib/ui/popup.js b/lib/ui/popup.js index 8d853b4..a0eccc7 100644 --- a/lib/ui/popup.js +++ b/lib/ui/popup.js @@ -1,7 +1,7 @@ import "./css/popup.scss"; import { r as lang } from "../utility/lgres"; import { nullOrEmpty } from "../utility/strings"; -import { global } from "../utility"; +import { global, isPromiseLike } from "../utility"; import { appendResizer, makeMovable } from "./movable"; import { createElement, mergeOptions } from "../functions"; import { createIcon, changeIcon } from "./icon"; @@ -352,17 +352,20 @@ export class Popup { } else { this._var.__resolved = false; } - } else if (typeof result?.then === 'function') { - result.then(r => { + } else if (isPromiseLike(result)) { + const tmp = result.then(r => { if (r !== false) { this.close(r); } else { this._var.__resolved = false; } - }).catch(reason => { - this._var.__resolved = false; - console.warn(reason); }); + if ('catch' in tmp && typeof tmp.catch === 'function') { + tmp.catch(/** @param {any} reason */ reason => { + this._var.__resolved = false; + console.warn(reason); + }); + } } else { this.close(); } diff --git a/lib/utility.js b/lib/utility.js index 54ae9b1..7853248 100644 --- a/lib/utility.js +++ b/lib/utility.js @@ -22,6 +22,19 @@ function isMobile() { return /mobile/i.test(navigator.userAgent); } +/** + * @param {unknown} value + * @returns {value is PromiseLike} + */ +function isPromiseLike(value) { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + 'then' in value && + typeof value.then === 'function' + ); +} + /** * @template {any[]} TArgs * @template [TContext=typeof globalThis] @@ -157,6 +170,7 @@ export { g as global, isPositive, isMobile, + isPromiseLike, // functions mergeOptions, throttle,