DesignComp.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { cloneDeep, isEmpty } from "lodash";
  2. import { nanoid } from "nanoid";
  3. import { Background, ICompKeys, Layout } from "../../typings";
  4. import { mapValuesDeep } from "@/utils";
  5. export class DesignComp {
  6. // declare pid: string; // pid 作为前端临时数据,不存储到服务器,在初始化时关联
  7. declare $el: HTMLElement; // $el 映射dom
  8. id = nanoid();
  9. title = "";
  10. thumbnail = "";
  11. compKey: ICompKeys = "Text";
  12. value: any = undefined;
  13. layout: Layout = { size: [200, 200] };
  14. background: Background = {};
  15. children: Record<string, any> & { default?: string[] } = {};
  16. anim?:{startMatrix: string, endMatrix:string, transition: boolean}
  17. constructor(data?: Partial<DesignComp>) {
  18. if (!data) return;
  19. if (data instanceof DesignComp) return data;
  20. const fromData = Object.fromEntries(
  21. Object.entries(data).filter(
  22. ([, value]) => value !== null && value !== undefined
  23. )
  24. );
  25. Object.assign(this, cloneDeep(fromData));
  26. }
  27. getChildIds() {
  28. return mapValuesDeep(
  29. this.children,
  30. (v) => typeof v === "string",
  31. (v: string) => v
  32. );
  33. }
  34. isPostioned() {
  35. return this.layout.position === "absolute";
  36. }
  37. isTransformed() {
  38. return !isEmpty(this.layout.transform);
  39. }
  40. isFullWidth() {
  41. const w = this.layout.size?.[0];
  42. return !w || w === 750;
  43. }
  44. translate(x: number, y: number) {
  45. this.layout.transform || (this.layout.transform = {});
  46. x && (this.layout.transform.x = x);
  47. y && (this.layout.transform.y = y);
  48. }
  49. getW() {
  50. return this.layout.size?.[0] || 0;
  51. }
  52. getH() {
  53. return this.layout.size?.[1] || 0;
  54. }
  55. getBoundRect() {
  56. const out = { x: 0, y: 0, w: 0, h: 0 };
  57. if (!this.$el) return out;
  58. const r = this.$el.getBoundingClientRect();
  59. out.w = r.width;
  60. out.h = r.height;
  61. out.x = r.left;
  62. out.y = r.top;
  63. return out;
  64. }
  65. setH(height: number) {
  66. this.layout.size[1] = height;
  67. }
  68. setW(w: number) {
  69. this.layout.size[0] = w;
  70. }
  71. setSize(w: number, h: number) {
  72. this.layout.size[0] = w;
  73. this.layout.size[1] = h;
  74. }
  75. }