isPromiseLike and resolve partial of Grid.

This commit is contained in:
lchen committed 2026-11-25 17:00:03 +08:00
1 parent ec086e29aa
commit a78ef2df39
7 files changed
+1359 -619

No files matched your search

+6 -5
View File
@@ -1,5 +1,5 @@
import { Grid, GridColumn, createElement, setTooltip, createIcon, createCheckbox, createRadiobox, showAlert, showConfirm, Popup, requestAnimationFrame } from "../../ui"; 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 { createBox, appendMedia, fileSupported, insertFile, getMessageSendTo, getMessageStatus, updateCustomerName, createHideMessageTitleButton, createHideMessageCommentTail } from "./lib";
import { Contact, CustomerRecordContact } from "./contact"; import { Contact, CustomerRecordContact } from "./contact";
import Follower from "./follower"; import Follower from "./follower";
@@ -764,7 +764,7 @@ export default class CustomerCommunication {
if (typeof option.onOpenSelectCRContacts === 'function') { if (typeof option.onOpenSelectCRContacts === 'function') {
const result = option.onOpenSelectCRContacts(); const result = option.onOpenSelectCRContacts();
if (typeof result?.then === 'function') { if (isPromiseLike(result)) {
return result.then(r => { return result.then(r => {
r.map(c => { r.map(c => {
for (let cc of this._var.data.contacts) { for (let cc of this._var.data.contacts) {
@@ -822,7 +822,7 @@ export default class CustomerCommunication {
} }
if (typeof option.onSave === 'function') { if (typeof option.onSave === 'function') {
const result = option.onSave(item, true); const result = option.onSave(item, true);
if (typeof result?.then === 'function') { if (isPromiseLike(result)) {
return result.then(r => { return result.then(r => {
this._var.gridContact.source = r.filter(c => c.Id >= 0).map(c => { this._var.gridContact.source = r.filter(c => c.Id >= 0).map(c => {
if (c.OptOut || c.OptOut_BC) { if (c.OptOut || c.OptOut_BC) {
@@ -944,7 +944,7 @@ export default class CustomerCommunication {
} }
if (typeof option.onSave === 'function') { if (typeof option.onSave === 'function') {
const result = option.onSave(item); const result = option.onSave(item);
if (typeof result?.then === 'function') { if (isPromiseLike(result)) {
return result.then(r => { return result.then(r => {
This._var.gridContact.source = r.filter(c => c.Id >= 0).map(c => { This._var.gridContact.source = r.filter(c => c.Id >= 0).map(c => {
if (c.OptOut || c.OptOut_BC) { if (c.OptOut || c.OptOut_BC) {
@@ -1205,9 +1205,10 @@ export default class CustomerCommunication {
onOk: list => { onOk: list => {
if (typeof option.onAddFollower === 'function') { if (typeof option.onAddFollower === 'function') {
const result = option.onAddFollower(list); const result = option.onAddFollower(list);
if (typeof result?.then === 'function') { if (isPromiseLike(result)) {
return result.then(r => { return result.then(r => {
// this.followers = r; // this.followers = r;
// TODO: ?? maybe a bug? doing nothing...
return r; return r;
}); });
} }
+6 -5
View File
@@ -4,11 +4,12 @@ declare global {
interface Window { interface Window {
GetTextByKey?: (key: string, defaultValue?: string | null) => string; GetTextByKey?: (key: string, defaultValue?: string | null) => string;
consts?: { consts?: {
resver: number, resver: number;
path: string, path: string;
prefix: string, prefix: string;
cookie?: { lang: string }, modulePath?: string;
user?: { language: string } cookie?: { lang: string };
user?: { language: string };
}; };
_network?: { root: string }; _network?: { root: string };
_net?: { root: string }; _net?: { root: string };
+939 -3
View File
@@ -1,3 +1,5 @@
import { GridColumn } from "./ui";
export type GetTextCallback = (key: string, defaultValue?: string | null) => string; export type GetTextCallback = (key: string, defaultValue?: string | null) => string;
export interface LanguageResource { export interface LanguageResource {
@@ -83,7 +85,7 @@ export interface Popup {
close(result?: any, animation?: boolean): void; close(result?: any, animation?: boolean): void;
create(): HTMLDivElement; create(): HTMLDivElement;
show(parent?: HTMLElement, hidden?: boolean): Promise<HTMLElement> | undefined; show(parent?: HTMLElement, hidden?: boolean): PromiseLike<HTMLElement> | undefined;
} }
export interface PopupButton { export interface PopupButton {
@@ -98,7 +100,7 @@ export interface PopupButton {
* @param button 触发的按钮 * @param button 触发的按钮
* @returns 返回 false 则阻止窗口关闭 * @returns 返回 false 则阻止窗口关闭
*/ */
trigger?: (this: PopupButton, popup: Popup) => boolean | string | number | Promise<boolean | string | number> | undefined; trigger?: (this: PopupButton, popup: Popup) => boolean | string | number | PromiseLike<boolean | string | number> | undefined;
} }
export interface PopupOptions { export interface PopupOptions {
@@ -291,9 +293,943 @@ export interface DropdownOptions {
/** 是否固定为向下展开 */ /** 是否固定为向下展开 */
slideFixed?: boolean; slideFixed?: boolean;
/** 父元素,默认添加到头元素之后 */ /** 父元素,默认添加到头元素之后 */
wrapper?: HTMLElement; wrapper?: HTMLElement | null;
/** 是否忽略 All 选项 */ /** 是否忽略 All 选项 */
ignoreAll?: boolean; ignoreAll?: boolean;
/** 获取文本的代理函数 */ /** 获取文本的代理函数 */
getText?: GetTextCallback; getText?: GetTextCallback;
} }
export interface ValueItem {
Value: any;
DisplayValue: string;
__checked?: boolean;
}
export type GridRowItem = Record<string, ValueItem | any>;
export interface GridSourceItemBase {
value?: string;
text?: string;
}
export type GridSourceItem = GridSourceItemBase & Record<string, string>;
export interface GridExpandableObject {
element: HTMLElement;
}
export type GridExpandableObjectCallback = (this: Grid, item: GridRowItem) => GridExpandableObject;
/** 行数据包装接口 */
export interface GridItemWrapper {
/** 真实数据对象 */
values: GridRowItem;
/** 下拉数据源缓存对象 */
source?: Record<string, GridSourceItem[]>;
/** 缩进层级 */
__level: number;
/** 行索引 */
__index?: number;
/** 批量删除时暂存的索引偏移量 */
__offset?: number;
/** 正在编辑的列的原始值字典 */
__editing?: Record<string, any>;
/** 行数据是否发生改变 */
__changed?: boolean;
/** 行是否已展开 */
__expanded?: boolean;
/** 行扩展对象 */
__expandable_object?: GridExpandableObject;
}
/**
* 列定义基类
*
* _函数调用流程图示_<br/>
* <img src="./assets/column-refresh.jpg" alt="Column Refresh"/>
* @static
* @hideconstructor
*/
export interface GridColumn<TValue = string | boolean | number | Date> {
/**
* 该属性返回 `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} 方法<br/>
* 更多例子参考代码中 {@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<string, string>): 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<string> {
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<string> {
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<GridSourceItemBase>;
static leaveEdit(element: HTMLDivElement, container: HTMLElement): void;
/** @ignore */
static toString(): 'GridDropdown';
}
export interface GridCheckboxColumn extends GridColumn<boolean> {
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<string> {
/** @ignore */
static toString(): 'GridIcon';
}
export interface GridDateColumn extends GridColumn<string | number | Date> {
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<T> = (this: GridColumnDefinition, item: GridRowItem) => T;
export type GridItemObjectCallback = GridItemCallbackBase<Record<string, string>>;
export type GridItemStringCallback = GridItemCallbackBase<string>;
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<string, string>;
/** 列标题的帮助文本 */
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 控件的 `<tbody>` 部分
* @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<string, string>;
/** 合计行样式(仅在重建合计行元素时读取) */
totalCss?: Record<string, string>;
/** 单元格样式(填充行列数据时读取),支持直接返回样式对象或调用函数返回 */
style?: Record<string, string> | GridItemObjectCallback;
/** 设置单元格背景色(填充行列数据时读取),支持直接设置颜色字符串或调用函数返回 */
background?: string | GridItemStringCallback;
/** 复选框为 `ui-switch` 样式 *@since* 1.0.6 */
switch?: boolean;
/** 根据返回值设置单元格元素的附加属性,允许直接设置对象也支持调用函数返回对象 */
attrs?: Record<string, any> | ((this: GridColumnDefinition, item: GridRowItem) => Record<string, any>);
/** 给单元格元素附加事件(事件函数上下文为数据行对象) */
events?: Record<string, (this: GridRowItem, e?: any) => 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<GridSourceItem[]> | ((item: GridRowItem) => GridSourceItem[] | PromiseLike<GridSourceItem[]>);
/** 下拉列表数据源是否缓存结果(即行数据未发生变化时仅从 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;
/**
* 列定义接口
*
* <img src="./assets/column-types.png" alt="Column Types"/><br/>
* 代码参考页面下方的示例
* @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 控件基础类
*
* <img src="./assets/grid-sample.png" alt="Grid Sample"/><br/>
* 函数调用流程图<br/>
* <img src="./assets/grid.jpg" alt="Grid"/>
* @example <caption>基础示例</caption>
* <div id="grid"></div>
* @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<boolean>;
/**
* 单元格单击时触发,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<GridExportData>;
/**
* 展开/收折所有行
* @param expanded 是否展开,传 null 则切换展开状态
* @returns 返回展开状态
*/
expandAll(expanded?: boolean): boolean | undefined;
}
+115 -82
View File
@@ -1,4 +1,4 @@
import { global } from "../../utility"; import { global, isPromiseLike, isTag } from "../../utility";
import { createElement } from "../../functions"; import { createElement } from "../../functions";
import { createIcon } from "../icon"; import { createIcon } from "../icon";
import { createCheckbox, createRadiobox } from "../checkbox"; import { createCheckbox, createRadiobox } from "../checkbox";
@@ -6,16 +6,8 @@ import { createCheckbox, createRadiobox } from "../checkbox";
import { Dropdown } from "../dropdown"; import { Dropdown } from "../dropdown";
import { convertCssStyle } from "../extension"; import { convertCssStyle } from "../extension";
import { createDateInput, formatDate, setDateValue, getDateValue } from "../date"; import { createDateInput, formatDate, setDateValue, getDateValue } from "../date";
// definition
/** @import { GridRowItem, DropdownOptions, GridColumnDefinition, GridSourceItem, GridItemWrapper, Grid } from "./grid" */
/** /** @import { DropdownOptions, DropdownItem, Dropdown as IDropdown, GridSourceItemBase, GridSourceItem, GridItemWrapper, GridColumnDefinition, Grid } from '../../types' */
* @ignore
* @callback DropExpandedCallback
* @param {GridRowItem} item - 行数据对象
* @param {Dropdown} drop - 下拉框对象
* @this GridColumnDefinition
*/
/** /**
* 列定义基类 * 列定义基类
@@ -47,20 +39,19 @@ export class GridColumn {
/** /**
* 标记该类型是否支持列头批量操作 * 标记该类型是否支持列头批量操作
* @member * @member
* @name GridColumn.headerEditing
* @readonly
* @type {boolean} * @type {boolean}
*/ */
static get headerEditing() { return false; }
/** /**
* 创建显示单元格时调用的方法 * 创建显示单元格时调用的方法
* @param {GridColumnDefinition} col - 列定义对象 * @param {GridColumnDefinition} _col - 列定义对象
* @param {number} index - 行元素索引(需要配合 [startIndex]{@linkcode Grid#startIndex} 相加得到真实数据索引) * @param {number} [_index] - 行元素索引(需要配合 [startIndex]{@linkcode Grid#startIndex} 相加得到真实数据索引)
* @param {Grid} grid - Grid 实例 * @param {Grid} [_grid] - Grid 实例
* @returns {HTMLElement} 返回创建的单元格元素 * @returns {HTMLElement} 返回创建的单元格元素
* @virtual * @virtual
*/ */
static create() { static create(_col, _index, _grid) {
return createElement('span'); return createElement('span');
} }
@@ -71,11 +62,10 @@ export class GridColumn {
* 更多例子参考代码中 {@linkcode GridDropdownColumn} 的实现。 * 更多例子参考代码中 {@linkcode GridDropdownColumn} 的实现。
* @method * @method
* @name GridColumn.createEdit * @name GridColumn.createEdit
* @param {Function} trigger - 编辑事件回调函数 * @param {(e: any) => void} _trigger - 编辑事件回调函数,参数会传递给 [getValue]{@linkcode GridColumn.getValue} 方法
* @param {any} trigger.e - 该参数会传递给 [getValue]{@linkcode GridColumn.getValue} 方法 * @param {GridColumnDefinition} _col - 列定义对象
* @param {GridColumnDefinition} col - 列定义对象 * @param {HTMLElement} [_container] - 父容器元素
* @param {HTMLElement} [container] - 父容器元素 * @param {GridItemWrapper} [_wrapper] - 行包装对象,其 `values` 属性为行数据对象
* @param {GridItemWrapper} [wrapper] - 行包装对象,其 `values` 属性为行数据对象
* @returns {HTMLElement} 返回创建的编辑状态的单元格元素 * @returns {HTMLElement} 返回创建的编辑状态的单元格元素
* @virtual * @virtual
*/ */
@@ -104,27 +94,27 @@ export class GridColumn {
* @name GridColumn.getValue * @name GridColumn.getValue
* @param {any} e - 由 [createEdit]{@linkcode GridColumn.createEdit} 方法中 `trigger` 函数传递来的对象 * @param {any} e - 由 [createEdit]{@linkcode GridColumn.createEdit} 方法中 `trigger` 函数传递来的对象
* @param {GridColumnDefinition} col - 列定义对象 * @param {GridColumnDefinition} col - 列定义对象
* @returns {(string | boolean | number)} 返回单元格的值 * @returns {(string | boolean | number | Date)} 返回单元格的值
* @virtual * @virtual
*/ */
/** /**
* 设置单元格值时调用的方法 * 设置单元格值时调用的方法
* @param {HTMLElement} element - 单元格元素 * @param {HTMLElement} element - 单元格元素
* @param {(string | boolean | number)} val - 待设置的单元格值 * @param {(string | boolean | number | Date)} val - 待设置的单元格值
* @param {GridItemWrapper} wrapper - 行包装对象 * @param {GridItemWrapper} [_wrapper] - 行包装对象
* @param {GridColumnDefinition} col - 列定义对象 * @param {GridColumnDefinition} [_col] - 列定义对象
* @param {Grid} grid - Grid 对象 * @param {Grid} [_grid] - Grid 对象
* @virtual * @virtual
*/ */
static setValue(element, val) { static setValue(element, val, _wrapper, _col, _grid) {
element.innerText = val; element.innerText = String(val);
} }
/** /**
* 设置单元格样式时调用的方法 * 设置单元格样式时调用的方法
* @param {HTMLElement} element - 单元格元素 * @param {HTMLElement} element - 单元格元素
* @param {object} style - 样式对象 * @param {Object.<string, string>} style - 样式对象
* @virtual * @virtual
*/ */
static setStyle(element, style) { static setStyle(element, style) {
@@ -148,10 +138,11 @@ export class GridColumn {
* 设置单元格可用性时调用的方法 * 设置单元格可用性时调用的方法
* @param {HTMLElement} element - 单元格元素 * @param {HTMLElement} element - 单元格元素
* @param {boolean} enabled - 启用值,为 `false` 时代表禁用 * @param {boolean} enabled - 启用值,为 `false` 时代表禁用
* @param {boolean} editing - 是否处于编辑状态 * @param {boolean} [_editing] - 是否处于编辑状态
* @virtual * @virtual
*/ */
static setEnabled(element, enabled) { static setEnabled(element, enabled, _editing) {
/** @type {HTMLElement | null} */
const tooltip = element.querySelector('.ui-tooltip-wrapper'); const tooltip = element.querySelector('.ui-tooltip-wrapper');
if (tooltip != null) { if (tooltip != null) {
tooltip.style.display = enabled === false ? 'none' : ''; tooltip.style.display = enabled === false ? 'none' : '';
@@ -221,7 +212,7 @@ export class GridInputColumn extends GridColumn {
/** /**
* @ignore * @ignore
* @param {Function} trigger * @param {(this: HTMLElement, e: Event) => any} trigger
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @param {HTMLElement} _container * @param {HTMLElement} _container
* @param {GridItemWrapper} wrapper * @param {GridItemWrapper} wrapper
@@ -239,9 +230,12 @@ export class GridInputColumn extends GridColumn {
* @ignore * @ignore
* @param {HTMLElement} element * @param {HTMLElement} element
* @param {string} val * @param {string} val
* @param {GridItemWrapper} [_wrapper]
* @param {GridColumnDefinition} [_col]
* @param {Grid} [_grid]
*/ */
static setValue(element, val) { static setValue(element, val, _wrapper, _col, _grid) {
if (element.tagName !== 'INPUT') { if (!isTag(element, 'input')) {
super.setValue(element, val); super.setValue(element, val);
} else { } else {
element.value = val; element.value = val;
@@ -253,7 +247,12 @@ export class GridInputColumn extends GridColumn {
* @param {Event} e * @param {Event} e
* @returns {string} * @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 * @ignore
@@ -262,7 +261,9 @@ export class GridInputColumn extends GridColumn {
*/ */
static setEnabled(element, enabled) { static setEnabled(element, enabled) {
super.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 { export class GridTextColumn extends GridInputColumn {
/** /**
* @ignore * @ignore
* @param {Function} trigger * @param {(this: HTMLTextAreaElement, ev: Event) => any} trigger
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @param {HTMLElement} _container * @param {HTMLElement} _container
* @param {GridItemWrapper} wrapper * @param {GridItemWrapper} wrapper
* @returns {HTMLElement} * @returns {HTMLTextAreaElement}
*/ */
static createEdit(trigger, col, _container, wrapper) { static createEdit(trigger, col, _container, wrapper) {
const input = createElement('textarea'); const input = createElement('textarea');
@@ -304,7 +305,7 @@ export class GridTextColumn extends GridInputColumn {
* @param {Grid} grid * @param {Grid} grid
*/ */
static setValue(element, val, _wrapper, _col, grid) { static setValue(element, val, _wrapper, _col, grid) {
if (element.tagName !== 'TEXTAREA') { if (!isTag(element, 'textarea')) {
super.setValue(element, val); super.setValue(element, val);
} else { } else {
element.value = val; element.value = val;
@@ -322,7 +323,7 @@ export class GridTextColumn extends GridInputColumn {
static toString() { return 'GridText' } 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 * @ignore
* @param {Function} trigger * @param {(this: IDropdown, it?: DropdownItem) => void} trigger
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @param {HTMLElement} container * @param {HTMLElement} container
* @param {GridItemWrapper} wrapper * @param {GridItemWrapper} wrapper
* @returns {HTMLElement} * @returns {HTMLDivElement}
*/ */
static createEdit(trigger, col, container, wrapper) { static createEdit(trigger, col, container, wrapper) {
const drop = new Dropdown({ const drop = new Dropdown({
@@ -379,10 +380,10 @@ export class GridDropdownColumn extends GridColumn {
/** /**
* @ignore * @ignore
* @param {HTMLElement} element * @param {HTMLElement} element
* @returns {HTMLElement} * @returns {Element}
*/ */
static getElement(element) { static getElement(element) {
if (element.tagName === 'DIV') { if (isTag(element, 'div')) {
return element.children[0].children[0]; return element.children[0].children[0];
} }
return element.children[0]; return element.children[0];
@@ -391,17 +392,20 @@ export class GridDropdownColumn extends GridColumn {
/** /**
* @private * @private
* @param {HTMLElement} element * @param {HTMLElement} element
* @returns {Dropdown} * @returns {Dropdown | null}
*/ */
static _getDrop(element) { static _getDrop(element) {
/** /**
* @type {Map<string, Dropdown>} * @type {Object.<string, Dropdown>}
*/ */
const dropGlobal = global[SymbolDropdown]; const dropGlobal = /** @type {Record<symbol, any | undefined>} */ (/** @type {unknown} */ (global))[SymbolDropdown];
if (dropGlobal == null) { if (dropGlobal == null) {
return null; return null;
} }
const dropId = element.dataset.dropId; const dropId = element.dataset.dropId;
if (dropId == null) {
return null;
}
const drop = dropGlobal[dropId]; const drop = dropGlobal[dropId];
if (drop == null) { if (drop == null) {
return null; return null;
@@ -413,7 +417,7 @@ export class GridDropdownColumn extends GridColumn {
* @private * @private
* @param {GridItemWrapper} wrapper * @param {GridItemWrapper} wrapper
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @returns {GridSourceItem[]} * @returns {GridSourceItem[] | PromiseLike<GridSourceItem[]> | null}
*/ */
static _getSource(wrapper, col) { static _getSource(wrapper, col) {
let source; let source;
@@ -427,45 +431,58 @@ export class GridDropdownColumn extends GridColumn {
if (typeof source === 'function') { if (typeof source === 'function') {
source = source(wrapper.values); source = source(wrapper.values);
} }
if (col.sourceCache !== false) { if (source) {
if (wrapper.source == null) { if (col.sourceCache !== false) {
wrapper.source = { [col.key]: source }; if (isPromiseLike(source)) {
} else { source.then(s => {
wrapper.source[col.key] = source; 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 * @private
* @param {GridSourceItem[]} source * @param {GridSourceItem[]} source
* @param {HTMLElement} element * @param {HTMLElement} element
* @param {any} val * @param {string} val
* @param {DropdownOptions} opts * @param {DropdownOptions} [opts]
*/ */
static _setValue(source, element, val, opts) { static _setValue(source, element, val, opts) {
const data = source?.find(v => v[opts?.valueKey ?? 'value'] === val); const data = source?.find(v => v[opts?.valueKey ?? 'value'] === val);
if (data != null) { if (data != null) {
val = data[opts?.textKey ?? 'text']; val = data[opts?.textKey ?? 'text'];
} }
element.children[0].innerText = val; /** @type {HTMLElement} */ (element.children[0]).innerText = val;
} }
/** /**
* @ignore * @ignore
* @param {HTMLElement} element * @param {HTMLElement} element
* @param {any} val * @param {string} val
* @param {GridItemWrapper} wrapper * @param {GridItemWrapper} wrapper
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @param {Grid} grid * @param {Grid} grid
*/ */
static setValue(element, val, wrapper, col, grid) { static setValue(element, val, wrapper, col, grid) {
if (element.tagName !== 'DIV') { if (!isTag(element, 'div')) {
let source = this._getSource(wrapper, col); let source = this._getSource(wrapper, col);
if (source instanceof Promise) { if (isPromiseLike(source)) {
source.then(s => this._setValue(s, element, val, col.dropOptions)); source.then(s => this._setValue(s, element, val, col.dropOptions));
} else { } else if (source) {
this._setValue(source, element, val, col.dropOptions); this._setValue(source, element, val, col.dropOptions);
} }
return; return;
@@ -477,7 +494,7 @@ export class GridDropdownColumn extends GridColumn {
const ignoreCase = col.dropRestrictCase !== true; const ignoreCase = col.dropRestrictCase !== true;
if (drop.source == null || drop.source.length === 0) { if (drop.source == null || drop.source.length === 0) {
let source = this._getSource(wrapper, col); let source = this._getSource(wrapper, col);
if (source instanceof Promise) { if (isPromiseLike(source)) {
source.then(s => { source.then(s => {
drop.source = s; drop.source = s;
drop.select(val, true, ignoreCase); drop.select(val, true, ignoreCase);
@@ -499,6 +516,7 @@ export class GridDropdownColumn extends GridColumn {
if (item == null) { if (item == null) {
let text; let text;
if (col.text == null && typeof col.filter === 'function') { if (col.text == null && typeof col.filter === 'function') {
// @ts-ignore
text = col.filter(wrapper.values, false, grid._var.refs.body); text = col.filter(wrapper.values, false, grid._var.refs.body);
} else { } else {
text = val; text = val;
@@ -516,7 +534,7 @@ export class GridDropdownColumn extends GridColumn {
* @ignore * @ignore
* @param {GridSourceItem} e * @param {GridSourceItem} e
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @returns {any} * @returns {Required<GridSourceItemBase>}
*/ */
static getValue(e, col) { static getValue(e, col) {
return { return {
@@ -531,7 +549,7 @@ export class GridDropdownColumn extends GridColumn {
* @param {string} name * @param {string} name
*/ */
static setClass(element, name) { static setClass(element, name) {
if (element.tagName === 'DIV') { if (isTag(element, 'div')) {
element.className = `ui-drop-wrapper ${name ?? ''}`; element.className = `ui-drop-wrapper ${name ?? ''}`;
} else { } else {
super.setClass(element, name); super.setClass(element, name);
@@ -554,11 +572,11 @@ export class GridDropdownColumn extends GridColumn {
/** /**
* @ignore * @ignore
* @param {HTMLElement} element * @param {HTMLDivElement} element
* @param {HTMLElement} container * @param {HTMLElement} container
*/ */
static leaveEdit(element, 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) { if (e != null) {
e.classList.remove('active'); e.classList.remove('active');
} }
@@ -591,11 +609,12 @@ export class GridCheckboxColumn extends GridColumn {
/** /**
* @ignore * @ignore
* @param {Function} trigger * @param {(this: HTMLInputElement, ev: Event) => any} trigger
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @returns {HTMLElement} * @param {number} [_index]
* @returns {HTMLLabelElement}
*/ */
static createEdit(trigger, col) { static createEdit(trigger, col, _index) {
const check = createCheckbox({ const check = createCheckbox({
switch: col.switch, switch: col.switch,
onchange: trigger onchange: trigger
@@ -610,7 +629,9 @@ export class GridCheckboxColumn extends GridColumn {
*/ */
static setValue(element, val) { static setValue(element, val) {
// element.querySelector('input').checked = 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 * @param {Event} e
* @returns {boolean} * @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 * @ignore
@@ -626,7 +652,7 @@ export class GridCheckboxColumn extends GridColumn {
* @param {string} name * @param {string} name
*/ */
static setClass(element, name) { static setClass(element, name) {
if (element.tagName === 'LABEL') { if (isTag(element, 'label')) {
element.className = `ui-check-wrapper ${name ?? ''}`; element.className = `ui-check-wrapper ${name ?? ''}`;
} else { } else {
super.setClass(element, name); super.setClass(element, name);
@@ -641,7 +667,9 @@ export class GridCheckboxColumn extends GridColumn {
static setEnabled(element, enabled) { static setEnabled(element, enabled) {
super.setEnabled(element, enabled); super.setEnabled(element, enabled);
// element.querySelector('input').disabled = enabled === false; // 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 { export class GridRadioboxColumn extends GridCheckboxColumn {
/** /**
* @ignore * @ignore
* @param {Function} trigger * @param {(this: HTMLInputElement, ev: Event) => any} trigger
* @param {GridColumnDefinition} _col * @param {GridColumnDefinition} _col
* @param {number} index * @param {number} index
* @returns {HTMLElement} * @returns {HTMLLabelElement}
*/ */
static createEdit(trigger, _col, index) { static createEdit(trigger, _col, index) {
const check = createRadiobox({ const check = createRadiobox({
@@ -769,7 +797,7 @@ export class GridDateColumn extends GridColumn {
/** /**
* @ignore * @ignore
* @param {Function} trigger * @param {(this: HTMLInputElement, ev: FocusEvent) => any} trigger
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @param {HTMLElement} _container * @param {HTMLElement} _container
* @param {GridItemWrapper} wrapper * @param {GridItemWrapper} wrapper
@@ -779,11 +807,11 @@ export class GridDateColumn extends GridColumn {
let enabled = col.enabled; let enabled = col.enabled;
if (typeof enabled === 'string') { if (typeof enabled === 'string') {
enabled = wrapper.values[enabled]; enabled = wrapper.values[enabled];
} else if (typeof enabled === 'function') { } else if (typeof col.enabled === 'function') {
enabled = col.enabled(wrapper.values); enabled = col.enabled(wrapper.values);
} }
if (enabled === false) { if (enabled === false) {
return super.create(); return super.create(col);
} }
const date = createDateInput(col.dateMin, col.dateMax); const date = createDateInput(col.dateMin, col.dateMax);
date.addEventListener('change', () => super._changeValue(col.key, wrapper, date.value)); date.addEventListener('change', () => super._changeValue(col.key, wrapper, date.value));
@@ -806,10 +834,13 @@ export class GridDateColumn extends GridColumn {
* @ignore * @ignore
* @param {Event} e * @param {Event} e
* @param {GridColumnDefinition} col * @param {GridColumnDefinition} col
* @returns {string} * @returns {string | GridSourceItemBase}
*/ */
static getValue(e, col) { static getValue(e, col) {
if (e.target.tagName === 'INPUT') { if (!(e.target instanceof HTMLElement)) {
return '';
}
if (isTag(e.target, 'input')) {
return { return {
value: getDateValue(e.target, col.dateValueFormatter), value: getDateValue(e.target, col.dateValueFormatter),
text: getDateValue(e.target, col.dateDisplayFormatter) text: getDateValue(e.target, col.dateDisplayFormatter)
@@ -824,7 +855,7 @@ export class GridDateColumn extends GridColumn {
* @param {string} name * @param {string} name
*/ */
static setClass(element, name) { static setClass(element, name) {
if (element.tagName === 'INPUT') { if (isTag(element, 'input')) {
element.className = `ui-date-cell ${name ?? ''}`; element.className = `ui-date-cell ${name ?? ''}`;
} else { } else {
super.setClass(element, name); super.setClass(element, name);
@@ -837,7 +868,9 @@ export class GridDateColumn extends GridColumn {
* @param {boolean} enabled * @param {boolean} enabled
*/ */
static setEnabled(element, enabled) { static setEnabled(element, enabled) {
element.disabled = enabled === false; if (isTag(element, 'input')) {
element.disabled = enabled === false;
}
} }
/** /**
+270 -518
View File
File diff suppressed because it is too large. Load diff
+9 -6
View File
@@ -1,7 +1,7 @@
import "./css/popup.scss"; import "./css/popup.scss";
import { r as lang } from "../utility/lgres"; import { r as lang } from "../utility/lgres";
import { nullOrEmpty } from "../utility/strings"; import { nullOrEmpty } from "../utility/strings";
import { global } from "../utility"; import { global, isPromiseLike } from "../utility";
import { appendResizer, makeMovable } from "./movable"; import { appendResizer, makeMovable } from "./movable";
import { createElement, mergeOptions } from "../functions"; import { createElement, mergeOptions } from "../functions";
import { createIcon, changeIcon } from "./icon"; import { createIcon, changeIcon } from "./icon";
@@ -352,17 +352,20 @@ export class Popup {
} else { } else {
this._var.__resolved = false; this._var.__resolved = false;
} }
} else if (typeof result?.then === 'function') { } else if (isPromiseLike(result)) {
result.then(r => { const tmp = result.then(r => {
if (r !== false) { if (r !== false) {
this.close(r); this.close(r);
} else { } else {
this._var.__resolved = false; 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 { } else {
this.close(); this.close();
} }
+14
View File
@@ -22,6 +22,19 @@ function isMobile() {
return /mobile/i.test(navigator.userAgent); return /mobile/i.test(navigator.userAgent);
} }
/**
* @param {unknown} value
* @returns {value is PromiseLike<unknown>}
*/
function isPromiseLike(value) {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
'then' in value &&
typeof value.then === 'function'
);
}
/** /**
* @template {any[]} TArgs * @template {any[]} TArgs
* @template [TContext=typeof globalThis] * @template [TContext=typeof globalThis]
@@ -157,6 +170,7 @@ export {
g as global, g as global,
isPositive, isPositive,
isMobile, isMobile,
isPromiseLike,
// functions // functions
mergeOptions, mergeOptions,
throttle, throttle,