DesignComp.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 = {};
  14. background: Background = {};
  15. children: Record<string, any> & { default?: string[] } = {};
  16. constructor(data?: Partial<DesignComp>) {
  17. if (!data) return;
  18. if (data instanceof DesignComp) return data;
  19. const fromData = Object.fromEntries(
  20. Object.entries(data).filter(
  21. ([, value]) => value !== null && value !== undefined
  22. )
  23. );
  24. Object.assign(this, cloneDeep(fromData));
  25. }
  26. getChildIds() {
  27. return mapValuesDeep(
  28. this.children,
  29. (v) => typeof v === "string",
  30. (v: string) => v
  31. );
  32. }
  33. isPostioned() {
  34. return this.layout.position === "absolute";
  35. }
  36. isTransformed() {
  37. return !isEmpty(this.layout.transform);
  38. }
  39. isFullWidth() {
  40. const w = this.layout.size?.[0];
  41. return !w || w === 750;
  42. }
  43. translate(x: number, y: number) {
  44. this.layout.transform || (this.layout.transform = {});
  45. x && (this.layout.transform.x = x);
  46. y && (this.layout.transform.y = y);
  47. }
  48. getW() {
  49. return this.layout.size?.[0] || 0;
  50. }
  51. getH() {
  52. return this.layout.size?.[1] || 0;
  53. }
  54. setH(height: number) {
  55. if (!this.layout.size) this.layout.size = [];
  56. this.layout.size[1] = height;
  57. }
  58. }