@progress/kendo-react-grid
Version: 
React Data Grid (Table) provides 100+ ready-to-use data grid features. KendoReact Grid package
928 lines (927 loc) • 34.3 kB
JavaScript
/**
 * @license
 *-------------------------------------------------------------------------------------------
 * Copyright © 2025 Progress Software Corporation. All rights reserved.
 * Licensed under commercial license. See LICENSE.md in the package root for more information
 *-------------------------------------------------------------------------------------------
 */
"use client";
import * as a from "react";
import { useAdaptiveModeContext as Ut, canUseDOM as ae, getActiveElement as Vt, useDir as Wt, setScrollbarWidth as Be, cloneArray as jt, getter as de, RowHeightService as _t } from "@progress/kendo-react-common";
import { filterBy as qt } from "@progress/kendo-data-query";
import { getSelectionOptions as ce, populateClipboardData as $t, ClipboardActionType as Se, getEditableOptions as Xt, tableKeyboardNavigation as O, ClipboardService as Jt, TableKeyboardNavigationContext as Yt, editReducer as Qt, EDIT_ACTION as Zt, getDetailExpandableOptions as pt, detailExpandReducer as en, getGroupExpandableOptions as tn, groupExpandReducer as nn, getSelectedState as Ue, getSelectedStateFromKeyDown as rn, closestTagName as Ve, getColumnIndex as on, getRowIndex as an, updateLeft as dn, updateRight as cn } from "@progress/kendo-react-data-tools";
import { ColumnResize as ln } from "./drag/ColumnResize.mjs";
import { CommonDragLogic as sn } from "./drag/CommonDragLogic.mjs";
import { SAFARI_REGEX as un } from "./constants/index.mjs";
import { getDefaultHeadContextMenuItems as gn, getDefaultBodyContextMenuItems as fn, isRowReorderEnabled as mn, sanitizeColumns as Pn, getDataAsArray as hn, getFlatColumnsState as Rn, calcRowHeight as bn } from "./utils/index.mjs";
import { VirtualScroll as vn } from "./VirtualScroll.mjs";
import { GridContextMenu as Cn } from "./contextMenu/GridContextMenu.mjs";
import { GridContextMenuAnchorPart as We } from "./contextMenu/enums.mjs";
import { normalizeSortable as In, firstLevelSortSeqMap as En } from "./sortCommon.mjs";
import { BasePDFExport as wn } from "./BasePDFExport.mjs";
import { GridContext as yn } from "./utils/GridContext.mjs";
import { operators as Sn } from "./filterCommon.mjs";
const xn = (t, v, g, y) => {
  const N = Object.keys(v.cells).map((E) => g.findIndex((H) => H.field === E)), A = Object.keys(v.cells).length > 0 ? N : !0;
  return t.reduce((E, H) => (E[H[y != null ? y : "id"]] = A, E), {});
}, kn = (t, v, g, y) => v.reduce((A, E) => ({
  ...A,
  ...xn(qt(t, E), E, g, y)
}), {}), Wn = (t) => {
  const v = t.gridProps.isClient, [g, y] = a.useState({}), N = Ut(), A = a.useRef(null), E = (e) => {
    e.event.preventDefault(), y({
      ...g,
      show: !0,
      offset: {
        left: e.event.pageX,
        top: e.event.pageY
      },
      dataItem: e.dataItem,
      field: e.field
    });
  }, H = () => {
    y({});
  }, h = a.useMemo(() => t.columnsRef.find((e) => e.field === g.field), [t.columnsRef, g]), xe = a.useMemo(() => {
    const e = t.gridProps.sortable && (h == null ? void 0 : h.sortable);
    return gn({
      pdf: !!t.gridProps.pdf,
      sortable: !!e,
      selectable: ce(t.gridProps.selectable).enabled,
      clipboard: !!t.gridProps.clipboard
    });
  }, [h, t.gridProps.sortable, t.gridProps.selectable, t.gridProps.clipboard]), ke = a.useMemo(() => {
    const e = t.gridProps.sortable && (h == null ? void 0 : h.sortable);
    return fn({
      pdf: !!t.gridProps.pdf,
      sortable: !!e,
      selectable: ce(t.gridProps.selectable).enabled,
      clipboard: !!t.gridProps.clipboard,
      rowReorderable: mn(t.gridProps.rowReorderable)
    });
  }, [h, t.gridProps.sortable, t.gridProps.selectable, t.gridProps.clipboard]), J = a.useMemo(() => {
    const e = (h == null ? void 0 : h.contextMenu) || t.gridProps.contextMenu, n = typeof e == "function" ? e(g) : e;
    if (n && g.offset) {
      const o = g.dataItem ? We.body : We.head, r = n[o], i = g.dataItem ? ke : xe;
      return r === !1 ? void 0 : r === !0 || r === void 0 ? i : r;
    }
  }, [t.gridProps.contextMenu, g, ke, xe, h]), je = (e) => {
    var c, s, u, P, I, ie, b, q, $;
    const n = e.event.item, o = {
      target: C.current,
      syntheticEvent: e.event.syntheticEvent,
      nativeEvent: e.event.nativeEvent,
      menuItem: n,
      ...e
    };
    t.gridProps.onContextMenuItemClick && l(t.gridProps.onContextMenuItemClick, o);
    const r = w(), i = {
      selectedField: "",
      componentId: t.id,
      dataItems: r,
      dataItem: e.dataItem,
      startRowIndex: -1,
      endRowIndex: -1,
      startColIndex: -1,
      endColIndex: -1,
      ctrlKey: !1,
      altKey: !1,
      metaKey: !1,
      shiftKey: !1,
      isDrag: !1,
      ...ce(t.gridProps.selectable),
      ...o
    }, d = r.findIndex((X) => X === e.dataItem);
    switch ((c = n.data) == null ? void 0 : c.action) {
      case "SortCommand":
        if (h) {
          const X = (s = n.name) == null ? void 0 : s.toLowerCase().includes("asc"), Ot = ((u = n.name) == null ? void 0 : u.toLowerCase().includes("desc")) ? "desc" : void 0, Nt = X ? "asc" : Ot, Bt = n.name ? Nt : void 0;
          De(e.event.syntheticEvent, h, Bt);
        }
        break;
      case "SelectRowCommand":
        lt(i);
        break;
      case "SelectAllRowsCommand":
        ct(i);
        break;
      case "ExportPDFCommand":
        le();
        break;
      case "ClearSelectionCommand":
        st(i);
        break;
      case "ReorderRowCommand":
        _.current = e.dataItem, (P = n.name) != null && P.toLowerCase().includes("rowup") && d > 0 && B(e.event.syntheticEvent, d - 1, "before"), (I = n.name) != null && I.toLowerCase().includes("rowdown") && d < r.length - 1 && B(e.event.syntheticEvent, d + 1, "after"), (ie = n.name) != null && ie.toLowerCase().includes("rowtop") && B(e.event.syntheticEvent, 0, "before"), (b = n.name) != null && b.toLowerCase().includes("rowbottom") && B(e.event.syntheticEvent, r.length - 1, "after");
        break;
      case "CopySelectionCommand":
        p(
          Se.copy,
          e.event.nativeEvent,
          {
            copyHeaders: !((q = n.name) != null && q.toLowerCase().includes("noheaders"))
          },
          e.dataItem,
          e.field
        );
        break;
      case "PasteCommand":
        p(
          Se.paste,
          e.event.nativeEvent,
          {
            copyHeaders: !(($ = n.name) != null && $.toLowerCase().includes("noheaders"))
          },
          e.dataItem,
          e.field
        );
        break;
    }
    H();
  }, Y = () => {
    const e = t.columnsRef.filter((n) => n.declarationIndex >= 0 && n.parentIndex === -1);
    return Pn(e);
  }, _e = (e, n, o) => {
    if (t.gridProps.onContextMenu && v) {
      const r = {
        target: C.current,
        syntheticEvent: e,
        nativeEvent: e.nativeEvent,
        dataItem: n,
        field: o
      };
      l(t.gridProps.onContextMenu, r);
    }
    t.gridProps.contextMenu && E({
      event: e,
      dataItem: n,
      field: o
    });
  }, qe = (e) => {
    if (e.target !== e.currentTarget)
      return;
    clearTimeout(Ie.current), m.current && (m.current.table = T.current);
    const n = e.currentTarget.scrollLeft, o = e.currentTarget.scrollTop;
    t.gridProps.columnVirtualization && (!k || o === Ce.current) && (Ie.current = window.setTimeout(() => {
      U();
    }, 0)), t.gridProps.scrollLeftRef && (t.gridProps.scrollLeftRef.current = n), j.current && j.current.setScrollLeft(n), W.current && W.current.setScrollLeft(n), m.current && o !== Ce.current && m.current.scrollHandler(e), t.gridProps.onScroll && v && l(t.gridProps.onScroll, {
      ...f(e)
    }), Ce.current = o;
  }, $e = (e) => {
    O.onKeyDown(e, {
      navigatable: t.gridProps.navigatable || !1,
      contextStateRef: K,
      navigationStateRef: L,
      onNavigationAction: Je,
      columns: Y()
    }), O.onGetSnapshotBeforeUpdate({
      document: S(),
      contextStateRef: K,
      navigationStateRef: L
    });
    const n = {
      dataItems: w(),
      mode: R.mode,
      cell: R.cell,
      componentId: t.id,
      selectedField: "",
      ...f(e)
    };
    t.gridProps.onKeyDown && v && l(t.gridProps.onKeyDown, n);
  }, Xe = (e) => {
    O.onFocus(e, {
      navigatable: !!t.gridProps.navigatable,
      contextStateRef: K
    });
  }, Je = (e) => {
    const { columnsRef: n } = t;
    if (e.action === "moveToNextPage" && mt(e.event), e.action === "moveToPrevPage" && Pt(e.event), e.focusElement && (e.action === "reorderToRight" || e.action === "reorderToLeft")) {
      const o = parseInt(e.focusElement.ariaColIndex, 10) - 1;
      if (!n[o].reorderable)
        return;
      if (e.action === "reorderToRight" && o < t.columnsRef.length - 1) {
        if (n[o + 1].disableReorder)
          return;
        ge(o, o + 1, e.event);
      }
      if (e.action === "reorderToLeft" && o > 0) {
        if (n[o - 1].disableReorder)
          return;
        ge(o, o - 1, e.event);
      }
    }
    if (e.action === "select" && it(e.event), t.gridProps.onNavigationAction && v) {
      const o = {
        focusElement: e.focusElement,
        ...f(e.event)
      };
      l(t.gridProps.onNavigationAction, o);
    }
  }, Ye = (e, n) => {
    t.gridProps.onRowClick && e.target.nodeName === "TD" && l(t.gridProps.onRowClick, {
      dataItem: n,
      ...f(e)
    });
  }, Qe = (e, n) => {
    t.gridProps.onRowDoubleClick && e.target.nodeName === "TD" && l(t.gridProps.onRowDoubleClick, {
      dataItem: n,
      ...f(e)
    });
  }, Ze = (e) => {
    t.gridProps.onItemChange && l(t.gridProps.onItemChange, {
      ...f(e.syntheticEvent),
      dataItem: e.dataItem,
      field: void 0,
      value: void 0
    });
  }, pe = (e) => {
    t.gridProps.onItemChange && t.gridProps.onEditChange && l(t.gridProps.onEditChange, {
      edit: {},
      ...f(e.syntheticEvent)
    });
  }, et = (e, n, o) => {
    if (Ne.enabled && Ne.mode === "incell" && t.gridProps.dataItemKey) {
      const r = Qt(t.gridProps.edit, {
        type: Zt.ENTER_FIELD_EDIT,
        payload: { id: n[t.gridProps.dataItemKey], field: o }
      });
      t.gridProps.onEditChange && l(t.gridProps.onEditChange, {
        edit: r,
        ...f(e)
      });
    }
  }, tt = (e, n) => {
    var r;
    if (pt(t.detailExpandable).enabled) {
      const i = en((r = t.gridProps.detailExpand) != null ? r : {}, e);
      t.gridProps.onDetailExpandChange && l(t.gridProps.onDetailExpandChange, {
        ...f(n),
        detailExpand: i
      });
    }
  }, nt = (e, n) => {
    var r;
    const o = tn(
      typeof t.gridProps.groupable == "object" ? t.gridProps.groupable.expandable !== !1 : t.gridProps.groupable
    );
    if (o.enabled) {
      const i = nn((r = t.gridProps.groupExpand) != null ? r : [], e, o);
      t.gridProps.onGroupExpandChange && l(t.gridProps.onGroupExpandChange, {
        ...f(n),
        groupExpand: i
      });
    }
  }, De = (e, n, o) => {
    const { allowUnsort: r, mode: i } = In(
      t.gridProps.sortable || !1,
      n.sortable || !1
    ), d = (t.gridProps.sort || []).filter((u) => u.field === n.field)[0], c = o || En[r][d && d.dir || ""], s = i === "single" ? [] : (t.gridProps.sort || []).filter((u) => u.field !== n.field);
    c !== "" && n.field && s.push({ field: n.field, dir: c }), Ke(s, e);
  }, rt = (e) => {
    t.gridProps.onItemChange && l(t.gridProps.onItemChange, {
      ...f(e.syntheticEvent),
      dataItem: e.dataItem,
      dataIndex: e.dataIndex,
      field: e.field,
      value: e.value
    });
  }, ot = (e) => {
    var n;
    if (t.gridProps.onSelectionChange && R.enabled) {
      const { event: o, dataItem: r, dataIndex: i, columnIndex: d } = e, c = {
        ...f(o),
        dataItem: r,
        startColIndex: d,
        endColIndex: d,
        startRowIndex: i,
        endRowIndex: i,
        dataItems: w(),
        altKey: !1,
        ctrlKey: !1,
        shiftKey: !1,
        metaKey: !1,
        mode: R.mode,
        cell: R.cell,
        isDrag: !1,
        componentId: t.id,
        selectedField: ""
      };
      l(t.gridProps.onSelectionChange, {
        ...c,
        select: t.gridProps.dataItemKey ? Ue({
          event: c,
          selectedState: (n = t.gridProps.select) != null ? n : {},
          dataItemKey: t.gridProps.dataItemKey
        }) : {}
      });
    }
  }, it = (e) => {
    var u, P;
    if (!R.enabled || !t.gridProps.dataItemKey)
      return;
    const n = {
      dataItems: w(),
      mode: R.mode,
      cell: R.cell,
      componentId: t.id,
      selectedField: "",
      ...f(e)
    }, o = rn({
      event: n,
      selectedState: (u = t.gridProps.select) != null ? u : {},
      dataItemKey: t.gridProps.dataItemKey
    });
    if (o === t.gridProps.select)
      return;
    const r = e.target, i = Ve(r, "TD"), d = Ve(r, "TR"), c = on(i), s = an(d);
    if (c !== void 0 && s !== void 0) {
      const I = (P = hn(t.gridProps.data)) == null ? void 0 : P[s];
      t.gridProps.onSelectionChange && l(t.gridProps.onSelectionChange, {
        ...n,
        select: o,
        dataItem: I,
        startRowIndex: s,
        startColIndex: c,
        startDataItem: I,
        endDataItem: I,
        endRowIndex: s,
        endColIndex: c,
        ctrlKey: e.ctrlKey,
        altKey: e.altKey,
        metaKey: e.metaKey,
        shiftKey: e.shiftKey,
        isDrag: !1
      });
    }
  }, at = (e) => {
    if (t.gridProps.onHeaderSelectionChange && R.enabled) {
      const n = w();
      l(t.gridProps.onHeaderSelectionChange, {
        select: e.syntheticEvent.target.checked ? n.reduce((o, r) => (t.gridProps.dataItemKey && de(t.gridProps.dataItemKey)(r) !== void 0 && (o[de(t.gridProps.dataItemKey)(r)] = !0), o), {}) : {},
        field: e.field,
        nativeEvent: e.syntheticEvent && e.syntheticEvent.nativeEvent,
        syntheticEvent: e.syntheticEvent,
        target: C.current,
        dataItems: n
      });
    }
  }, Q = (e, n) => {
    t.gridProps.onSelectionChange && R.enabled && l(t.gridProps.onSelectionChange, {
      ...e,
      select: n
    });
  }, dt = (e) => {
    var n;
    if (t.gridProps.onSelectionChange && R.enabled) {
      const o = w()[e.startRowIndex], r = w()[e.endRowIndex], i = {
        syntheticEvent: void 0,
        target: C.current,
        selectedField: "",
        componentId: t.id,
        dataItems: w(),
        dataItem: null,
        startDataItem: o,
        endDataItem: r,
        ...e
      }, d = Ue({
        event: i,
        selectedState: (n = t.gridProps.select) != null ? n : {},
        // Thats kinda strange, even through the `dataItemKey` is required by the `getSelectedState`
        // it does work correctly even without it
        dataItemKey: t.gridProps.dataItemKey
      });
      Q(i, d);
    }
  }, ct = (e) => {
    if (t.gridProps.onSelectionChange && R.enabled) {
      const n = e.dataItems[0], o = e.dataItems[e.dataItems.length - 1], r = {}, i = {
        ...e,
        startDataItem: n,
        endDataItem: o,
        startRowIndex: 0,
        endRowIndex: e.dataItems.length - 1,
        startColIndex: 0,
        endColIndex: t.columnsRef.length - 1
      };
      e.dataItems.forEach((d) => {
        const s = de(t.gridProps.dataItemKey)(d);
        r[s] = e.cell ? [...Array(t.columnsRef.length).keys()] : !0;
      }), Q(i, r);
    }
  }, lt = (e) => {
    if (t.gridProps.onSelectionChange && R.enabled) {
      const o = de(t.gridProps.dataItemKey)(e.dataItem), r = 0, i = t.columnsRef.length - 1, d = e.dataItems.findIndex(
        (I) => I[t.gridProps.dataItemKey] === e.dataItem[t.gridProps.dataItemKey]
      ), u = {
        ...e,
        startDataItem: d,
        endDataItem: d,
        startRowIndex: d,
        endRowIndex: d,
        startColIndex: r,
        endColIndex: i
      }, P = e.mode === "multiple" ? t.gridProps.select || {} : {};
      P[o] === !0 || Array.isArray(P[o]) && P[o].length === t.columnsRef.length ? delete P[o] : P[o] = e.cell ? [...Array(t.columnsRef.length).keys()] : !0, Q(u, P);
    }
  }, st = (e) => {
    t.gridProps.onSelectionChange && R.enabled && Q(e, {});
  }, G = (e, n, o, r, i) => {
    ft();
    const d = t.gridProps.onDataStateChange;
    if (e) {
      const c = { ...f(r), ...n, targetEvent: i };
      l(e, c);
    } else d && l(d, {
      ...f(r),
      targetEvent: i || {},
      dataState: {
        ...xt(),
        ...o
      }
    });
  }, Z = (e, n, o) => {
    var r;
    k && t.gridProps.pageable && ((r = m.current) == null || r.reset()), G(
      t.gridProps.onPageChange,
      { page: e },
      { skip: e.skip, take: e.take },
      n,
      o
    );
  }, ut = (e, n, o) => {
    var r;
    t.gridProps.pageable || (r = t.gridProps.group) != null && r.length ? t.gridProps.virtualSkipRef && (t.gridProps.virtualSkipRef.current = e.skip, U()) : Z(e, n, o);
  }, gt = () => {
    let e = t.gridProps.total || 0;
    return Array.isArray(t.gridProps.data) ? e = e || t.gridProps.data.length : t.gridProps.data && (e = e || t.gridProps.data.total), e;
  }, ft = () => {
    k && t.gridProps.virtualSkipRef && (t.gridProps.virtualSkipRef.current = 0);
  }, mt = (e) => {
    var i, d;
    const n = (d = (i = t.gridProps.take) != null ? i : t.gridProps.pageSize) != null ? d : 0, o = (t.gridProps.skip || 0) + n, r = gt();
    o < r && Z({ skip: o, take: n }, e);
  }, Pt = (e) => {
    var r, i;
    const n = (i = (r = t.gridProps.take) != null ? r : t.gridProps.pageSize) != null ? i : 0, o = (t.gridProps.skip || 0) - n;
    o >= 0 && Z({ skip: o, take: n }, e);
  }, ht = (e) => {
    Z({ skip: e.skip, take: e.take }, e.syntheticEvent, e.targetEvent);
  }, Ke = (e, n) => {
    G(
      t.gridProps.onSortChange,
      { sort: e },
      { sort: e, ...k && !t.gridProps.pageable ? { skip: 0 } : {} },
      n
    );
  }, Rt = (e, n) => {
    G(
      t.gridProps.onFilterChange,
      { filter: e },
      { filter: e, skip: 0 },
      n
    );
  }, bt = (e) => {
    if (!e || e.length === 0) {
      Te({});
      return;
    }
    const n = kn(
      t.gridProps.data,
      e,
      t.columnsRef,
      t.gridProps.dataItemKey
    );
    Te({ ...n });
  }, Te = (e) => {
    G(t.gridProps.onHighlightChange, { highlight: e }, {}, {});
  }, vt = (e) => {
    const n = t.gridProps.searchFields || t.columnsRef.map((i) => i.field) || [], o = e.nativeEvent.target.value, r = {
      logic: "or",
      filters: n.filter((i) => i !== void 0).map((i) => {
        var d;
        return typeof i == "string" ? { field: i, value: o, operator: "contains" } : {
          value: o,
          operator: (d = i.operator) != null ? d : "contains",
          field: i.field,
          ignoreCase: i.ignoreCase
        };
      })
    };
    G(
      t.gridProps.onSearchChange,
      {
        search: r
      },
      { skip: 0 },
      e.syntheticEvent
    );
  }, le = () => {
    var e;
    (e = A.current) == null || e.save();
  }, Ct = async (e) => {
    var n, o;
    (n = t.gridProps) != null && n.onPdfExport && await ((o = t.gridProps) == null ? void 0 : o.onPdfExport(e));
  }, se = (e, n) => {
    const o = n.nativeEvent ? n : { nativeEvent: n.nativeEvent || n.originalEvent };
    let r = {};
    t.isVirtualScroll && e.length && !t.gridProps.pageable && (r = { take: void 0 }), e.length === 0 && t.gridProps.navigatable && (Re.current = !0), G(
      t.gridProps.onGroupChange,
      { group: e },
      { group: e, skip: 0, ...r },
      o
    );
  }, ue = (e) => {
    if (t.gridProps.onColumnsStateChange) {
      const n = {
        target: C.current,
        columnsState: e
      };
      l(t.gridProps.onColumnsStateChange, n);
    }
  }, ge = (e, n, o) => {
    const { columnsRef: r, columnsState: i } = t, d = r[e], c = Rn(i), s = d.depth, u = (b) => {
      do
        b++;
      while (b < r.length && r[b].depth > s);
      return b;
    }, P = r.splice(e, u(e) - e);
    r.splice(e < n ? u(n - P.length) : n, 0, ...P), r.filter((b) => b.declarationIndex >= 0).forEach((b, q) => {
      b.orderIndex = q;
      const $ = c.find((X) => X.id === b.id);
      $ && ($.orderIndex = q);
    });
    const I = r[e].locked && r[n].locked;
    dn(t.columnsMapRef, r, I || re.current), cn(t.columnsMapRef, r, I || re.current), he.current && (re.current = !1, he.current = !1);
    const ie = Y();
    if (U(), t.gridProps.onColumnReorder) {
      const b = {
        target: C.current,
        columns: ie,
        columnId: d.id,
        nativeEvent: o
      };
      l(t.gridProps.onColumnReorder, b);
    }
    ue(i);
  }, B = (e, n, o) => {
    const r = typeof t.gridProps.rowReorderable == "object" ? t.gridProps.rowReorderable.enabled : t.gridProps.rowReorderable;
    if (o === "forbidden" || !r || !_.current)
      return;
    const i = t.dataRef[n];
    t.gridProps.onRowReorder && l(t.gridProps.onRowReorder, {
      draggedDataItems: [_.current],
      droppedDataItem: i == null ? void 0 : i.dataItem,
      dropPosition: o,
      nativeEvent: e.originalEvent,
      dragEvent: e,
      target: C.current
    }), _.current = null;
  }, It = (e, n, o) => {
    if (t.gridProps.group === void 0)
      return;
    const r = t.gridProps.group.slice();
    r.splice(n, 0, ...r.splice(e, 1)), se(r, o);
  }, Me = (e, n, o) => {
    const r = t.columnsRef[e].field;
    if (!r)
      return;
    const i = (t.gridProps.group || []).slice();
    i.splice(n, 0, { field: r }), se(i, o);
  }, Et = (e, n) => {
    const o = D.current.getCurrentGroupsLength;
    Me(e, o, n);
  }, fe = () => {
    let e = 0;
    if (!x.current.colGroupMain)
      return;
    const n = x.current.colGroupMain.children;
    for (let o = 0; o < n.length; o++) {
      const r = n[o].width;
      if (!r) {
        e = 0;
        break;
      }
      e += parseFloat(r.toString());
    }
    e = Math.round(e), j.current && j.current.setWidth(e), W.current && W.current.setWidth(e), T.current && (T.current.style.width = e ? e + "px" : "");
  }, Ae = () => {
    var e;
    t.gridProps.widthRef && (t.gridProps.widthRef.current = ((e = M.current) == null ? void 0 : e.offsetWidth) || 0);
  }, He = () => {
    var e;
    t.gridProps.containerHeightRef && (t.gridProps.containerHeightRef.current = ((e = V.current) == null ? void 0 : e.offsetHeight) || 0);
  }, wt = () => {
    const e = t.gridProps.minRowHeightRef;
    if (e && !e.current && !t.gridProps.rowHeight) {
      const n = bn(z.current);
      n && (e.current = n, U());
    }
  }, p = a.useCallback(
    (e, n, o, r, i) => {
      var u;
      if (!yt() && !o || !e)
        return;
      const d = {
        type: e,
        nativeEvent: n,
        columns: t.columnsRef,
        dataItemKey: t.gridProps.dataItemKey || "",
        dataItem: r,
        field: i,
        ...typeof t.gridProps.clipboard != "boolean" ? t.gridProps.clipboard : {},
        ...o
      }, c = w(), s = $t({
        event: d,
        data: c,
        selectedState: (u = t.gridProps.select) != null ? u : {},
        previousCopiedItems: ze.current
      });
      e !== Se.paste && (ze.current = s.copiedItems), t.gridProps.onClipboard && v && l(t.gridProps.onClipboard, {
        ...d,
        ...s
      });
    },
    [
      t.gridProps.select,
      t.gridProps.dataItemKey,
      t.gridProps.data,
      t.gridProps.clipboard,
      t.gridProps.onClipboard
    ]
  ), yt = () => {
    var i, d, c;
    if (!ae)
      return !1;
    const e = Vt(S()), n = e ? e.matches(".k-table-td") ? e : (i = S()) == null ? void 0 : i.body : (d = S()) == null ? void 0 : d.body, o = n.closest(".k-grid-container"), r = n && ((c = M.current) == null ? void 0 : c.contains(n));
    return !!(n && r && o);
  }, St = (e, n, o, r, i, d, c) => {
    fe(), re.current = !0, he.current = !0, t.gridProps.onColumnResize && v && l(t.gridProps.onColumnResize, {
      columns: Y(),
      nativeEvent: r,
      targetColumnId: c,
      index: e,
      newWidth: n,
      oldWidth: o,
      end: i,
      target: C.current
    }), i && ue(d);
  }, xt = () => {
    var e;
    return {
      filter: t.gridProps.filter,
      sort: t.gridProps.sort,
      skip: t.gridProps.skip,
      take: (e = t.gridProps.take) != null ? e : t.gridProps.pageSize,
      group: t.gridProps.group
    };
  }, f = (e) => ({
    nativeEvent: e && e.nativeEvent,
    syntheticEvent: e,
    target: C.current
  }), kt = (e) => ({
    ...e,
    nativeEvent: void 0,
    syntheticEvent: void 0,
    target: void 0,
    targetEvent: void 0,
    focusElement: void 0
  }), l = (e, n) => {
    if (t.gridProps.isClient) {
      e(n);
      return;
    }
    e(kt(n));
  }, Dt = () => {
    var e, n, o;
    if (z.current && ((e = z.current) == null ? void 0 : e.getElementsByClassName("k-grid-edit-row").length) > 0) {
      ve.current = !1, (n = document.activeElement) != null && n.closest(".k-grid-edit-row") ? be.current = document.activeElement : be.current = void 0;
      const r = Array.from((o = z.current) == null ? void 0 : o.getElementsByClassName("k-grid-edit-row"));
      r.length > we.current.length ? ne.current = r.filter(
        (i) => !we.current.includes(i)
      )[0] : r.length === 1 && (ne.current = r[0], ve.current = !0), we.current = r;
    }
  }, w = () => t.dataRef.filter((e) => e.rowType === "data").map((e) => e.dataItem), S = () => {
    var e;
    if (ae)
      return ((e = ee()) == null ? void 0 : e.ownerDocument) || document;
  }, ee = () => M.current, me = a.useCallback(
    (e) => {
      var r, i;
      if (!m.current || !((r = m.current) != null && r.container) || t.gridProps.scrollable === "none")
        return;
      F.current && F.current.disconnect();
      const { rowIndex: n } = e, o = ee();
      if (k) {
        const d = ((i = m.current.rowHeightService) == null ? void 0 : i.offset(n)) || 0;
        m.current.container.scroll(0, d);
      } else if (o) {
        const d = n < 1 ? o.querySelector("tbody > tr:nth-child(1)") : o.querySelector(`tbody > tr:nth-child(${n + 1})`);
        d && V.current && (V.current.scrollTop = d.offsetTop);
      }
    },
    [t.gridProps.scrollable]
  ), Ge = (e) => JSON.stringify(e.map((n) => ({ id: n.id, field: n.field, title: n.title, children: n.children }))), Kt = () => Ge(Ft) === Ge(t.columnsRef), Tt = () => {
    oe.current = window.innerWidth, Kt() || U();
  }, Mt = () => {
    var d;
    const { virtualTotal: e, virtualPageSize: n, gridProps: o } = t, r = m.current, i = t.gridProps.rowHeight || ((d = o.minRowHeightRef) == null ? void 0 : d.current) || 0;
    r && (r.fixedScroll = o.fixedScroll || !1, r.PageChange = ut, r.pageSize = n, r.scrollableVirtual = k, r.container = V.current, r.tableBody = z.current, r.scrollHeightContainer = Fe.current, r.table = T.current, (!r.rowHeightService || r.total !== e) && i && (r.total = e, r.rowHeightService = new _t(e, i)));
  }, Le = a.useCallback(
    (e) => {
      const n = { rowIndex: Ee.current };
      e.forEach((o) => {
        o.boundingClientRect.height !== o.intersectionRect.height && me(n);
      });
    },
    [me]
  ), U = () => {
    t.gridProps.forceUpdate && t.gridProps.forceUpdate();
  }, At = (e) => e.left !== void 0 ? ye !== "rtl" ? { left: e.left, right: e.right } : { left: e.right, right: e.left } : {}, C = a.useRef(null), m = a.useRef(void 0), x = a.useRef(void 0), D = a.useRef(void 0), K = a.useRef(void 0), L = a.useRef(void 0), te = a.useRef(void 0), F = a.useRef(null), z = a.useRef(null), Ht = a.useRef(null), V = a.useRef(null), T = a.useRef(null), Pe = a.useRef(null), M = a.useRef(null), Fe = a.useRef(null), W = a.useRef(null), j = a.useRef(null), he = a.useRef(!1), Re = a.useRef(!1), ne = a.useRef(void 0), be = a.useRef(void 0), ve = a.useRef(!1), re = a.useRef(!0), Ce = a.useRef(0), Ie = a.useRef(void 0), Ee = a.useRef(void 0), we = a.useRef([]), ze = a.useRef([]), oe = a.useRef(0), _ = a.useRef(null), Gt = a.useRef(null), Lt = a.useRef(null), ye = Wt(M), k = t.isVirtualScroll, Ft = a.useMemo(() => a.Children.toArray(t.gridProps.children), [t.gridProps.children]), Oe = t.gridProps.groupable === !0 || typeof t.gridProps.groupable == "object" && t.gridProps.groupable.enabled !== !1, R = ce(t.gridProps.selectable), Ne = Xt(t.gridProps.editable), zt = oe.current && N && oe.current <= N.medium && t.gridProps.adaptive;
  return a.useMemo(() => {
    O.onConstructor({
      navigatable: !!t.gridProps.navigatable,
      contextStateRef: K,
      navigationStateRef: L,
      idPrefix: t.id
    }), m.current = new vn();
  }, []), a.useMemo(() => {
    var e;
    (e = m.current) == null || e.reset();
  }, [
    t.gridProps.scrollable,
    t.gridProps.total,
    t.gridProps.filter,
    t.gridProps.group,
    Oe,
    t.gridProps.sort,
    t.gridProps.rowHeight
  ]), a.useEffect(() => (t.gridProps.clipboard && (te.current = new Jt(p), te.current.addEventListeners(S())), () => {
    te.current && te.current.removeEventListeners(S());
  }), [t.gridProps.onClipboard, t.gridProps.clipboard, p, S]), a.useEffect(() => (t.gridProps.columnVirtualization && !window.navigator.userAgent.match(un) && (Pe.current && (Pe.current.style.display = "block"), T.current && (T.current.style.display = "block")), Ae(), fe(), Be(), O.onComponentDidMount({
    scope: M.current || void 0,
    contextStateRef: K,
    navigationStateRef: L
  }), () => {
    clearTimeout(Ie.current);
  }), []), a.useEffect(() => {
    var e;
    Ae(), fe(), Be(), k && (He(), wt(), (e = m.current) == null || e.update()), Dt(), O.onComponentDidUpdate({
      scope: M.current || void 0,
      contextStateRef: K,
      navigationStateRef: L,
      focusFirst: Re.current,
      newEditableRow: ne.current,
      singleEditRow: ve.current,
      lastActiveElement: be.current,
      navigatable: t.gridProps.navigatable
    }), Re.current = !1, ne.current = void 0;
  }), a.useEffect(() => {
    if (ae) {
      const e = {
        rootMargin: "0px",
        threshold: 0.9
      };
      F.current = window.IntersectionObserver && new window.IntersectionObserver(Le, e) || null;
    }
  }, [Le]), a.useEffect(() => {
    var n;
    let e;
    return ae && window.ResizeObserver && (e = new window.ResizeObserver(() => {
      Tt(), k && He();
    }), e.observe((n = S()) == null ? void 0 : n.body)), () => {
      e == null || e.disconnect();
    };
  }, []), a.useImperativeHandle(
    C,
    () => ({
      get element() {
        return ee();
      },
      props: t.gridProps,
      get columns() {
        return Y();
      },
      scrollIntoView: (e) => {
        var r;
        if (!((r = m.current) != null && r.container) || t.gridProps.scrollable === "none")
          return;
        const { rowIndex: n } = e;
        Ee.current = n;
        const o = ee();
        if (F.current && o) {
          F.current.disconnect();
          const i = o.querySelector(`[absolute-row-index="${Ee.current}"]`);
          i ? F.current.observe(i) : me(e);
        }
      },
      fitColumns: (e) => {
        x.current.dblClickHandler(null, e);
      },
      exportAsPdf: le
    })
  ), a.useImperativeHandle(t.gridRef, () => C.current), a.useMemo(() => {
    x.current = new ln(St);
  }, [t.gridProps.onColumnResize, t.columnsRef]), a.useMemo(() => {
    D.current = new sn(ge, It, Me);
  }, [
    t.gridProps.onColumnReorder,
    t.gridProps.onGroupChange,
    t.gridProps.group,
    t.columnsRef,
    t.gridProps.groupable
  ]), x.current.resizable = t.gridProps.resizable || !1, x.current.columns = t.columnsRef, x.current.columnsState = jt(t.columnsState), D.current.reorderable = t.gridProps.reorderable || !1, D.current.groupable = Oe, D.current.columns = t.columnsRef, D.current.dir = ye, Mt(), /* @__PURE__ */ a.createElement(
    yn.Provider,
    {
      value: {
        isClient: v,
        rowReorder: B,
        activeDragRowDataItemRef: _,
        reorderRowDragTargetRef: Gt,
        reorderRowDropTargetRef: Lt,
        dir: ye,
        getCellPositionStyle: At,
        dataItemKey: t.gridProps.dataItemKey,
        columnsState: t.columnsState,
        columnsRef: t.columnsRef,
        onColumnsStateChange: ue,
        groupable: t.gridProps.groupable,
        group: t.gridProps.group,
        defaultGroup: t.gridProps.defaultGroup,
        groupChange: se,
        selectionRelease: dt,
        pagerPageChange: ht,
        onContextMenu: _e,
        rowClick: Ye,
        rowDblClick: Qe,
        cellClick: et,
        headerCellClick: De,
        itemChange: rt,
        onDialogEditCancel: pe,
        onDialogEditSubmit: Ze,
        sortable: t.gridProps.sortable,
        sort: t.gridProps.sort,
        defaultSort: t.gridProps.defaultSort,
        sortChange: Ke,
        filterable: t.gridProps.filterable,
        filter: t.gridProps.filter,
        defaultFilter: t.gridProps.defaultFilter,
        filterOperators: t.gridProps.filterOperators || Sn,
        filterChange: Rt,
        applyHighlightDescriptor: bt,
        highlight: t.gridProps.highlight,
        searchChange: vt,
        exportAsPdf: le,
        onHeaderSelectionChange: at,
        columnGroupChange: Et,
        onKeyDown: $e,
        onFocus: Xe,
        scrollHandler: qe,
        selectionChange: ot,
        mobileMode: zt,
        adaptiveColumnMenuRef: oe.current,
        adpativeTitle: t.gridProps.adaptiveTitle,
        adaptive: t.gridProps.adaptive,
        dispatchDetailExpand: tt,
        dispatchGroupExpand: nt,
        columnResizeRef: x,
        dragLogicRef: D,
        navigationStateRef: L,
        tableElementRef: T,
        tableBodyElementRef: z,
        headerElementRef: Ht,
        containerElementRef: V,
        headTableElementRef: Pe,
        elementRef: M,
        virtualScrollHeightContainerRef: Fe,
        footerRef: W,
        headerRef: j,
        vsRef: m
      }
    },
    /* @__PURE__ */ a.createElement(Yt.Provider, { value: K.current }, t.children),
    /* @__PURE__ */ a.createElement(
      Cn,
      {
        show: g.show && (J == null ? void 0 : J.length),
        dataItem: g.dataItem,
        field: g.field,
        items: J,
        offset: g.offset,
        onClose: H,
        onSelect: je
      }
    ),
    t.gridProps.pdf && /* @__PURE__ */ a.createElement(
      wn,
      {
        gridProps: t.gridProps,
        innerGrid: t.innerGrid,
        pdf: typeof t.gridProps.pdf == "object" ? t.gridProps.pdf : {},
        onPdfExport: Ct,
        ref: (e) => A.current = e
      }
    )
  );
};
export {
  Wn as GridClientWrapper
};