use-selection.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import { Rect } from "konva/lib/shapes/Rect";
  2. import {
  3. globalWatch,
  4. installGlobalVar,
  5. useForciblyShowItemIds,
  6. useMountParts,
  7. useStage,
  8. } from "./use-global-vars";
  9. import {
  10. useFormalLayer,
  11. useHelperLayer,
  12. useGetFormalChildren,
  13. } from "./use-layer";
  14. import { themeColor } from "@/constant";
  15. import { dragListener } from "@/utils/event";
  16. import { Layer } from "konva/lib/Layer";
  17. import { useOperMode } from "./use-status";
  18. import {
  19. computed,
  20. markRaw,
  21. nextTick,
  22. reactive,
  23. Ref,
  24. ref,
  25. toRaw,
  26. watch,
  27. watchEffect,
  28. } from "vue";
  29. import { EntityShape } from "@/deconstruction";
  30. import { Util } from "konva/lib/Util";
  31. import {
  32. useViewerInvertTransform,
  33. useViewerInvertTransformConfig,
  34. } from "./use-viewer";
  35. import { debounce, diffArrayChange, mergeFuns, onlyId } from "@/utils/shared";
  36. import { IRect } from "konva/lib/types";
  37. import { useMouseShapesStatus } from "./use-mouse-status";
  38. import Icon from "../components/icon/temp-icon.vue";
  39. import { Group } from "konva/lib/Group";
  40. import { Component as GroupComp, GroupData } from "../components/group";
  41. import { useStore } from "../store";
  42. import { useGetShapeBelong, useOnComponentBoundChange } from "./use-component";
  43. import { useHistory } from "./use-history";
  44. import { isRectContained } from "@/utils/math";
  45. import { useTransformer } from "./use-transformer";
  46. import { IconData } from "../components/icon";
  47. import { usePause } from "./use-pause";
  48. import mitt, { Emitter } from "mitt";
  49. import { components, ShapeType, shapeTypes } from "../components";
  50. import { getFlatChildren } from "@/utils/shape";
  51. export const useExcludeSelection = installGlobalVar(() => ref<string[]>([]));
  52. // 多选不包含分组, 只包含选中者
  53. export const useSelection = installGlobalVar(() => {
  54. const layer = useHelperLayer();
  55. const eSelection = useExcludeSelection();
  56. const getChildren = useGetFormalChildren();
  57. const box = new Rect({
  58. stroke: themeColor,
  59. strokeWidth: 1,
  60. fill: "#fff",
  61. listening: false,
  62. opacity: 0.5,
  63. });
  64. const stage = useStage();
  65. const operMode = useOperMode();
  66. const selections = ref<EntityShape[]>();
  67. const transformer = useTransformer();
  68. const getShapeSelectionManage = useGetShapeSelectionManage();
  69. let itemShapeBoxs: IRect[][] = [];
  70. let itemShapes: EntityShape[][] = [];
  71. const updateSelections = () => {
  72. const boxRect = box.getClientRect();
  73. selections.value = [];
  74. for (let i = 0; i < itemShapeBoxs.length; i++) {
  75. for (let j = 0; j < itemShapeBoxs[i].length; j++) {
  76. const shape = itemShapes[i][j];
  77. const box = itemShapeBoxs[i][j];
  78. const itemSelects: EntityShape[] = [];
  79. if (
  80. Util.haveIntersection(boxRect, box) &&
  81. !isRectContained(box, boxRect)
  82. ) {
  83. if (!selections.value.includes(shape)) {
  84. selections.value.push(shape);
  85. itemSelects.push(shape);
  86. }
  87. }
  88. }
  89. }
  90. };
  91. const store = useStore();
  92. const init = (dom: HTMLDivElement, layer: Layer) => {
  93. store.bus.on("addItemAfter", updateInitData);
  94. store.bus.on('dataChangeAfter', updateInitData);
  95. const stopListener = dragListener(dom, {
  96. down(pos) {
  97. layer.add(box);
  98. box.x(pos.x);
  99. box.y(pos.y);
  100. box.width(0);
  101. box.height(0);
  102. },
  103. move({ end }) {
  104. box.width(end.x - box.x());
  105. box.height(end.y - box.y());
  106. updateSelections();
  107. },
  108. up() {
  109. selections.value = undefined;
  110. box.remove();
  111. },
  112. });
  113. return () => {
  114. store.bus.off("addItemAfter", updateInitData);
  115. store.bus.off('dataChangeAfter', updateInitData);
  116. stopListener();
  117. box.remove();
  118. };
  119. };
  120. const updateInitData = () => {
  121. itemShapes = getChildren().map((item) =>
  122. getFlatChildren(item).filter(
  123. (shape) =>
  124. !eSelection.value.includes(shape.id()) &&
  125. shape !== toRaw(transformer) &&
  126. getShapeSelectionManage(shape)?.canSelect(shape)
  127. )
  128. );
  129. itemShapeBoxs = itemShapes.map((shapes) =>
  130. shapes.map((shape) => shape.getClientRect())
  131. );
  132. };
  133. const stopWatch = globalWatch(
  134. () => operMode.value.mulSelection,
  135. (mulSelection, _, onCleanup) => {
  136. if (!mulSelection) return;
  137. const dom = stage.value?.getNode().container()!;
  138. updateInitData();
  139. onCleanup(init(dom, layer.value!));
  140. }
  141. );
  142. return {
  143. onDestroy: stopWatch,
  144. var: { selections, box },
  145. };
  146. });
  147. type ShapeIconArgs = Partial<
  148. Pick<IconData, "width" | "height" | "url" | "fill" | "stroke">
  149. >;
  150. export const useShapesIcon = (
  151. shapes: Ref<EntityShape[] | undefined>,
  152. args: ShapeIconArgs = {}
  153. ) => {
  154. const mParts = useMountParts();
  155. const { on } = useOnComponentBoundChange();
  156. const iconProps = {
  157. width: 12,
  158. height: 12,
  159. url: "./icons/state_s.svg",
  160. fill: themeColor,
  161. stroke: "#fff",
  162. ...args,
  163. listening: false,
  164. };
  165. const invConfig = useViewerInvertTransformConfig();
  166. const invMat = useViewerInvertTransform();
  167. const getShapeMat = (shape: EntityShape) => {
  168. const rect = shape.getClientRect();
  169. const center = invMat.value.point({
  170. x: rect.x + rect.width / 2,
  171. y: rect.y + rect.height / 2,
  172. });
  173. return [1, 0, 0, 1, center.x, center.y];
  174. };
  175. const unMountMap = new WeakMap<EntityShape, () => void>();
  176. const pause = usePause();
  177. const stop = watch([shapes, () => pause.isPause], ([shapes], [oldShapes]) => {
  178. if (pause.isPause) {
  179. shapes = [];
  180. }
  181. const { added, deleted } = diffArrayChange(shapes || [], oldShapes || []);
  182. for (const addShape of added) {
  183. const mat = ref(getShapeMat(addShape));
  184. const data = reactive({ ...iconProps, mat: mat });
  185. const unHooks = [
  186. on(addShape, () => (mat.value = getShapeMat(addShape))),
  187. watch(
  188. invConfig,
  189. () => {
  190. data.width = invConfig.value.scaleX * iconProps.width;
  191. data.height = invConfig.value.scaleY * iconProps.height;
  192. },
  193. { immediate: true }
  194. ),
  195. mParts.add({
  196. comp: markRaw(Icon),
  197. props: { data },
  198. }),
  199. ];
  200. unMountMap.set(addShape, mergeFuns(unHooks));
  201. }
  202. for (const delShape of deleted) {
  203. const fn = unMountMap.get(delShape);
  204. fn && fn();
  205. }
  206. });
  207. return [stop, pause];
  208. };
  209. export type SelectionManageBus = Emitter<Record<"del" | "update", EntityShape>>;
  210. export type SelectionManage = {
  211. canSelect: (shape: EntityShape, selects?: EntityShape[]) => boolean;
  212. listener: (shape: EntityShape) => {
  213. stop: () => void;
  214. bus: SelectionManageBus;
  215. };
  216. };
  217. export type UseGetSelectionManage = () => SelectionManage;
  218. export const useStoreSelectionManage = installGlobalVar((): SelectionManage => {
  219. const store = useStore();
  220. const { on } = useOnComponentBoundChange();
  221. const canSelect = (shape: EntityShape) => {
  222. const id = shape.id();
  223. return !!(id && store.items.some((item) => item.id === id));
  224. };
  225. const listener = (shape: EntityShape) => {
  226. const bus: SelectionManageBus = mitt();
  227. const stop = watch(
  228. () => canSelect(shape),
  229. (exixts, _, onCleanup) => {
  230. if (!exixts) {
  231. bus.emit("del", shape);
  232. } else {
  233. onCleanup(on(shape, () => bus.emit("update", shape)));
  234. }
  235. },
  236. { immediate: true }
  237. );
  238. return { stop, bus };
  239. };
  240. return { canSelect, listener };
  241. });
  242. export const useGetShapeSelectionManage = installGlobalVar(() => {
  243. const compManages: Partial<Record<ShapeType, SelectionManage>> = {};
  244. for (const type of shapeTypes) {
  245. compManages[type] =
  246. components[type].useGetSelectionManage &&
  247. components[type].useGetSelectionManage();
  248. }
  249. const storeManage = useStoreSelectionManage();
  250. const getShapeBelong = useGetShapeBelong();
  251. return (shape: EntityShape) => {
  252. const bl = getShapeBelong(shape);
  253. if (!bl) return;
  254. if (compManages[bl.type]) {
  255. return compManages[bl.type];
  256. } else if (bl.isSelf) {
  257. return storeManage;
  258. }
  259. };
  260. });
  261. export const useSelectionRevise = () => {
  262. const getShapeSelectionManage = useGetShapeSelectionManage();
  263. const mParts = useMountParts();
  264. const status = useMouseShapesStatus();
  265. const store = useStore();
  266. const { selections: rectSelects } = useSelection();
  267. let selfSet = false;
  268. const setSelectShapes = (shapes: EntityShape[]) => {
  269. selfSet = true;
  270. status.selects = shapes;
  271. selfSet = false;
  272. };
  273. let initSelections: EntityShape[] = [];
  274. watch(
  275. () => rectSelects.value && [...rectSelects.value],
  276. (rectSelects, oldRectSelects) => {
  277. if (!oldRectSelects) {
  278. initSelections = [...status.selects];
  279. } else if (!rectSelects) {
  280. initSelections = [];
  281. } else {
  282. setSelectShapes(initSelections.concat(rectSelects));
  283. }
  284. }
  285. );
  286. useShapesIcon(computed(() => status.selects.concat(rectSelects.value || [])));
  287. const filterSelect = debounce(() => {
  288. const selects = new Set<EntityShape>();
  289. for (const shape of status.selects) {
  290. const children = getFlatChildren(shape);
  291. children.forEach((childShape) => {
  292. const manage = getShapeSelectionManage(childShape);
  293. if (manage?.canSelect(childShape)) {
  294. selects.add(childShape);
  295. }
  296. });
  297. }
  298. setSelectShapes([...selects]);
  299. }, 16);
  300. store.bus.on("delItemAfter", filterSelect);
  301. store.bus.on("clearAfter", filterSelect);
  302. store.bus.on("dataChangeAfter", filterSelect);
  303. store.bus.on("setCurrentLayerAfter", filterSelect);
  304. watch(
  305. () => status.selects,
  306. () => selfSet || filterSelect(),
  307. { flush: "sync" }
  308. );
  309. const ids = computed(() => [
  310. ...new Set(status.selects.map((item) => item.id())),
  311. ]);
  312. const groupConfig = {
  313. id: onlyId(),
  314. createTime: Date.now(),
  315. lock: false,
  316. opacity: 1,
  317. ref: false,
  318. listening: false,
  319. stroke: themeColor,
  320. };
  321. const operMode = useOperMode();
  322. const layer = useFormalLayer();
  323. watch(
  324. () => [!!ids.value.length, operMode.value.mulSelection],
  325. (_a, _b) => {
  326. const groupShape = layer.value?.findOne<Group>(`#${groupConfig.id}`);
  327. if (!groupShape) return;
  328. if (ids.value.length && !operMode.value.mulSelection) {
  329. status.actives = [groupShape];
  330. } else if (status.actives.includes(groupShape)) {
  331. status.actives = [];
  332. }
  333. }
  334. );
  335. const stage = useStage();
  336. const history = useHistory();
  337. const showItemId = useForciblyShowItemIds();
  338. watchEffect((onCleanup) => {
  339. if (!ids.value.length) return;
  340. const props = {
  341. data: { ...groupConfig, ids: ids.value },
  342. key: groupConfig.id,
  343. onUpdateShape(data: GroupData) {
  344. // status.selects;
  345. // data.ids;
  346. },
  347. onDelShape() {
  348. setSelectShapes([]);
  349. },
  350. onAddShape(data: GroupData) {
  351. history.onceTrack(() => {
  352. const ids = data.ids;
  353. const groups = store.typeItems.group;
  354. const exists = groups?.some((group) => {
  355. if (group.ids.length !== ids.length) return false;
  356. const diff = diffArrayChange(group.ids, ids);
  357. return diff.added.length === 0 && diff.deleted.length == 0;
  358. });
  359. if (exists) return;
  360. store.addItem("group", { ...data, ids });
  361. showItemId.cycle(data.id, async () => {
  362. await nextTick();
  363. const $stage = stage.value!.getNode();
  364. const addShape = $stage.findOne("#" + data.id) as EntityShape;
  365. setSelectShapes([addShape]);
  366. });
  367. });
  368. },
  369. };
  370. onCleanup(mParts.add({ comp: markRaw(GroupComp), props }));
  371. });
  372. };