use-selection.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. useGetFormalChildren,
  11. useFormalLayer,
  12. useHelperLayer,
  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. toRaw,
  25. watch,
  26. watchEffect,
  27. } from "vue";
  28. import { EntityShape } from "@/deconstruction";
  29. import { Util } from "konva/lib/Util";
  30. import { useViewerInvertTransform } from "./use-viewer";
  31. import { debounce, diffArrayChange, mergeFuns, onlyId } from "@/utils/shared";
  32. import { IRect } from "konva/lib/types";
  33. import { useMouseShapesStatus } from "./use-mouse-status";
  34. import Icon from "../components/icon/temp-icon.vue";
  35. import { Group } from "konva/lib/Group";
  36. import { Component as GroupComp, GroupData } from "../components/group/";
  37. import { DrawStore, useStore } from "../store";
  38. import { DrawItem } from "../components";
  39. import { Stage } from "konva/lib/Stage";
  40. import { useOnComponentBoundChange } from "./use-component";
  41. import { useHistory } from "./use-history";
  42. import { isRectContained } from "@/utils/math";
  43. import { useTransformer } from "./use-transformer";
  44. const normalSelectIds = (
  45. store: DrawStore,
  46. ids: string[],
  47. needChildren = false
  48. ) => {
  49. if (!store.typeItems.group) return ids;
  50. const gChildrenIds = store.typeItems.group.map((item) => item.ids);
  51. const findNdx = (id: string) =>
  52. gChildrenIds.findIndex((cIds) => cIds.includes(id));
  53. if (!needChildren) {
  54. return ids.filter((id) => !~findNdx(id));
  55. }
  56. const groupIds = store.typeItems.group.map((item) => item.id);
  57. const nIds: string[] = [];
  58. for (let i = 0; i < ids.length; i++) {
  59. let ndx = findNdx(ids[i]);
  60. ~ndx || (ndx = groupIds.indexOf(ids[i]));
  61. if (!~ndx) {
  62. nIds.push(ids[i]);
  63. continue;
  64. }
  65. const group = store.typeItems.group[ndx];
  66. const addIds = [group.id, ...group.ids].filter(
  67. (aid) => !nIds.includes(aid)
  68. );
  69. nIds.push(...addIds);
  70. }
  71. return nIds;
  72. };
  73. export const normalSelectShapes = (
  74. stage: Stage,
  75. store: DrawStore,
  76. shapes: EntityShape[],
  77. needChildren = false
  78. ) => {
  79. let ids: string[] = [];
  80. for (let i = 0; i < shapes.length; i++) {
  81. const shape = shapes[i];
  82. const id = shape.id();
  83. id && ids.push(id);
  84. }
  85. ids = normalSelectIds(store, ids, needChildren);
  86. return ids.map((id) => stage.findOne(`#${id}`)!) as EntityShape[];
  87. };
  88. export const normalSelectItems = (
  89. store: DrawStore,
  90. items: DrawItem[],
  91. needChildren = false
  92. ) => {
  93. return normalSelectIds(
  94. store,
  95. items.map((item) => item.id),
  96. needChildren
  97. ).map((id) => store.getItemById(id)!);
  98. };
  99. export const useSelection = installGlobalVar(() => {
  100. const layer = useHelperLayer();
  101. const getChildren = useGetFormalChildren();
  102. const box = new Rect({
  103. stroke: themeColor,
  104. strokeWidth: 1,
  105. fill: "#fff",
  106. listening: false,
  107. opacity: 0.5,
  108. });
  109. const stage = useStage();
  110. const operMode = useOperMode();
  111. const selections = ref<EntityShape[]>();
  112. const transformer = useTransformer();
  113. let shapeBoxs: IRect[] = [];
  114. let shapes: EntityShape[] = [];
  115. const updateSelections = () => {
  116. const boxRect = box.getClientRect();
  117. selections.value = [];
  118. for (let i = 0; i < shapeBoxs.length; i++) {
  119. if (
  120. Util.haveIntersection(boxRect, shapeBoxs[i]) &&
  121. !isRectContained(shapeBoxs[i], boxRect) &&
  122. shapes[i] !== toRaw(transformer)
  123. ) {
  124. if (!selections.value.includes(shapes[i])) {
  125. selections.value.push(shapes[i]);
  126. }
  127. }
  128. }
  129. };
  130. const init = (dom: HTMLDivElement, layer: Layer) => {
  131. const stopListener = dragListener(dom, {
  132. down(pos) {
  133. layer.add(box);
  134. box.x(pos.x);
  135. box.y(pos.y);
  136. box.width(0);
  137. box.height(0);
  138. },
  139. move({ end }) {
  140. box.width(end.x - box.x());
  141. box.height(end.y - box.y());
  142. updateSelections();
  143. },
  144. up() {
  145. selections.value = undefined;
  146. box.remove();
  147. },
  148. });
  149. return () => {
  150. stopListener();
  151. box.remove();
  152. };
  153. };
  154. const updateInitData = () => {
  155. shapes = getChildren();
  156. shapeBoxs = shapes.map((shape) => shape.getClientRect());
  157. };
  158. const stopWatch = globalWatch(
  159. () => operMode.value.mulSelection,
  160. (mulSelection, _, onCleanup) => {
  161. if (!mulSelection) return;
  162. const dom = stage.value?.getNode().container()!;
  163. updateInitData();
  164. onCleanup(init(dom, layer.value!));
  165. }
  166. );
  167. return {
  168. onDestroy: stopWatch,
  169. var: selections,
  170. };
  171. });
  172. export const useSelectionShowIcons = installGlobalVar(() => {
  173. const mParts = useMountParts();
  174. const { on } = useOnComponentBoundChange();
  175. const iconProps = {
  176. width: 20,
  177. height: 20,
  178. url: "./icons/state_s.svg",
  179. fill: themeColor,
  180. stroke: "#fff",
  181. listening: false,
  182. };
  183. const status = useMouseShapesStatus();
  184. const store = useStore();
  185. const invMat = useViewerInvertTransform();
  186. const getShapeMat = (shape: EntityShape) => {
  187. const rect = shape.getClientRect();
  188. const center = invMat.value.point({
  189. x: rect.x + rect.width / 2,
  190. y: rect.y + rect.height / 2,
  191. });
  192. return [1, 0, 0, 1, center.x, center.y];
  193. };
  194. const shapes = computed(() =>
  195. status.selects.filter((shape) => store.getType(shape.id()) !== "group")
  196. );
  197. const unMountMap = new WeakMap<EntityShape, () => void>();
  198. watch(shapes, (shapes, oldShapes) => {
  199. const { added, deleted } = diffArrayChange(shapes, oldShapes);
  200. for (const addShape of added) {
  201. const mat = ref(getShapeMat(addShape));
  202. const unHooks = [
  203. on(addShape, () => (mat.value = getShapeMat(addShape))),
  204. mParts.add({
  205. comp: markRaw(Icon),
  206. props: {
  207. data: reactive({ ...iconProps, mat: mat }),
  208. },
  209. }),
  210. ];
  211. unMountMap.set(addShape, mergeFuns(unHooks));
  212. }
  213. for (const delShape of deleted) {
  214. const fn = unMountMap.get(delShape);
  215. fn && fn();
  216. }
  217. });
  218. });
  219. const useWatchSelection = () => {
  220. const status = useMouseShapesStatus();
  221. const addShapes = (allShapes: Set<EntityShape>, iShapes: EntityShape[]) => {
  222. iShapes.forEach((shape) => allShapes.add(toRaw(shape)));
  223. return allShapes;
  224. };
  225. const delShapes = (allShapes: Set<EntityShape>, dShapes: EntityShape[]) => {
  226. dShapes.forEach((item) => allShapes.delete(toRaw(item)));
  227. return allShapes;
  228. };
  229. // 分组管理
  230. const watchSelection = () =>
  231. watch(
  232. () => status.selects,
  233. (shapes) => {
  234. const fShapes = Array.from(new Set(shapes));
  235. const { added, deleted } = diffArrayChange(shapes, fShapes);
  236. if (added.length || deleted.length) {
  237. status.selects = fShapes;
  238. }
  239. },
  240. { flush: "post" }
  241. );
  242. return {
  243. addShapes,
  244. delShapes,
  245. watchSelection,
  246. };
  247. };
  248. const useWatchSelectionGroup = () => {
  249. const stage = useStage();
  250. const store = useStore();
  251. const status = useMouseShapesStatus();
  252. const addShapes = (allShapes: Set<EntityShape>, iShapes: EntityShape[]) => {
  253. const shapes = normalSelectShapes(
  254. stage.value!.getNode(),
  255. store,
  256. iShapes,
  257. true
  258. );
  259. shapes.forEach((shape) => allShapes.add(shape));
  260. return allShapes;
  261. };
  262. const delShapes = (allShapes: Set<EntityShape>, dShapes: EntityShape[]) => {
  263. const shapes = normalSelectShapes(
  264. stage.value!.getNode(),
  265. store,
  266. dShapes,
  267. true
  268. );
  269. shapes.forEach((item) => allShapes.delete(item));
  270. return allShapes;
  271. };
  272. // 分组管理
  273. const watchSelection = () =>
  274. watch(
  275. () => status.selects,
  276. (shapes, oldShapes) => {
  277. const { added, deleted } = diffArrayChange(shapes, oldShapes);
  278. const filterShapes = new Set(shapes);
  279. added.length && addShapes(filterShapes, added);
  280. deleted.length && delShapes(filterShapes, deleted);
  281. if (added.length || deleted.length) {
  282. status.selects = Array.from(filterShapes);
  283. }
  284. },
  285. { flush: "post" }
  286. );
  287. return {
  288. addShapes,
  289. delShapes,
  290. watchSelection,
  291. };
  292. };
  293. export const useSelectionRevise = () => {
  294. const mParts = useMountParts();
  295. const status = useMouseShapesStatus();
  296. const store = useStore();
  297. // const { addShapes, delShapes, watchSelection } =
  298. // useWatchSelectionGroup();
  299. const { addShapes, delShapes, watchSelection } = useWatchSelection();
  300. useSelectionShowIcons();
  301. const getFormatChildren = useGetFormalChildren();
  302. const filterSelect = debounce(() => {
  303. const children = getFormatChildren();
  304. const mouseSelects = status.selects.filter((shape) =>
  305. children.includes(shape)
  306. );
  307. status.selects = mouseSelects;
  308. }, 16);
  309. store.bus.on("delItemAfter", filterSelect);
  310. store.bus.on("clearAfter", filterSelect);
  311. store.bus.on("dataChangeAfter", filterSelect);
  312. store.bus.on("setCurrentLayerAfter", filterSelect);
  313. const rectSelects = useSelection();
  314. let initSelections: EntityShape[] = [];
  315. let stopWatchSelection = watchSelection();
  316. watch(
  317. () => rectSelects.value && [...rectSelects.value],
  318. (rectSelects, oldRectSelects) => {
  319. if (!oldRectSelects) {
  320. initSelections = [...status.selects];
  321. stopWatchSelection();
  322. } else if (!rectSelects) {
  323. initSelections = [];
  324. stopWatchSelection = watchSelection();
  325. } else {
  326. status.selects = Array.from(
  327. addShapes(new Set(initSelections), rectSelects)
  328. );
  329. }
  330. }
  331. );
  332. const ids = computed(() => [...new Set(status.selects.map((item) => item.id()))]);
  333. const groupConfig = {
  334. id: onlyId(),
  335. createTime: Date.now(),
  336. lock: false,
  337. opacity: 1,
  338. ref: false,
  339. listening: false,
  340. stroke: themeColor,
  341. };
  342. const operMode = useOperMode();
  343. const layer = useFormalLayer();
  344. watch(
  345. () => [!!ids.value.length, operMode.value.mulSelection],
  346. (_a, _b) => {
  347. const groupShape = layer.value?.findOne<Group>(`#${groupConfig.id}`);
  348. if (!groupShape) return;
  349. if (ids.value.length && !operMode.value.mulSelection) {
  350. status.actives = [groupShape];
  351. } else if (status.actives.includes(groupShape)) {
  352. status.actives = [];
  353. }
  354. }
  355. );
  356. const stage = useStage();
  357. const history = useHistory();
  358. const showItemId = useForciblyShowItemIds();
  359. watchEffect((onCleanup) => {
  360. if (!ids.value.length) return;
  361. const props = {
  362. data: { ...groupConfig, ids: ids.value },
  363. key: groupConfig.id,
  364. onUpdateShape(data: GroupData) {
  365. status.selects;
  366. data.ids;
  367. },
  368. onDelShape() {
  369. status.selects = [];
  370. },
  371. onAddShape(data: GroupData) {
  372. history.onceTrack(() => {
  373. const ids = data.ids;
  374. const cIds = ids.filter((id) => store.getType(id) !== "group");
  375. const groups = store.typeItems.group;
  376. const exists = groups?.some((group) => {
  377. if (group.ids.length !== cIds.length) return false;
  378. const diff = diffArrayChange(group.ids, cIds);
  379. return diff.added.length === 0 && diff.deleted.length == 0;
  380. });
  381. if (exists) return;
  382. let selects = new Set(status.selects);
  383. for (let i = 0; i < ids.length; i++) {
  384. if (store.getType(ids[i]) === "group") {
  385. delShapes(
  386. selects,
  387. status.selects.filter((shape) => shape.id() === ids[i])
  388. );
  389. store.delItem("group", ids[i]);
  390. }
  391. }
  392. store.addItem("group", { ...data, ids: cIds });
  393. showItemId.cycle(data.id, async () => {
  394. await nextTick();
  395. const $stage = stage.value!.getNode();
  396. const addShape = $stage.findOne("#" + data.id) as EntityShape;
  397. addShapes(selects, [addShape]);
  398. status.selects = Array.from(selects);
  399. });
  400. });
  401. },
  402. };
  403. onCleanup(mParts.add({ comp: markRaw(GroupComp), props }));
  404. });
  405. };