createCompHooks.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { useEditor } from "@/modules/editor";
  2. import { DesignComp } from "@/modules/editor/objects/DesignTemp/DesignComp";
  3. import { Background, Layout } from "@/modules/editor/typings";
  4. import { cloneDeep, defaultsDeep } from "lodash";
  5. import { AnyFun } from "queenjs/typing";
  6. import { addCacheToMap } from "./createCompId";
  7. type IOptions<T, C> = {
  8. value: T;
  9. layout?: Layout;
  10. background?: Background;
  11. children?: C;
  12. };
  13. export function createCompHooks<T, C extends { [name: string]: AnyFun }>(
  14. defaultOpts: IOptions<T, C>
  15. ) {
  16. function createComp(opts: any) {
  17. const defData: any = cloneDeep(defaultOpts);
  18. if (defData.children) {
  19. Object.entries(defData.children).forEach(([key, fn]: any) => {
  20. defData.children[key] = fn(defData);
  21. });
  22. }
  23. const options = defaultsDeep(opts, defData)
  24. return new DesignComp(options);
  25. }
  26. function useCompData(compId: string) {
  27. const editor = useEditor();
  28. const comp = editor.store.designData.compMap[compId];
  29. return comp as {
  30. value: T;
  31. children: { [name in keyof C]: ReturnType<C[name]> };
  32. layout: Layout;
  33. };
  34. }
  35. function useCreateChild<T extends keyof C>(key: T) {
  36. const editor = useEditor();
  37. const createChild: any = (...args: any) => {
  38. const result = (defaultOpts as any).children[key](defaultOpts, ...args);
  39. addCacheToMap(editor.store.designData.compMap);
  40. return result;
  41. };
  42. return createChild as C[T];
  43. }
  44. return {
  45. createComp,
  46. useCompData,
  47. useCreateChild,
  48. };
  49. }