新增前端vue
This commit is contained in:
5
web-vue/packages/core/components/Tree/index.ts
Normal file
5
web-vue/packages/core/components/Tree/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import BasicTree from './src/Tree.vue';
|
||||
|
||||
export { BasicTree };
|
||||
export type { ContextMenuItem } from '@jeesite/core/hooks/web/useContextMenu';
|
||||
export * from './src/typing';
|
||||
777
web-vue/packages/core/components/Tree/src/Tree.vue
Normal file
777
web-vue/packages/core/components/Tree/src/Tree.vue
Normal file
@@ -0,0 +1,777 @@
|
||||
<!--
|
||||
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
|
||||
* No deletion without permission, or be held responsible to law.
|
||||
* @description 树结构生成封装兼容并统一多种数据格式
|
||||
* @author Vben、ThinkGem
|
||||
-->
|
||||
<script lang="tsx">
|
||||
import type { FieldNames, Keys, CheckKeys, TreeActionType, TreeItem } from './typing';
|
||||
|
||||
import {
|
||||
defineComponent,
|
||||
reactive,
|
||||
computed,
|
||||
unref,
|
||||
ref,
|
||||
watchEffect,
|
||||
toRaw,
|
||||
watch,
|
||||
onMounted,
|
||||
onBeforeUnmount,
|
||||
CSSProperties,
|
||||
} from 'vue';
|
||||
import { Tree, Empty, Spin } from 'ant-design-vue';
|
||||
import { TreeIcon } from './TreeIcon';
|
||||
import TreeHeader from './TreeHeader.vue';
|
||||
import { ScrollContainer } from '@jeesite/core/components/Container';
|
||||
import { addResizeListener, removeResizeListener } from '@jeesite/core/utils/event';
|
||||
|
||||
import { omit, get, difference, intersection, cloneDeep } from 'lodash-es';
|
||||
import { isArray, isBoolean, isEmpty, isFunction } from '@jeesite/core/utils/is';
|
||||
import { extendSlots, getSlot } from '@jeesite/core/utils/helper/tsxHelper';
|
||||
import { eachTree, filter, listToTree, treeToList } from '@jeesite/core/utils/helper/treeHelper';
|
||||
|
||||
import { useTree } from './useTree';
|
||||
import { useContextMenu } from '@jeesite/core/hooks/web/useContextMenu';
|
||||
import { useDesign } from '@jeesite/core/hooks/web/useDesign';
|
||||
import { useDict } from '@jeesite/core/components/Dict';
|
||||
|
||||
import { basicProps } from './props';
|
||||
import { CreateContextOptions } from '@jeesite/core/components/ContextMenu';
|
||||
|
||||
interface State {
|
||||
expandedKeys: Keys;
|
||||
selectedKeys: Keys;
|
||||
checkedKeys: CheckKeys;
|
||||
halfCheckedKeys: Keys;
|
||||
checkStrictly?: boolean;
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: 'BasicTree',
|
||||
inheritAttrs: false,
|
||||
props: basicProps,
|
||||
emits: [
|
||||
'update:expandedKeys',
|
||||
'update:selectedKeys',
|
||||
'update:value',
|
||||
'change',
|
||||
'check',
|
||||
'update:searchValue',
|
||||
'reload',
|
||||
'tree-data-change',
|
||||
],
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const state = reactive<State>({
|
||||
checkStrictly: props.checkStrictly,
|
||||
expandedKeys: props.expandedKeys || [],
|
||||
selectedKeys: props.selectedKeys || [],
|
||||
checkedKeys: props.checkedKeys || [],
|
||||
halfCheckedKeys: [],
|
||||
});
|
||||
|
||||
const searchState = reactive({
|
||||
startSearch: false,
|
||||
searchText: '',
|
||||
searchData: [] as TreeItem[],
|
||||
});
|
||||
|
||||
const treeDataRef = ref<TreeItem[]>(props.treeData as TreeItem[]);
|
||||
|
||||
if (props.dictType && props.dictType !== '') {
|
||||
const { initSelectTreeData } = useDict();
|
||||
initSelectTreeData(treeDataRef, props.dictType, true);
|
||||
}
|
||||
|
||||
const [createContextMenu] = useContextMenu();
|
||||
const { prefixCls } = useDesign('basic-tree');
|
||||
|
||||
const getFieldNames = computed((): Required<FieldNames> => {
|
||||
const { fieldNames } = props;
|
||||
return {
|
||||
key: 'id',
|
||||
title: 'name',
|
||||
children: 'children',
|
||||
...fieldNames,
|
||||
};
|
||||
});
|
||||
|
||||
const getBindValues = computed(() => {
|
||||
let propsData = {
|
||||
blockNode: true,
|
||||
...attrs,
|
||||
...props,
|
||||
openAnimation: {}, // fix parent undefined
|
||||
expandedKeys: state.expandedKeys,
|
||||
selectedKeys: state.selectedKeys,
|
||||
checkedKeys: state.checkedKeys,
|
||||
checkStrictly: state.checkStrictly,
|
||||
fieldNames: unref(getFieldNames),
|
||||
'onUpdate:expandedKeys': (v: Keys) => {
|
||||
state.expandedKeys = v;
|
||||
emit('update:expandedKeys', v);
|
||||
},
|
||||
'onUpdate:selectedKeys': (v: Keys) => {
|
||||
state.selectedKeys = v;
|
||||
emit('update:selectedKeys', v);
|
||||
},
|
||||
onCheck: (v: CheckKeys, e) => {
|
||||
let currentValue = toRaw(state.checkedKeys) as Keys;
|
||||
if (isArray(currentValue) && searchState.startSearch) {
|
||||
const { key } = unref(getFieldNames);
|
||||
currentValue = difference(currentValue, getChildrenKeys(e.node.dataRef[key]));
|
||||
if (e.checked) {
|
||||
currentValue.push(e.node.dataRef[key]);
|
||||
}
|
||||
state.checkedKeys = currentValue;
|
||||
} else {
|
||||
state.checkedKeys = v;
|
||||
state.halfCheckedKeys = e.halfCheckedKeys || [];
|
||||
}
|
||||
const rawVal = toRaw(state.checkedKeys);
|
||||
emit('update:value', rawVal);
|
||||
emit('check', rawVal, e);
|
||||
},
|
||||
onRightClick: handleRightClick,
|
||||
};
|
||||
return omit(propsData, 'treeData', 'class');
|
||||
});
|
||||
|
||||
const getTreeData = computed((): TreeItem[] =>
|
||||
searchState.startSearch ? searchState.searchData : unref(treeDataRef),
|
||||
);
|
||||
|
||||
const getNotFound = computed((): boolean => {
|
||||
return !getTreeData.value || getTreeData.value.length === 0;
|
||||
});
|
||||
|
||||
const {
|
||||
deleteNodeByKey,
|
||||
insertNodeByKey,
|
||||
insertNodesByKey,
|
||||
filterByLevel,
|
||||
updateNodeByKey,
|
||||
getAllKeys,
|
||||
getChildrenKeys,
|
||||
getEnabledKeys,
|
||||
} = useTree(treeDataRef, getFieldNames);
|
||||
|
||||
function getIcon(params: Recordable, icon?: string) {
|
||||
if (!icon) {
|
||||
if (props.renderIcon && isFunction(props.renderIcon)) {
|
||||
return props.renderIcon(params);
|
||||
}
|
||||
}
|
||||
return icon;
|
||||
}
|
||||
|
||||
async function handleRightClick({ event, node }: Recordable) {
|
||||
const { rightMenuList: menuList = [], beforeRightClick } = props;
|
||||
let contextMenuOptions: CreateContextOptions = { event, items: [] };
|
||||
|
||||
if (beforeRightClick && isFunction(beforeRightClick)) {
|
||||
let result = await beforeRightClick(node, event);
|
||||
if (Array.isArray(result)) {
|
||||
contextMenuOptions.items = result;
|
||||
} else {
|
||||
Object.assign(contextMenuOptions, result);
|
||||
}
|
||||
} else {
|
||||
contextMenuOptions.items = menuList;
|
||||
}
|
||||
if (!contextMenuOptions.items?.length) return;
|
||||
createContextMenu(contextMenuOptions);
|
||||
}
|
||||
|
||||
function setExpandedKeys(keys: Keys) {
|
||||
state.expandedKeys = keys;
|
||||
}
|
||||
|
||||
function getExpandedKeys() {
|
||||
return state.expandedKeys;
|
||||
}
|
||||
|
||||
function setSelectedKeys(keys: Keys) {
|
||||
state.selectedKeys = keys;
|
||||
}
|
||||
|
||||
function getSelectedKeys() {
|
||||
return state.selectedKeys;
|
||||
}
|
||||
|
||||
function setCheckedKeys(keys: Keys) {
|
||||
if (!state.checkStrictly && keys && keys.length > 0) {
|
||||
const childrenKeys = getEnabledKeys(undefined, true);
|
||||
state.checkedKeys = intersection(keys, childrenKeys);
|
||||
state.halfCheckedKeys = difference(keys, childrenKeys);
|
||||
} else {
|
||||
state.checkedKeys = keys || [];
|
||||
}
|
||||
}
|
||||
|
||||
function getCheckedKeys() {
|
||||
let checkedKeys: Keys;
|
||||
if (isArray(state.checkedKeys)) {
|
||||
checkedKeys = [...state.halfCheckedKeys, ...state.checkedKeys];
|
||||
} else if (state.checkedKeys.checked) {
|
||||
checkedKeys = state.checkedKeys.checked;
|
||||
} else {
|
||||
checkedKeys = [];
|
||||
}
|
||||
return checkedKeys;
|
||||
}
|
||||
|
||||
function reload() {
|
||||
loadTreeData();
|
||||
emit('reload');
|
||||
}
|
||||
|
||||
function checkAll(checkAll: boolean) {
|
||||
state.checkedKeys = checkAll ? getEnabledKeys() : ([] as Keys);
|
||||
}
|
||||
|
||||
function expandAll(expandAll: boolean) {
|
||||
state.expandedKeys = expandAll ? getAllKeys() : ([] as Keys);
|
||||
}
|
||||
|
||||
function onStrictlyChange(strictly: boolean) {
|
||||
state.checkStrictly = strictly;
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.searchValue,
|
||||
(val) => {
|
||||
if (val !== searchState.searchText) {
|
||||
searchState.searchText = val;
|
||||
}
|
||||
},
|
||||
{
|
||||
immediate: true,
|
||||
},
|
||||
);
|
||||
|
||||
const isFirstLoaded = ref<boolean>(false);
|
||||
const loading = ref(false);
|
||||
|
||||
watch(
|
||||
() => props.params,
|
||||
() => {
|
||||
isFirstLoaded.value && loadTreeData();
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.immediate,
|
||||
(v) => {
|
||||
v && !isFirstLoaded.value && loadTreeData();
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
if (props.immediate) {
|
||||
loadTreeData();
|
||||
isFirstLoaded.value = true;
|
||||
}
|
||||
});
|
||||
|
||||
async function loadTreeData() {
|
||||
const { api } = props;
|
||||
if (!api || !isFunction(api)) return;
|
||||
loading.value = true;
|
||||
treeDataRef.value = [];
|
||||
let result;
|
||||
try {
|
||||
result = await api(props.params);
|
||||
result = listToTree(result, {
|
||||
callback: (parent, _node) => {
|
||||
if (!props.canSelectParent && parent) {
|
||||
if (parent.children && parent.children.length > 0) {
|
||||
if (props.checkable) {
|
||||
parent.disableCheckbox = true;
|
||||
} else {
|
||||
parent.disabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
if (!result) return;
|
||||
if (!isArray(result)) {
|
||||
result = get(result, props.resultField);
|
||||
}
|
||||
treeDataRef.value = (result as TreeItem[]) || [];
|
||||
emit('tree-data-change', treeDataRef.value);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.treeData,
|
||||
() => {
|
||||
setTreeData(props.treeData);
|
||||
},
|
||||
);
|
||||
|
||||
function setTreeData(treeData: Recordable[] | undefined) {
|
||||
if (!treeData) {
|
||||
loading.value = true;
|
||||
return;
|
||||
}
|
||||
if (props.treeDataSimpleMode) {
|
||||
treeDataRef.value = listToTree(treeData);
|
||||
} else {
|
||||
treeDataRef.value = treeData as TreeItem[];
|
||||
}
|
||||
loading.value = false;
|
||||
emit('tree-data-change', treeDataRef.value);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => treeDataRef.value,
|
||||
(val) => {
|
||||
if (val) {
|
||||
// 展开默认级别,而不是 onMounted 时调用
|
||||
expandDefaultLevel();
|
||||
// 执行搜索过滤
|
||||
handleSearch(searchState.searchText);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
function expandDefaultLevel() {
|
||||
const level = parseInt(props.defaultExpandLevel);
|
||||
if (level > 0) {
|
||||
state.expandedKeys = filterByLevel(level);
|
||||
} else if (props.defaultExpandAll) {
|
||||
expandAll(true);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSearch(searchValue: string) {
|
||||
if (searchValue !== searchState.searchText) searchState.searchText = searchValue;
|
||||
emit('update:searchValue', searchValue);
|
||||
if (!searchValue) {
|
||||
searchState.startSearch = false;
|
||||
return;
|
||||
}
|
||||
const { filterFn, checkable, expandOnSearch, checkOnSearch, selectedOnSearch } = unref(props);
|
||||
searchState.startSearch = true;
|
||||
const { title: titleField, key: keyField } = unref(getFieldNames);
|
||||
|
||||
const matchedKeys: string[] = [];
|
||||
searchState.searchData = filter(
|
||||
unref(treeDataRef),
|
||||
(node) => {
|
||||
const result = filterFn
|
||||
? filterFn(searchValue, node, unref(getFieldNames))
|
||||
: (node[titleField]?.includes(searchValue) ?? false);
|
||||
if (result) {
|
||||
matchedKeys.push(node[keyField]);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
unref(getFieldNames),
|
||||
props.onlySearchLevel,
|
||||
);
|
||||
|
||||
if (expandOnSearch) {
|
||||
const expandKeys = treeToList(searchState.searchData).map((val) => {
|
||||
return val[keyField];
|
||||
});
|
||||
if (expandKeys && expandKeys.length) {
|
||||
setExpandedKeys(expandKeys);
|
||||
}
|
||||
}
|
||||
|
||||
if (checkOnSearch && checkable && matchedKeys.length) {
|
||||
setCheckedKeys(matchedKeys);
|
||||
}
|
||||
|
||||
if (selectedOnSearch && matchedKeys.length) {
|
||||
setSelectedKeys(matchedKeys);
|
||||
}
|
||||
}
|
||||
|
||||
function handleClickNode(key: string, children: TreeItem[]) {
|
||||
if (props.showIcon || !props.clickRowToExpand || !children || children.length === 0) return;
|
||||
if (!state.expandedKeys.includes(key)) {
|
||||
setExpandedKeys([...state.expandedKeys, key]);
|
||||
} else {
|
||||
const keys = [...state.expandedKeys];
|
||||
const index = keys.findIndex((item) => item === key);
|
||||
if (index !== -1) {
|
||||
keys.splice(index, 1);
|
||||
}
|
||||
setExpandedKeys(keys);
|
||||
}
|
||||
}
|
||||
|
||||
// watchEffect(() => {
|
||||
// treeDataRef.value = props.treeData as TreeItem[];
|
||||
// });
|
||||
|
||||
// onMounted(() => {
|
||||
// const level = parseInt(props.defaultExpandLevel);
|
||||
// if (level > 0) {
|
||||
// state.expandedKeys = filterByLevel(level);
|
||||
// } else if (props.defaultExpandAll) {
|
||||
// expandAll(true);
|
||||
// }
|
||||
// });
|
||||
|
||||
watchEffect(() => {
|
||||
state.expandedKeys = props.expandedKeys;
|
||||
});
|
||||
|
||||
watchEffect(() => {
|
||||
state.selectedKeys = props.selectedKeys;
|
||||
});
|
||||
|
||||
watchEffect(() => {
|
||||
state.checkedKeys = props.checkedKeys;
|
||||
});
|
||||
|
||||
watch(
|
||||
() => props.value,
|
||||
() => {
|
||||
state.checkedKeys = toRaw(props.value || []);
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => state.checkedKeys,
|
||||
() => {
|
||||
const v = toRaw(state.checkedKeys);
|
||||
emit('update:value', v);
|
||||
emit('change', v);
|
||||
},
|
||||
);
|
||||
|
||||
// watchEffect(() => {
|
||||
// console.log('======================');
|
||||
// console.log(props.value);
|
||||
// console.log('======================');
|
||||
// if (props.value) {
|
||||
// state.checkedKeys = props.value;
|
||||
// }
|
||||
// });
|
||||
|
||||
watchEffect(() => {
|
||||
state.checkStrictly = props.checkStrictly;
|
||||
});
|
||||
|
||||
const instance: TreeActionType = {
|
||||
setExpandedKeys,
|
||||
getExpandedKeys,
|
||||
setSelectedKeys,
|
||||
getSelectedKeys,
|
||||
setCheckedKeys,
|
||||
getCheckedKeys,
|
||||
insertNodeByKey,
|
||||
insertNodesByKey,
|
||||
deleteNodeByKey,
|
||||
updateNodeByKey,
|
||||
checkAll,
|
||||
expandAll,
|
||||
filterByLevel: (level: number) => {
|
||||
state.expandedKeys = filterByLevel(level);
|
||||
},
|
||||
setSearchValue: (value: string) => {
|
||||
handleSearch(value);
|
||||
},
|
||||
getSearchValue: () => {
|
||||
return searchState.searchText;
|
||||
},
|
||||
setTreeData,
|
||||
reload,
|
||||
};
|
||||
|
||||
expose(instance);
|
||||
|
||||
function renderAction(node: TreeItem) {
|
||||
const { actionList } = props;
|
||||
if (!actionList || actionList.length === 0) return;
|
||||
return actionList.map((item, index) => {
|
||||
let nodeShow = true;
|
||||
if (isFunction(item.show)) {
|
||||
nodeShow = item.show?.(node);
|
||||
} else if (isBoolean(item.show)) {
|
||||
nodeShow = item.show;
|
||||
}
|
||||
|
||||
if (!nodeShow) return null;
|
||||
|
||||
return (
|
||||
<span key={index} class={`${prefixCls}__action`}>
|
||||
{item.render(node)}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const treeData = computed((): TreeItem[] | undefined => {
|
||||
const data = cloneDeep(getTreeData.value);
|
||||
if (!data) return undefined;
|
||||
eachTree(data, (item, _parent) => {
|
||||
const searchText = searchState.searchText;
|
||||
const { highlight } = unref(props);
|
||||
const { title: titleField, key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
|
||||
const icon = getIcon(item, item.icon);
|
||||
const title = get(item, titleField);
|
||||
|
||||
const searchIdx = searchText ? title.indexOf(searchText) : -1;
|
||||
const isHighlight = searchState.startSearch && !isEmpty(searchText) && highlight && searchIdx !== -1;
|
||||
const highlightStyle = `color: ${isBoolean(highlight) ? '#f50' : highlight}`;
|
||||
|
||||
const titleDom = isHighlight ? (
|
||||
<span class={unref(getBindValues)?.blockNode ? `${prefixCls}__content` : ''}>
|
||||
<span>{title.substr(0, searchIdx)}</span>
|
||||
<span style={highlightStyle}>{searchText}</span>
|
||||
<span>{title.substr(searchIdx + (searchText as string).length)}</span>
|
||||
</span>
|
||||
) : (
|
||||
<span innerHTML={title} />
|
||||
);
|
||||
|
||||
// item.isLeaf = !(item.children && item.children.length > 0);
|
||||
item.isLeaf = attrs.loadData
|
||||
? item.isParent != undefined
|
||||
? !item.isParent
|
||||
: item.isLeaf != undefined
|
||||
? item.isLeaf
|
||||
: false
|
||||
: !(item.children && item.children.length > 0);
|
||||
|
||||
item[titleField] = (
|
||||
<span
|
||||
class={`${prefixCls}-title pl-2`}
|
||||
onClick={handleClickNode.bind(null, item[keyField], item[childrenField])}
|
||||
>
|
||||
{slots?.title ? (
|
||||
getSlot(slots, 'title', item)
|
||||
) : (
|
||||
<>
|
||||
{icon && <TreeIcon icon={icon} />}
|
||||
{titleDom}
|
||||
{/*{get(item, titleField)}*/}
|
||||
<span class={`${prefixCls}__actions`}>{renderAction(item)}</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
return item;
|
||||
});
|
||||
return data;
|
||||
});
|
||||
|
||||
const treeHeight = ref<number>();
|
||||
const treeRef = ref<HTMLDivElement>();
|
||||
const treeResize = () => {
|
||||
const el = unref(treeRef) as HTMLDivElement;
|
||||
if (!el || el.clientHeight <= 0) return;
|
||||
if (!el.parentElement?.classList.contains('sidebar-content')) return;
|
||||
let height = el.clientHeight;
|
||||
const header = el.querySelector('.jeesite-basic-tree-header');
|
||||
if (header) height -= header.clientHeight;
|
||||
treeHeight.value = height - 5;
|
||||
};
|
||||
onMounted(() => addResizeListener(unref(treeRef), treeResize));
|
||||
onBeforeUnmount(() => removeResizeListener(unref(treeRef), treeResize));
|
||||
|
||||
return () => {
|
||||
const { title, helpMessage, toolbar, search, checkable, showIcon } = props;
|
||||
const showTitle = title || toolbar || search || slots.headerTitle;
|
||||
const scrollStyle: CSSProperties = {
|
||||
height: unref(treeHeight) + 'px',
|
||||
};
|
||||
const TreeComp = showIcon ? Tree.DirectoryTree : Tree;
|
||||
return (
|
||||
<div ref={treeRef} class={[prefixCls, 'h-full', attrs.class]}>
|
||||
{showTitle && (
|
||||
<TreeHeader
|
||||
checkable={checkable}
|
||||
checkAll={checkAll}
|
||||
expandAll={expandAll}
|
||||
reload={reload}
|
||||
title={title}
|
||||
search={search}
|
||||
toolbar={toolbar}
|
||||
helpMessage={helpMessage}
|
||||
onStrictly-change={onStrictlyChange}
|
||||
onSearch={handleSearch}
|
||||
searchText={searchState.searchText}
|
||||
v-slots={extendSlots(slots)}
|
||||
/>
|
||||
)}
|
||||
<ScrollContainer style={scrollStyle} v-show={!unref(getNotFound)}>
|
||||
<TreeComp
|
||||
{...unref(getBindValues)}
|
||||
treeData={unref(treeData.value)}
|
||||
v-slots={extendSlots(slots, ['default'])}
|
||||
/>
|
||||
</ScrollContainer>
|
||||
<Spin spinning={unref(loading)}>
|
||||
<Empty v-show={unref(getNotFound)} image={Empty.PRESENTED_IMAGE_SIMPLE} class="!mt-4" />
|
||||
</Spin>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="less">
|
||||
@prefix-cls: ~'jeesite-basic-tree';
|
||||
|
||||
.@{prefix-cls} {
|
||||
background-color: @component-background;
|
||||
border-radius: 5px;
|
||||
|
||||
.ant-tree {
|
||||
margin: 10px 6px 10px 10px;
|
||||
background-color: transparent;
|
||||
|
||||
.ant-tree-checkbox {
|
||||
margin-top: -2px;
|
||||
}
|
||||
|
||||
.ant-tree-switcher {
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
.ant-tree-node-content-wrapper {
|
||||
position: relative;
|
||||
display: flex;
|
||||
padding: 0 !important;
|
||||
margin-bottom: 2px;
|
||||
|
||||
//.ant-tree-title {
|
||||
// position: absolute;
|
||||
// left: 0;
|
||||
// width: 100%;
|
||||
// overflow: hidden;
|
||||
// text-overflow: ellipsis;
|
||||
// white-space: nowrap;
|
||||
//}
|
||||
}
|
||||
|
||||
&.ant-tree-directory {
|
||||
.ant-tree-treenode:hover::before {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.ant-tree-treenode {
|
||||
.ant-tree-switcher {
|
||||
color: fade(@text-color-base, 70);
|
||||
width: 20px;
|
||||
}
|
||||
|
||||
.ant-tree-switcher-icon svg {
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.ant-tree-node-content-wrapper {
|
||||
transition: none;
|
||||
|
||||
.ant-tree-title {
|
||||
left: auto;
|
||||
}
|
||||
.@{prefix-cls}-title {
|
||||
padding-left: 3px;
|
||||
}
|
||||
|
||||
.ant-tree-iconEle {
|
||||
color: fade(@text-color-base, 70);
|
||||
width: 20px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: fade(@primary-color, 5);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
&.ant-tree-node-selected {
|
||||
color: @text-color-base;
|
||||
background-color: fade(@primary-color, 15);
|
||||
border-radius: 3px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ant-tree-treenode-selected {
|
||||
color: @text-color-base;
|
||||
|
||||
.ant-tree-switcher,
|
||||
.ant-tree-iconEle {
|
||||
color: fade(@text-color-base, 70);
|
||||
}
|
||||
|
||||
&:hover::before,
|
||||
&::before {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&-title {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
padding: 0 5px;
|
||||
|
||||
&:hover {
|
||||
.@{prefix-cls}__action {
|
||||
visibility: visible;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&__content {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 3px;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
&__action {
|
||||
margin-left: 4px;
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
html[data-theme='light'] {
|
||||
.@{prefix-cls}.bg-gray {
|
||||
background-color: #f9f9f9;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
}
|
||||
|
||||
html[data-theme='dark'] {
|
||||
.@{prefix-cls}.bg-gray {
|
||||
background-color: #1d1d1d;
|
||||
border: 1px solid #383838;
|
||||
}
|
||||
.@{prefix-cls} {
|
||||
.ant-tree {
|
||||
&.ant-tree-directory {
|
||||
> li.ant-tree-treenode-selected > span,
|
||||
.ant-tree-child-tree > li.ant-tree-treenode-selected > span {
|
||||
&.ant-tree-node-content-wrapper {
|
||||
background-color: fade(@primary-color, 50) !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
220
web-vue/packages/core/components/Tree/src/TreeHeader.vue
Normal file
220
web-vue/packages/core/components/Tree/src/TreeHeader.vue
Normal file
@@ -0,0 +1,220 @@
|
||||
<template>
|
||||
<div class="jeesite-basic-tree-header flex items-center px-2 py-1.5">
|
||||
<slot name="headerTitle" v-if="$slots.headerTitle"></slot>
|
||||
<BasicTitle :helpMessage="helpMessage" v-if="!$slots.headerTitle && title">
|
||||
{{ title }}
|
||||
</BasicTitle>
|
||||
<div class="flex flex-1 cursor-pointer items-center justify-self-stretch" v-if="search || toolbar">
|
||||
<div :class="getInputSearchCls" v-if="search">
|
||||
<FormItemRest>
|
||||
<AInput :placeholder="t('common.searchText')" size="small" allowClear v-model:value="searchValue" />
|
||||
</FormItemRest>
|
||||
</div>
|
||||
<Dropdown @click.prevent v-if="toolbar">
|
||||
<Icon icon="i-ant-design:setting-outlined" class="px-1" />
|
||||
<template #overlay>
|
||||
<AMenu @click="handleMenuClick">
|
||||
<template v-for="item in toolbarList" :key="item.value">
|
||||
<MenuItem v-bind="{ key: item.value }">
|
||||
{{ item.label }}
|
||||
</MenuItem>
|
||||
<MenuDivider v-if="item.divider" />
|
||||
</template>
|
||||
</AMenu>
|
||||
</template>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { PropType } from 'vue';
|
||||
import { defineComponent, computed, ref, watch } from 'vue';
|
||||
|
||||
import { Dropdown, Menu, Input, Form } from 'ant-design-vue';
|
||||
import { Icon } from '@jeesite/core/components/Icon';
|
||||
import { BasicTitle } from '@jeesite/core/components/Basic';
|
||||
|
||||
import { propTypes } from '@jeesite/core/utils/propTypes';
|
||||
|
||||
import { useI18n } from '@jeesite/core/hooks/web/useI18n';
|
||||
import { useDebounceFn } from '@vueuse/core';
|
||||
import { MenuInfo } from 'ant-design-vue/es/menu/src/interface';
|
||||
|
||||
enum ToolbarEnum {
|
||||
RELOAD,
|
||||
SELECT_ALL,
|
||||
UN_SELECT_ALL,
|
||||
EXPAND_ALL,
|
||||
UN_EXPAND_ALL,
|
||||
CHECK_STRICTLY,
|
||||
CHECK_UN_STRICTLY,
|
||||
}
|
||||
|
||||
interface ToolbarMenuInfo {
|
||||
key: ToolbarEnum;
|
||||
}
|
||||
|
||||
const props = {
|
||||
helpMessage: {
|
||||
type: [String, Array] as PropType<string | string[]>,
|
||||
default: '',
|
||||
},
|
||||
title: propTypes.string,
|
||||
toolbar: propTypes.bool,
|
||||
checkable: propTypes.bool,
|
||||
search: propTypes.bool,
|
||||
reload: propTypes.func,
|
||||
checkAll: propTypes.func,
|
||||
expandAll: propTypes.func,
|
||||
searchText: propTypes.string,
|
||||
};
|
||||
|
||||
export default defineComponent({
|
||||
name: 'BasicTreeHeader',
|
||||
components: {
|
||||
BasicTitle,
|
||||
Icon,
|
||||
Dropdown,
|
||||
AMenu: Menu,
|
||||
MenuItem: Menu.Item,
|
||||
MenuDivider: Menu.Divider,
|
||||
AInput: Input,
|
||||
FormItemRest: Form.ItemRest,
|
||||
},
|
||||
props,
|
||||
emits: ['strictly-change', 'search'],
|
||||
setup(props, { emit, slots }) {
|
||||
const { t } = useI18n();
|
||||
const searchValue = ref('');
|
||||
|
||||
const getInputSearchCls = computed(() => {
|
||||
const titleExists = slots.headerTitle || props.title;
|
||||
return [
|
||||
'mr-1',
|
||||
'w-full',
|
||||
// titleExists ? 'w-2/3' : 'w-full',
|
||||
{
|
||||
['ml-3']: titleExists,
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const toolbarList = computed<any>(() => {
|
||||
const { checkable } = props;
|
||||
const defaultToolbarList = [
|
||||
{ label: t('component.tree.expandAll'), value: ToolbarEnum.EXPAND_ALL },
|
||||
{
|
||||
label: t('component.tree.unExpandAll'),
|
||||
value: ToolbarEnum.UN_EXPAND_ALL,
|
||||
divider: checkable,
|
||||
},
|
||||
];
|
||||
|
||||
const reload = [{ label: t('component.tree.reload'), value: ToolbarEnum.RELOAD }];
|
||||
|
||||
return checkable
|
||||
? [
|
||||
...reload,
|
||||
{ label: t('component.tree.selectAll'), value: ToolbarEnum.SELECT_ALL },
|
||||
{
|
||||
label: t('component.tree.unSelectAll'),
|
||||
value: ToolbarEnum.UN_SELECT_ALL,
|
||||
divider: checkable,
|
||||
},
|
||||
...defaultToolbarList,
|
||||
{ label: t('component.tree.checkStrictly'), value: ToolbarEnum.CHECK_STRICTLY },
|
||||
{ label: t('component.tree.checkUnStrictly'), value: ToolbarEnum.CHECK_UN_STRICTLY },
|
||||
]
|
||||
: [...reload, ...defaultToolbarList];
|
||||
});
|
||||
|
||||
function handleMenuClick(e: ToolbarMenuInfo | MenuInfo) {
|
||||
const { key } = e;
|
||||
switch (key) {
|
||||
case ToolbarEnum.RELOAD:
|
||||
props.reload?.();
|
||||
break;
|
||||
case ToolbarEnum.SELECT_ALL:
|
||||
props.checkAll?.(true);
|
||||
break;
|
||||
case ToolbarEnum.UN_SELECT_ALL:
|
||||
props.checkAll?.(false);
|
||||
break;
|
||||
case ToolbarEnum.EXPAND_ALL:
|
||||
props.expandAll?.(true);
|
||||
break;
|
||||
case ToolbarEnum.UN_EXPAND_ALL:
|
||||
props.expandAll?.(false);
|
||||
break;
|
||||
case ToolbarEnum.CHECK_STRICTLY:
|
||||
emit('strictly-change', false);
|
||||
break;
|
||||
case ToolbarEnum.CHECK_UN_STRICTLY:
|
||||
emit('strictly-change', true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function emitChange(value?: string): void {
|
||||
emit('search', value);
|
||||
}
|
||||
const debounceEmitChange = useDebounceFn(emitChange, 200);
|
||||
|
||||
watch(
|
||||
() => searchValue.value,
|
||||
(v) => {
|
||||
debounceEmitChange(v);
|
||||
},
|
||||
);
|
||||
watch(
|
||||
() => props.searchText,
|
||||
(v) => {
|
||||
if (v !== searchValue.value) {
|
||||
searchValue.value = v;
|
||||
}
|
||||
},
|
||||
);
|
||||
// function handleSearch(e: ChangeEvent): void {
|
||||
// debounceEmitChange(e.target.value);
|
||||
// }
|
||||
|
||||
return { t, toolbarList, handleMenuClick, searchValue, getInputSearchCls };
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<style lang="less">
|
||||
html[data-theme='dark'] {
|
||||
.jeesite-basic-tree-header {
|
||||
border-bottom: 1px solid #303030;
|
||||
color: rgb(255 255 255 / 75%);
|
||||
}
|
||||
}
|
||||
|
||||
.jeesite-basic-tree-header {
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
color: @text-color-base;
|
||||
min-height: 35px;
|
||||
overflow: hidden;
|
||||
|
||||
.jeesite-basic-title {
|
||||
font-size: 16px;
|
||||
line-height: 15px;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.anticon {
|
||||
color: @text-color-call-out;
|
||||
}
|
||||
|
||||
.ant-input-affix-wrapper-status-error {
|
||||
&.ant-input-affix-wrapper {
|
||||
border-color: @border-color-base !important;
|
||||
|
||||
&:focus,
|
||||
&-focused {
|
||||
box-shadow: 0 0 0 2px fade(@border-color-base, 10%) !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
13
web-vue/packages/core/components/Tree/src/TreeIcon.ts
Normal file
13
web-vue/packages/core/components/Tree/src/TreeIcon.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { VNode } from 'vue';
|
||||
|
||||
import { h } from 'vue';
|
||||
import { isString } from '@jeesite/core/utils/is';
|
||||
import { Icon } from '@jeesite/core/components/Icon';
|
||||
|
||||
export const TreeIcon = ({ icon }: { icon: VNode | string | undefined }) => {
|
||||
if (!icon) return null;
|
||||
if (isString(icon)) {
|
||||
return h(Icon, { icon, class: 'mr-1' });
|
||||
}
|
||||
return h(Icon);
|
||||
};
|
||||
112
web-vue/packages/core/components/Tree/src/props.ts
Normal file
112
web-vue/packages/core/components/Tree/src/props.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import type { PropType } from 'vue';
|
||||
import type { FieldNames, TreeActionItem, Keys, CheckKeys, ContextMenuOptions, TreeItem } from './typing';
|
||||
import type { ContextMenuItem } from '@jeesite/core/hooks/web/useContextMenu';
|
||||
import type { TreeDataItem } from 'ant-design-vue/es/tree';
|
||||
import { propTypes } from '@jeesite/core/utils/propTypes';
|
||||
|
||||
export const basicProps = {
|
||||
value: {
|
||||
type: [Object, Array] as PropType<Keys | CheckKeys>,
|
||||
},
|
||||
renderIcon: {
|
||||
type: Function as PropType<(params: Recordable) => string>,
|
||||
},
|
||||
|
||||
helpMessage: {
|
||||
type: [String, Array] as PropType<string | string[]>,
|
||||
default: '',
|
||||
},
|
||||
|
||||
title: propTypes.string,
|
||||
toolbar: propTypes.bool,
|
||||
search: propTypes.bool,
|
||||
searchValue: propTypes.string,
|
||||
checkStrictly: propTypes.bool,
|
||||
showIcon: propTypes.bool.def(false),
|
||||
clickRowToExpand: propTypes.bool.def(true),
|
||||
checkable: propTypes.bool.def(false),
|
||||
defaultExpandLevel: {
|
||||
type: [String, Number] as PropType<string | number>,
|
||||
default: '',
|
||||
},
|
||||
defaultExpandAll: propTypes.bool.def(false),
|
||||
|
||||
// formatter for ztree
|
||||
treeDataSimpleMode: propTypes.bool.def(true),
|
||||
|
||||
fieldNames: {
|
||||
type: Object as PropType<FieldNames>,
|
||||
},
|
||||
|
||||
treeData: {
|
||||
type: Array as PropType<TreeDataItem[]>,
|
||||
},
|
||||
|
||||
api: { type: Function as PropType<(arg?: Recordable) => Promise<Recordable>> },
|
||||
params: { type: Object as PropType<Recordable> },
|
||||
canSelectParent: propTypes.bool.def(true),
|
||||
immediate: { type: Boolean, default: true },
|
||||
resultField: propTypes.string.def(''),
|
||||
dictType: propTypes.string,
|
||||
|
||||
actionList: {
|
||||
type: Array as PropType<TreeActionItem[]>,
|
||||
default: () => [],
|
||||
},
|
||||
|
||||
expandedKeys: {
|
||||
type: Array as PropType<Keys>,
|
||||
default: () => [],
|
||||
},
|
||||
|
||||
selectedKeys: {
|
||||
type: Array as PropType<Keys>,
|
||||
default: () => [],
|
||||
},
|
||||
|
||||
checkedKeys: {
|
||||
type: Array as PropType<CheckKeys>,
|
||||
default: () => [],
|
||||
},
|
||||
|
||||
beforeRightClick: {
|
||||
type: Function as PropType<(...arg: any) => ContextMenuItem[] | ContextMenuOptions>,
|
||||
default: null,
|
||||
},
|
||||
|
||||
rightMenuList: {
|
||||
type: Array as PropType<ContextMenuItem[]>,
|
||||
},
|
||||
// 自定义数据过滤判断方法(注: 不是整个过滤方法,而是内置过滤的判断方法,用于增强原本仅能通过title进行过滤的方式)
|
||||
filterFn: {
|
||||
type: Function as PropType<(searchValue: any, node: TreeItem, fieldNames: FieldNames) => boolean>,
|
||||
default: null,
|
||||
},
|
||||
// 高亮搜索值,仅高亮具体匹配值(通过title)值为true时使用默认色值,值为#xxx时使用此值替代且高亮开启
|
||||
highlight: {
|
||||
type: [Boolean, String] as PropType<boolean | string>,
|
||||
default: false,
|
||||
},
|
||||
// 搜索完成时自动展开结果
|
||||
expandOnSearch: propTypes.bool.def(true),
|
||||
// 搜索完成自动选中所有结果,当且仅当 checkable===true 时生效
|
||||
checkOnSearch: propTypes.bool.def(false),
|
||||
// 搜索完成自动select所有结果
|
||||
selectedOnSearch: propTypes.bool.def(false),
|
||||
// 只搜索树表指定的层级,获得该层级下所有结果
|
||||
onlySearchLevel: propTypes.number,
|
||||
};
|
||||
|
||||
export const treeNodeProps = {
|
||||
actionList: {
|
||||
type: Array as PropType<TreeActionItem[]>,
|
||||
default: () => [],
|
||||
},
|
||||
fieldNames: {
|
||||
type: Object as PropType<FieldNames>,
|
||||
},
|
||||
treeData: {
|
||||
type: Array as PropType<TreeDataItem[]>,
|
||||
default: () => [],
|
||||
},
|
||||
};
|
||||
57
web-vue/packages/core/components/Tree/src/typing.ts
Normal file
57
web-vue/packages/core/components/Tree/src/typing.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import type { TreeDataItem } from 'ant-design-vue/es/tree';
|
||||
import { ContextMenuItem } from '@jeesite/core/hooks/web/useContextMenu';
|
||||
|
||||
export interface TreeActionItem {
|
||||
render: (record: Recordable) => any;
|
||||
show?: boolean | ((record: Recordable) => boolean);
|
||||
}
|
||||
|
||||
export interface TreeItem extends TreeDataItem {
|
||||
icon?: any;
|
||||
id?: string;
|
||||
pId?: string;
|
||||
name?: string;
|
||||
children?: TreeItem[];
|
||||
}
|
||||
|
||||
export interface FieldNames {
|
||||
children?: string;
|
||||
title?: string;
|
||||
key?: string;
|
||||
}
|
||||
|
||||
export type Keys = (string | number)[];
|
||||
export type CheckKeys = (string | number)[] | { checked: (string | number)[]; halfChecked: (string | number)[] };
|
||||
|
||||
export interface TreeActionType {
|
||||
checkAll: (checkAll: boolean) => void;
|
||||
expandAll: (expandAll: boolean) => void;
|
||||
setExpandedKeys: (keys: Keys) => void;
|
||||
getExpandedKeys: () => Keys;
|
||||
setSelectedKeys: (keys: Keys) => void;
|
||||
getSelectedKeys: () => Keys;
|
||||
setCheckedKeys: (keys: Keys) => void;
|
||||
getCheckedKeys: () => Keys;
|
||||
filterByLevel: (level: number) => void;
|
||||
insertNodeByKey: (opt: InsertNodeParams) => void;
|
||||
insertNodesByKey: (opt: InsertNodeParams) => void;
|
||||
deleteNodeByKey: (key: string) => void;
|
||||
updateNodeByKey: (key: string, node: Omit<TreeDataItem, 'key'>, list?: TreeDataItem[]) => void;
|
||||
setSearchValue: (value: string) => void;
|
||||
getSearchValue: () => string;
|
||||
setTreeData: (treeData: Recordable[] | undefined) => void;
|
||||
reload: () => void;
|
||||
}
|
||||
|
||||
export interface InsertNodeParams {
|
||||
parentKey: string | null;
|
||||
node: TreeDataItem;
|
||||
list?: TreeDataItem[];
|
||||
push?: 'push' | 'unshift';
|
||||
}
|
||||
|
||||
export interface ContextMenuOptions {
|
||||
icon?: string;
|
||||
styles?: any;
|
||||
items?: ContextMenuItem[];
|
||||
}
|
||||
207
web-vue/packages/core/components/Tree/src/useTree.ts
Normal file
207
web-vue/packages/core/components/Tree/src/useTree.ts
Normal file
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
|
||||
* No deletion without permission, or be held responsible to law.
|
||||
* @description 树结构数据操作工具
|
||||
* @author Vben、ThinkGem
|
||||
*/
|
||||
import type { InsertNodeParams, Keys, FieldNames } from './typing';
|
||||
import type { Ref, ComputedRef } from 'vue';
|
||||
import type { TreeDataItem } from 'ant-design-vue/es/tree';
|
||||
|
||||
import { cloneDeep } from 'lodash-es';
|
||||
import { unref } from 'vue';
|
||||
import { forEach } from '@jeesite/core/utils/helper/treeHelper';
|
||||
|
||||
export function useTree(treeDataRef: Ref<TreeDataItem[]>, getFieldNames: ComputedRef<FieldNames>) {
|
||||
// Get all keys
|
||||
function getAllKeys(list?: TreeDataItem[]) {
|
||||
const keys: string[] = [];
|
||||
const treeData = list || unref(treeDataRef);
|
||||
const { key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
if (!childrenField || !keyField) return keys;
|
||||
|
||||
for (let index = 0; index < treeData.length; index++) {
|
||||
const node = treeData[index];
|
||||
keys.push(node[keyField]!);
|
||||
const children = node[childrenField];
|
||||
if (children && children.length) {
|
||||
keys.push(...(getAllKeys(children) as string[]));
|
||||
}
|
||||
}
|
||||
return keys as Keys;
|
||||
}
|
||||
|
||||
// Get keys that can be checked and selected
|
||||
function getEnabledKeys(list?: TreeDataItem[], onlyChildren = false) {
|
||||
const keys: string[] = [];
|
||||
const treeData = list || unref(treeDataRef);
|
||||
const { key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
if (!childrenField || !keyField) return keys;
|
||||
for (let index = 0; index < treeData.length; index++) {
|
||||
const node = treeData[index];
|
||||
const children = node[childrenField];
|
||||
if (node.disabled !== true && node.selectable !== false) {
|
||||
if (onlyChildren) {
|
||||
if (!(children && children.length > 0)) {
|
||||
keys.push(node[keyField]!);
|
||||
}
|
||||
} else {
|
||||
keys.push(node[keyField]!);
|
||||
}
|
||||
}
|
||||
if (children && children.length) {
|
||||
keys.push(...(getEnabledKeys(children, onlyChildren) as string[]));
|
||||
}
|
||||
}
|
||||
return keys as Keys;
|
||||
}
|
||||
|
||||
// Get children keys
|
||||
function getChildrenKeys(nodeKey: string | number, list?: TreeDataItem[]): Keys {
|
||||
const keys: Keys = [];
|
||||
const treeData = list || unref(treeDataRef);
|
||||
const { key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
if (!childrenField || !keyField) return keys;
|
||||
for (let index = 0; index < treeData.length; index++) {
|
||||
const node = treeData[index];
|
||||
const children = node[childrenField];
|
||||
if (nodeKey === node[keyField]) {
|
||||
keys.push(node[keyField]!);
|
||||
if (children && children.length) {
|
||||
keys.push(...(getAllKeys(children) as string[]));
|
||||
}
|
||||
} else {
|
||||
if (children && children.length) {
|
||||
keys.push(...getChildrenKeys(nodeKey, children));
|
||||
}
|
||||
}
|
||||
}
|
||||
return keys as Keys;
|
||||
}
|
||||
|
||||
// Update node
|
||||
function updateNodeByKey(key: string, node: Omit<TreeDataItem, 'key'>, list?: TreeDataItem[]) {
|
||||
if (!key) return;
|
||||
const treeData = list || unref(treeDataRef);
|
||||
const { key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
|
||||
if (!childrenField || !keyField) return;
|
||||
|
||||
for (let index = 0; index < treeData.length; index++) {
|
||||
const element: any = treeData[index];
|
||||
const children = element[childrenField];
|
||||
|
||||
if (element[keyField] === key) {
|
||||
treeData[index] = { ...treeData[index], ...node };
|
||||
break;
|
||||
} else if (children && children.length) {
|
||||
updateNodeByKey(key, node, element[childrenField]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Expand the specified level
|
||||
function filterByLevel(level = 1, list?: TreeDataItem[], currentLevel = 1) {
|
||||
if (!level) {
|
||||
return [];
|
||||
}
|
||||
const res: (string | number)[] = [];
|
||||
const data = list || unref(treeDataRef) || [];
|
||||
for (let index = 0; index < data.length; index++) {
|
||||
const item = data[index];
|
||||
|
||||
const { key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
const key = keyField ? item[keyField] : '';
|
||||
const children = childrenField ? item[childrenField] : [];
|
||||
res.push(key);
|
||||
if (children && children.length && currentLevel < level) {
|
||||
currentLevel += 1;
|
||||
res.push(...filterByLevel(level, children, currentLevel));
|
||||
}
|
||||
}
|
||||
return res as string[] | number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加节点
|
||||
*/
|
||||
function insertNodeByKey({ parentKey = null, node, push = 'push' }: InsertNodeParams) {
|
||||
const treeData: any = cloneDeep(unref(treeDataRef));
|
||||
if (!parentKey) {
|
||||
treeData[push](node);
|
||||
treeDataRef.value = treeData;
|
||||
return;
|
||||
}
|
||||
const { key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
if (!childrenField || !keyField) return;
|
||||
|
||||
forEach(treeData, (treeItem) => {
|
||||
if (treeItem[keyField] === parentKey) {
|
||||
treeItem[childrenField] = treeItem[childrenField] || [];
|
||||
treeItem[childrenField][push](node);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
treeDataRef.value = treeData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量添加节点
|
||||
*/
|
||||
function insertNodesByKey({ parentKey = null, list, push = 'push' }: InsertNodeParams) {
|
||||
const treeData: any = cloneDeep(unref(treeDataRef));
|
||||
if (!list || list.length < 1) {
|
||||
return;
|
||||
}
|
||||
if (!parentKey) {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
treeData[push](list[i]);
|
||||
}
|
||||
} else {
|
||||
const { key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
if (!childrenField || !keyField) return;
|
||||
|
||||
forEach(treeData, (treeItem) => {
|
||||
if (treeItem[keyField] === parentKey) {
|
||||
treeItem[childrenField] = treeItem[childrenField] || [];
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
treeItem[childrenField][push](list[i]);
|
||||
}
|
||||
treeDataRef.value = treeData;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Delete node
|
||||
function deleteNodeByKey(key: string, list?: TreeDataItem[]) {
|
||||
if (!key) return;
|
||||
const treeData = list || unref(treeDataRef);
|
||||
const { key: keyField, children: childrenField } = unref(getFieldNames);
|
||||
if (!childrenField || !keyField) return;
|
||||
|
||||
for (let index = 0; index < treeData.length; index++) {
|
||||
const element: any = treeData[index];
|
||||
const children = element[childrenField];
|
||||
|
||||
if (element[keyField] === key) {
|
||||
treeData.splice(index, 1);
|
||||
break;
|
||||
} else if (children && children.length) {
|
||||
deleteNodeByKey(key, element[childrenField]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
deleteNodeByKey,
|
||||
insertNodeByKey,
|
||||
insertNodesByKey,
|
||||
filterByLevel,
|
||||
updateNodeByKey,
|
||||
getAllKeys,
|
||||
getChildrenKeys,
|
||||
getEnabledKeys,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user