20260724173425

This commit is contained in:
oneao committed 2026-07-24 17:34:26 +08:00
1 parent 4f40ad9f11
commit b33c743236
27 files changed
+1310 -437

No files matched your search

@@ -1,5 +1,5 @@
<script setup>
import { computed, nextTick, ref, useSlots } from "vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useSlots } from "vue";
import { useRafFn, useResizeObserver } from "@vueuse/core";
import { StkTable } from "stk-table-vue";
import { createActionsCellRenderer } from "./utils/createActionsCellRenderer";
@@ -30,15 +30,150 @@ function getRowKey(row) {
const selectedRowKeySet = computed(() => new Set(props.rowSelection?.selectedRowKeys || []));
// 追踪用户点击的单元格列,用于编辑态自动聚焦到对应列
// 追踪当前编辑列,用于 EditableCell 决定哪个单元格自动聚焦
const activeColKey = ref(null);
function onStkRowClick(ev, row, data) {
const td = ev.target.closest?.("td");
activeColKey.value = td?.dataset?.colKey || null;
// 更新键盘导航的起始位置
const rowIndex = props.dataSource.findIndex(
(r) => String(getRowKey(r)) === String(getRowKey(row)),
);
const colIndex = props.columns.findIndex((c) => c.dataIndex === activeColKey.value);
if (rowIndex >= 0 && colIndex >= 0) {
currentPos.value = { rowIndex, colIndex };
}
emit("row-click", ev, row, data);
}
// ==================== 自定义键盘导航 ====================
// StkTable 的 areaSelection keyboard 模式在按键重复(~30Hz)时内部做选区矩形计算、
// overlay DOM 操作和虚拟滚动重算——这些不经过我们的 RAF,是 FPS ~12 的根源。
// 这里关闭 areaSelection 内置键盘处理,自己接管方向键,只做行/列定位 + RAF 批量化更新。
const currentPos = ref({ rowIndex: -1, colIndex: -1 });
let navRafPending = false;
let navPendingState = null;
/** RAF 批量化提交一次导航(activeColKey + row-click emit),每帧至多一次。 */
function flushNav() {
navRafPending = false;
const p = navPendingState;
navPendingState = null;
if (!p) return;
if (activeColKey.value !== p.colKey) {
activeColKey.value = p.colKey;
}
const rowKey = String(getRowKey(p.row));
if (String(props.activeRowKey ?? "") !== rowKey) {
emit("row-click", null, p.row, p.rows);
}
}
function navigateTo(rowIndex, colIndex) {
const rows = props.dataSource;
const cols = props.columns;
if (rowIndex < 0 || rowIndex >= rows.length || colIndex < 0 || colIndex >= cols.length) return;
const row = rows[rowIndex];
const colKey = cols[colIndex].dataIndex;
currentPos.value = { rowIndex, colIndex };
navPendingState = { row, colKey, rows };
if (!navRafPending) {
navRafPending = true;
requestAnimationFrame(flushNav);
}
// 虚拟滚动跟随:目标行超出可视区时滚动
const table = tableRef.value;
if (!table) return;
const el = table.$el;
const scrollTop = el?.scrollTop ?? 0;
const containerHeight = el?.clientHeight ?? 600;
const visibleTop = scrollTop + headerRowHeight;
const visibleBottom = scrollTop + containerHeight;
const targetTop = rowIndex * rowHeight;
if (targetTop < visibleTop) {
table.scrollTo(Math.max(0, targetTop - headerRowHeight), null);
} else if (targetTop + rowHeight > visibleBottom) {
table.scrollTo(targetTop + rowHeight - containerHeight + headerRowHeight, null);
}
}
function onTableKeydown(event) {
const { key, shiftKey, ctrlKey } = event;
if (ctrlKey || ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Tab"].indexOf(key) < 0)
return;
if (key === "Tab" && shiftKey) return;
// 输入框/文本框内按键留给浏览器处理光标移动,不拦截为表格导航
const tag = event.target?.tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || event.target?.isContentEditable)
return;
const rows = props.dataSource;
const cols = props.columns;
if (rows.length === 0 || cols.length === 0) return;
let { rowIndex, colIndex } = currentPos.value;
// 首次按键或位置无效时,从 activeRowKey 推导起始位置
if (rowIndex < 0 || colIndex < 0 || rowIndex >= rows.length) {
const activeRowKeyStr = String(props.activeRowKey ?? "");
rowIndex = rows.findIndex((r) => String(getRowKey(r)) === activeRowKeyStr);
colIndex = 0;
if (rowIndex < 0) rowIndex = 0;
currentPos.value = { rowIndex, colIndex };
}
switch (key) {
case "ArrowUp":
if (rowIndex > 0) rowIndex--;
break;
case "ArrowDown":
if (rowIndex < rows.length - 1) rowIndex++;
break;
case "ArrowLeft":
if (colIndex > 0) colIndex--;
break;
case "ArrowRight":
case "Tab":
if (colIndex < cols.length - 1) colIndex++;
else if (rowIndex < rows.length - 1) {
rowIndex++;
colIndex = 0;
}
break;
default:
return;
}
event.preventDefault();
event.stopPropagation();
navigateTo(rowIndex, colIndex);
}
function attachKeyboard() {
nextTick(() => {
const el = tableRef.value?.$el;
if (el) el.addEventListener("keydown", onTableKeydown, true);
});
}
function detachKeyboard() {
const el = tableRef.value?.$el;
if (el) el.removeEventListener("keydown", onTableKeydown, true);
}
onMounted(attachKeyboard);
onBeforeUnmount(detachKeyboard);
// ==================== 自定义键盘导航 END ====================
const EditableCell = createEditableCellRenderer({
getRowKey,
getActiveRowKey: () => props.activeRowKey,
@@ -52,14 +187,43 @@ const { SelectionCell, SelectionHeaderCell } = createSelectionCellRenderers({
onChange: (keys, rows) => props.rowSelection?.onChange?.(keys, rows),
});
// areaSelection 仅保留 enabled 做占位(避免 StkTable prop 类型警告),
// keyboard 已关闭:键盘导航改为本组件自实现的 onTableKeydown 接管,
// 绕过 StkTable 内部每帧 30+ 次的选区计算 + overlay DOM 操作。
const areaSelectionConfig = ref({
enabled: true,
keyboard: false,
highlight: {
cell: false,
row: false,
},
});
// 列宽拖拽结果缓存:StkTable 拖拽列宽依赖 v-model:columns 回写;
// 父组件多为单向 :columns 绑定,这里在封装层内部保留拖拽后的宽度,避免重渲染时被重置。
const resizedWidths = ref({});
function getColumnKey(column) {
return column.dataIndex ?? column.key;
}
// StkTable 的编辑单元格、操作列和多选列统一在封装层生成,业务页面只声明 editor / actions / rowSelection。
const tableColumnsModel = computed({
get: () => {
// 依赖 activeRowKey:切换编辑行时触发 columns 重算,迫使 StkTable 重渲染单元格
void props.activeRowKey;
const columns = props.columns.map((column) => {
// 不依赖 activeRowKey:EditableCell 作为函数式组件,内部已通过 getActiveRowKey()/
// getActiveColKey() 读取响应式 props.activeRowKey 与 activeColKey,切换编辑行时
// 只有可见的编辑单元格会自动重渲染。若在此处依赖 activeRowKey,每次切换都会生成
// 全新列对象数组,触发 StkTable 的 watch(columns) → handleDealColumns 全表重渲染,
// 这是编辑/新增时卡顿的根源(对比 TableDemo:customCell 直接读 ref 即可精确更新)。
const columns = props.columns.map((rawColumn) => {
const width = resizedWidths.value[getColumnKey(rawColumn)];
const column = width != null ? { ...rawColumn, width } : rawColumn;
if (column.actions && !column.customCell) {
return { ...column, customCell: createActionsCellRenderer(column.actions), __fmsAction: true };
return {
...column,
customCell: createActionsCellRenderer(column.actions),
__fmsAction: true,
};
}
if (column.editor && !column.customCell) {
return { ...column, customCell: EditableCell, __fmsEditor: true };
@@ -83,7 +247,13 @@ const tableColumnsModel = computed({
...columns,
];
},
set: (value) =>
set: (value) => {
// 缓存拖拽后的列宽,供 get 重新应用(即使父组件只用单向 :columns 绑定)
for (const column of value) {
if (column.width != null) {
resizedWidths.value[getColumnKey(column)] = column.width;
}
}
emit(
"update:columns",
value
@@ -96,16 +266,22 @@ const tableColumnsModel = computed({
delete rest.__fmsAction;
return rest;
}),
),
);
},
});
const slots = useSlots();
const tableRef = ref(null);
// 表格样式
// 表格行高:既作为 CSS 变量控制实际 DOM 行高,又作为 StkTable 的 row-height /
// header-row-height prop 传入,确保虚拟滚动按实际 DOM 行高计算总高度、pageSize、
// offsetTop/offsetBottom。否则 StkTable 默认 rowHeight=28 与 CSS 变量 34 不一致,
// 会导致滚动到底部时计算高度与实际内容高度不匹配而回弹。
const rowHeight = 34;
const headerRowHeight = 40;
const customVars = ref({
"--header-row-height": "40px",
"--row-height": "34px",
"--header-row-height": `${headerRowHeight}px`,
"--row-height": `${rowHeight}px`,
"--footer-row-height": "36px",
});
@@ -136,14 +312,18 @@ const forwardSlots = computed(() => {
return result;
});
// areaSelection 只做外观占位,键盘导航由自实现接管以避免 StkTable 内部选区计算开销。
// 鼠标点击后 keyboard 会通过 onTableKeydown 从 activeRowKey 推导起始位置继续导航。
// 滚动到指定行;用于新增后自动聚焦
async function scrollToRow(rowKey) {
await nextTick();
const el = tableRef.value?.$el;
if (!el) return;
const key = String(rowKey);
const rowEl = el.querySelector(`[data-row-key="${key}"]`);
rowEl?.scrollIntoView?.({ block: "nearest", behavior: "smooth" });
const table = tableRef.value;
if (!table) return;
const rows = props.dataSource;
const idx = rows.findIndex((row) => String(getRowKey(row)) === String(rowKey));
if (idx < 0) return;
table.scrollTo(idx * rowHeight, null);
}
defineExpose({ scrollToRow });
@@ -156,6 +336,8 @@ defineExpose({ scrollToRow });
v-bind="$attrs"
:style="customVars"
:auto-resize="false"
:row-height="rowHeight"
:header-row-height="headerRowHeight"
:virtual="virtual"
:virtual-x="virtualX"
:col-resizable="colResizable"
@@ -164,6 +346,7 @@ defineExpose({ scrollToRow });
:row-key="rowKey"
:bordered="bordered"
:no-data-full="noDataFull"
:area-selection="areaSelectionConfig"
@row-click="onStkRowClick"
>
<template v-for="(slot, name) in forwardSlots" :key="name" #[name]="slotProps">
@@ -192,4 +375,29 @@ defineExpose({ scrollToRow });
white-space: nowrap;
vertical-align: middle;
}
/* 编辑单元格 wrapper:始终同时渲染文本 span 和编辑组件,通过 display 切换。
保证编辑/文本切换时 Vue patch 只更新 props,不触发组件 mount/unmount。 */
::deep(.fms-editable-cell-wrap) {
display: flex;
align-items: center;
width: 100%;
height: 100%;
}
::deep(.fms-editable-cell-wrap .fms-cell-text) {
flex: 1;
}
::deep(
.fms-editable-cell-wrap .ant-input-number,
.fms-editable-cell-wrap .ant-select,
.fms-editable-cell-wrap .ant-input
) {
flex: 1;
}
/* 隐藏 areaSelection 视觉覆盖层:只借用它的键盘导航 + 虚拟滚动跟随,
不需要蓝色的选区高亮遮罩。编辑态下由 EditableCell 的 input/select 展示焦点。 */
::deep(.stk-table-area-selection) {
display: none !important;
}
</style>