Untitled

 avatar
unknown
plain_text
a month ago
6.3 kB
5
Indexable
loadSections(request: EditorSelectionChangeRequest) {
  const { nodes: nodeQueue, sectionsToRemove } = request;
  const queue: Node[] = [...nodeQueue];

  // Remove sections if necessary
  if (sectionsToRemove) {
    sectionsToRemove.forEach((key) => {
      const section = (
        this.flattenDataService.flattenDataByKey(
          [...(this.pageLayouts ?? [])].map((lay) => lay.sections).flat(1),
          'content'
        ) as PageSection[]
      ).find((sec) => sec.key && sec.key === key);

      if (section) {
        section.content = [];
        section.tables = [];
        section.header = undefined;
        section.expandedOnce = false;
        section.collapsed = false;
        section.loading = true;
        section.isItem = false;
        section.styleClass = undefined;
        section.messages = [];
      }
    });
  }

  while (queue.length > 0) {
    const node = queue.shift(); // Get the next node
    if (!node) continue;

    const nodeIsItemChild =
      [...(node.key?.split('-') ?? [])].length > 1 &&
      isNaN(Number(node.key?.split('-')[0]));

    // Check if the section is already loaded
    if (this.getSectionLoadedState(<string>node.key) || !node.parent) {
      if (
        this.queryStringService
          .getUrlParamsByKey(SELECTION_PARAM_KEY)
          .some((key) => key === node.key) ||
        node.selectable === false
      ) {
        this.queryStringService.removeUrlParamsByKey(SELECTION_PARAM_KEY, [
          <string>node.key,
        ]);
        this.selectionChange$.next({
          node,
          requestType: EditorSelectionChangeType.Hide,
        });
      } else {
        this.queryStringService.addUrlParam(
          SELECTION_PARAM_KEY,
          <string>node.key
        );
        this.selectionChange$.next({
          node,
          requestType: EditorSelectionChangeType.Show,
        });
      }
      continue;
    }

    // Handle parent node loading for item children
    if (nodeIsItemChild) {
      const parentHasLoaded = this.getSectionLoadedState(
        <string>node.parent?.key
      );

      if (node.parent && !parentHasLoaded) {
        queue.unshift(node.parent); // Add parent to the front of the queue
        continue;
      }
    }

    const layout = [...(this.pageLayouts ?? [])].find(
      (layout) => layout.key === this.getTopLevelTreeNode(<string>node.key).key
    );

    if (!layout) continue;

    let section = layout.sections.find((section) => section.key === node.key);
    if (!section) {
      section = {
        key: '',
        collapsed: true,
        content: [],
      };
    }

    const itemNode = this.setupValues?.find(
      (value) =>
        value.nodeName === node.key?.split('-')[0] &&
        value.nodeType === NodeType.I
    );

    // Load the section
    const observable = forkJoin({
      itemNames: itemNode
        ? this.itemDataService.getItemNameList(<ItemNameRequest>{
            nodeDefIds: [itemNode.nodeDefId],
            versioncar: this.setup?.versionCar,
          })
        : of(undefined),
      pageSection: this.pageSectionDataService.getByKey(
        <string>node.key,
        <string>this.versionCar
      ),
      nodeMetadata: this.nodeMetatadataService.getWithQuery({
        names: [node.key as string],
      }),
    });

    observable
      .pipe(
        catchError((err) => {
          this.messageService.add({
            severity: 'error',
            detail: this.i18nService.translate(
              'editor.EDITORPAGE.MESSAGE.ERRORITEMLOAD',
              {},
              this.i18nService.getActiveLang()
            ),
          });
          console.warn('Page section could not be loaded', err);
          return of(undefined);
        }),
        filter((data) => data !== undefined),
        mergeMap(({ itemNames, pageSection, nodeMetadata }) => {
          let itemId: undefined | number = undefined;
          const metadata = nodeMetadata[0];

          if (metadata?.metadata?.position) {
            section.styleClass = `config-editor__panel--position-${metadata.metadata.position}`;
          }

          if (itemNode && itemNames) {
            itemId =
              typeof itemNode.value === 'string'
                ? itemNames.find((x) => x.itemName === itemNode.value)?.id
                : itemNode.value;
          }

          if (
            itemId === undefined &&
            metadata?.nodeType === NodeType.I &&
            !itemNames?.some((itemName) => itemName.itemName === itemNode?.value)
          ) {
            return of(undefined);
          }

          return forkJoin({
            pageSection: of(pageSection),
            relItemData: itemId
              ? this.itemDataService.getById(itemId).pipe(
                  catchError((err) => {
                    console.warn('Error loading item', err);
                    return of(undefined);
                  })
                )
              : of(undefined),
          });
        }),
        finalize(() => {
          this.queryStringService.addUrlParam(
            SELECTION_PARAM_KEY,
            <string>node.key
          );
          this.selectionChange$.next({
            node,
            requestType: EditorSelectionChangeType.Load,
          });
        })
      )
      .subscribe((data) => {
        // Handle the loaded section and its data
        if (!data) {
          section.messages = [
            ...(section.messages ?? []),
            {
              severity: 'error',
              detail: this.i18nService.translate(
                'editor.EDITORPAGE.MESSAGE.ERRORITEMEXISTS',
                {},
                this.i18nService.getActiveLang()
              ),
            },
          ];
          section.header = node.label;
          section.key = <string>node.key;
          section.expandedOnce = true;
        } else {
          const { relItemData, pageSection } = data;
          section.header = pageSection.header;
          section.key = <string>node.key;
          section.content = <EditorContent[]>pageSection.content;

          if (relItemData) {
            section.itemName = relItemData.name;
            section.valueName = <string>relItemData.name;
            section.isItem = true;
            section.expandedOnce = true;
          }
        }
      });
  }
}
Leave a Comment