yesamer commented on code in PR #2687: URL: https://github.com/apache/incubator-kie-tools/pull/2687#discussion_r1810611084
########## packages/scesim-editor-envelope/src/TestScenarioEditorRoot.tsx: ########## @@ -0,0 +1,517 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import * as React from "react"; +import { useEffect, useMemo, useState } from "react"; +import * as __path from "path"; +import { + imperativePromiseHandle, + PromiseImperativeHandle, +} from "@kie-tools-core/react-hooks/dist/useImperativePromiseHandler"; +import { generateUuid } from "@kie-tools/boxed-expression-component/dist/api"; +import { ResourceContent, SearchType, WorkspaceChannelApi, WorkspaceEdit } from "@kie-tools-core/workspace/dist/api"; +import { KeyboardShortcutsService } from "@kie-tools-core/keyboard-shortcuts/dist/envelope/KeyboardShortcutsService"; +import { Flex } from "@patternfly/react-core/dist/js/layouts/Flex"; +import { EmptyState, EmptyStateBody, EmptyStateIcon } from "@patternfly/react-core/dist/js/components/EmptyState"; +import { Title } from "@patternfly/react-core/dist/js/components/Title"; +import { domParser } from "@kie-tools/xml-parser-ts"; +import { normalize } from "@kie-tools/dmn-marshaller/dist/normalization/normalize"; +import { getMarshaller as getDmnMarshaller } from "@kie-tools/dmn-marshaller"; +import * as TestScenarioEditor from "@kie-tools/scesim-editor/dist/TestScenarioEditor"; +import { getMarshaller, SceSimMarshaller, SceSimModel } from "@kie-tools/scesim-marshaller"; +import { EMPTY_ONE_EIGHT } from "@kie-tools/scesim-editor/dist/resources/EmptyScesimFile"; + +export const DMN_MODELS_SEARCH_GLOB_PATTERN = "**/*.{dmn}"; + +export type TestScenarioEditorRootProps = { + exposing: (s: TestScenarioEditorRoot) => void; + isReadOnly: boolean; + keyboardShortcutsService: KeyboardShortcutsService | undefined; + onNewEdit: (edit: WorkspaceEdit) => void; + onRequestWorkspaceFilesList: WorkspaceChannelApi["kogitoWorkspace_resourceListRequest"]; + onRequestWorkspaceFileContent: WorkspaceChannelApi["kogitoWorkspace_resourceContentRequest"]; + onOpenFileFromNormalizedPosixPathRelativeToTheWorkspaceRoot: WorkspaceChannelApi["kogitoWorkspace_openFile"]; + workspaceRootAbsolutePosixPath: string; +}; + +export type TestScenarioEditorRootState = { + error: Error | undefined; + externalModelsByNamespace: TestScenarioEditor.ExternalDmnsIndex; + externalModelsManagerDoneBootstraping: boolean; + isReadOnly: boolean; + keyboardShortcutsRegistred: boolean; + keyboardShortcutsRegisterIds: number[]; + marshaller: SceSimMarshaller | undefined; + openFilenormalizedPosixPathRelativeToTheWorkspaceRoot: string | undefined; + pointer: number; + stack: SceSimModel[]; +}; + +export class TestScenarioEditorRoot extends React.Component<TestScenarioEditorRootProps, TestScenarioEditorRootState> { + private readonly externalModelsManagerDoneBootstraping = imperativePromiseHandle<void>(); + + private readonly testScenarioEditorRef: React.RefObject<TestScenarioEditor.TestScenarioEditorRef>; + + constructor(props: TestScenarioEditorRootProps) { + super(props); + props.exposing(this); + this.testScenarioEditorRef = React.createRef(); + this.state = { + error: undefined, + externalModelsByNamespace: {}, + externalModelsManagerDoneBootstraping: false, + isReadOnly: props.isReadOnly, + keyboardShortcutsRegisterIds: [], + keyboardShortcutsRegistred: false, + marshaller: undefined, + openFilenormalizedPosixPathRelativeToTheWorkspaceRoot: undefined, + pointer: -1, + stack: [], + }; + } + + // Exposed API + + public async undo(): Promise<void> { + this.setState((prev) => ({ ...prev, pointer: Math.max(0, prev.pointer - 1) })); + } + + public async redo(): Promise<void> { + this.setState((prev) => ({ ...prev, pointer: Math.min(prev.stack.length - 1, prev.pointer + 1) })); + } + + public async getDiagramSvg(): Promise<string | undefined> { + return this.testScenarioEditorRef.current?.getDiagramSvg(); + } + + public async getContent(): Promise<string> { + if (!this.state.marshaller || !this.model) { + throw new Error( + `Test Scenario EDITOR ROOT: Content has not been set yet. Throwing an error to prevent returning a "default" content.` + ); + } + + return this.state.marshaller.builder.build(this.model); + } + + public async setContent( + openFilenormalizedPosixPathRelativeToTheWorkspaceRoot: string, + content: string + ): Promise<void> { + const marshaller = this.getMarshaller(content); + + // Save stack + let savedStackPointer: SceSimModel[] = []; + + // Set the model and path for external models manager. + this.setState((prev) => { + savedStackPointer = [...prev.stack]; + return { + stack: [marshaller.parser.parse()], + openFilenormalizedPosixPathRelativeToTheWorkspaceRoot, + pointer: 0, + }; + }); + + // Wait the external manager models to load. + await this.externalModelsManagerDoneBootstraping.promise; + + // Set the valeus to render the Test Scenario Editor. + this.setState((prev) => { + // External change to the same file. + if ( + prev.openFilenormalizedPosixPathRelativeToTheWorkspaceRoot === + openFilenormalizedPosixPathRelativeToTheWorkspaceRoot + ) { + const newStack = savedStackPointer.slice(0, prev.pointer + 1); + return { + externalModelsManagerDoneBootstraping: true, + isReadOnly: prev.isReadOnly, + openFilenormalizedPosixPathRelativeToTheWorkspaceRoot, + marshaller, + pointer: newStack.length, + stack: [...newStack, marshaller.parser.parse()], + }; + } + + // Different file opened. Need to reset everything. + else { + return { + externalModelsManagerDoneBootstraping: true, + isReadOnly: prev.isReadOnly, + marshaller, + openFilenormalizedPosixPathRelativeToTheWorkspaceRoot, + pointer: 0, + stack: [marshaller.parser.parse()], + }; + } + }); + } + + public get model(): SceSimModel | undefined { + return this.state.stack[this.state.pointer]; + } + + // Internal methods + + private getMarshaller(content: string) { + try { + return getMarshaller(content || EMPTY_ONE_EIGHT); + } catch (e) { + this.setState((s) => ({ + ...s, + error: e, + })); + throw e; + } + } + + private setExternalModelsByNamespace = (externalModelsByNamespace: TestScenarioEditor.ExternalDmnsIndex) => { + this.setState((prev) => ({ ...prev, externalModelsByNamespace })); + }; + + private onModelChange: TestScenarioEditor.OnSceSimModelChange = (model) => { + this.setState( + (prev) => { + const newStack = prev.stack.slice(0, prev.pointer + 1); + return { + ...prev, + stack: [...newStack, model], + pointer: newStack.length, + }; + }, + () => + this.props.onNewEdit({ + id: `${this.state.openFilenormalizedPosixPathRelativeToTheWorkspaceRoot}__${generateUuid()}`, + }) + ); + }; + + private onRequestExternalModelsAvailableToInclude: TestScenarioEditor.OnRequestExternalModelsAvailableToInclude = + async () => { + if (!this.state.openFilenormalizedPosixPathRelativeToTheWorkspaceRoot) { + return []; + } + + const list = await this.props.onRequestWorkspaceFilesList({ + pattern: DMN_MODELS_SEARCH_GLOB_PATTERN, + opts: { type: SearchType.TRAVERSAL }, + }); + + return list.normalizedPosixPathsRelativeToTheWorkspaceRoot.flatMap((p) => + __path.relative(__path.dirname(this.state.openFilenormalizedPosixPathRelativeToTheWorkspaceRoot!), p) + ); + }; + + private onRequestToResolvePathRelativeToTheOpenFile: TestScenarioEditor.OnRequestToResolvePath = ( + normalizedPosixPathRelativeToTheOpenFile + ) => { + const normalizedPosixPathRelativeToTheWorkspaceRoot = __path + .resolve( + __path.dirname(this.state.openFilenormalizedPosixPathRelativeToTheWorkspaceRoot!), + normalizedPosixPathRelativeToTheOpenFile + ) + .substring(1); // Remove leading slash. + + return normalizedPosixPathRelativeToTheWorkspaceRoot; + + // Example: + // this.state.openFileAbsolutePath = /Users/ljmotta/packages/dmns/Dmn.dmn + // normalizedPosixPathRelativeToTheOpenFile = ../../tmp/Tmp.dmn + // workspaceRootAbsolutePosixPath = /Users/ljmotta + // resolvedAbsolutePath = /Users/ljmotta/tmp/Tmp.dmn + // return (which is the normalizedPosixPathRelativeToTheWorkspaceRoot) = tmp/Tmp.dmn + }; + + private onRequestExternalModelByPathsRelativeToTheOpenFile: TestScenarioEditor.OnRequestExternalModelByPath = async ( + normalizedPosixPathRelativeToTheOpenFile + ) => { + const normalizedPosixPathRelativeToTheWorkspaceRoot = this.onRequestToResolvePathRelativeToTheOpenFile( + normalizedPosixPathRelativeToTheOpenFile + ); + const resource = await this.props.onRequestWorkspaceFileContent({ + normalizedPosixPathRelativeToTheWorkspaceRoot, + opts: { type: "text" }, + }); + + const ext = __path.extname(normalizedPosixPathRelativeToTheOpenFile); + if (ext === ".dmn") { + return { + normalizedPosixPathRelativeToTheOpenFile, + type: "dmn", + model: normalize(getDmnMarshaller(resource?.content ?? "", { upgradeTo: "latest" }).parser.parse()), + svg: "", + }; + } else { + throw new Error(`Unknown extension '${ext}'.`); Review Comment: @jomarko Only DMN files are directly imported. In case of RULE-based Test Scenario, we don't import the DRL file, but the Java Classes present in the user project. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
