From 7fdf733a64670fceefc3ded35cfa581e1c458179 Mon Sep 17 00:00:00 2001 From: Einav Weiss Keidar Date: Tue, 20 Mar 2018 14:45:40 +0200 Subject: Adding Prettier and fixing up eslint version Issue-ID: SDC-1094 Change-Id: Ie83ad95a03899345dd90235daf0323cbe3bc6afd Signed-off-by: Einav Weiss Keidar --- dox-sequence-diagram-ui/.prettierrc | 5 + dox-sequence-diagram-ui/eslintrc.json | 136 +- dox-sequence-diagram-ui/package.json | 114 +- .../webapp/lib/ecomp/asdc/sequencer/Sequencer.jsx | 307 ++-- .../lib/ecomp/asdc/sequencer/common/Common.js | 622 +++---- .../lib/ecomp/asdc/sequencer/common/Logger.js | 191 ++- .../lib/ecomp/asdc/sequencer/common/Options.js | 193 ++- .../components/application/Application.jsx | 450 ++--- .../asdc/sequencer/components/diagram/Diagram.jsx | 1729 +++++++++++--------- .../components/diagram/components/popup/Popup.jsx | 148 +- .../asdc/sequencer/components/dialog/Dialog.jsx | 405 ++--- .../asdc/sequencer/components/editor/Editor.jsx | 248 ++- .../editor/components/designer/Designer.jsx | 708 ++++---- .../designer/components/actions/Actions.jsx | 860 +++++----- .../designer/components/lifeline/Lifeline.jsx | 397 ++--- .../designer/components/lifeline/LifelineNew.jsx | 132 +- .../designer/components/lifeline/Lifelines.jsx | 189 ++- .../designer/components/message/Message.jsx | 1012 ++++++------ .../designer/components/message/MessageNew.jsx | 126 +- .../designer/components/message/Messages.jsx | 201 ++- .../designer/components/metadata/Metadata.jsx | 8 +- .../components/editor/components/source/Source.jsx | 90 +- .../editor/components/toolbar/Toolbar.jsx | 228 +-- .../asdc/sequencer/components/export/Export.jsx | 21 +- .../ecomp/asdc/sequencer/components/icons/Icon.jsx | 15 +- .../asdc/sequencer/components/overlay/Overlay.jsx | 65 +- .../lib/ecomp/asdc/sequencer/model/Metamodel.js | 116 +- .../lib/ecomp/asdc/sequencer/model/Metamodels.js | 97 +- .../webapp/lib/ecomp/asdc/sequencer/model/Model.js | 864 +++++----- .../sequencer/model/demo/scenarios/Scenarios.js | 181 +- .../src/main/webapp/lib/main.jsx | 14 +- dox-sequence-diagram-ui/yarn.lock | 634 +++---- openecomp-ui/.eslintrc | 71 +- openecomp-ui/.prettierrc | 5 + openecomp-ui/package.json | 304 ++-- .../src/nfvo-components/SubmitErrorResponse.jsx | 228 +-- .../src/nfvo-components/accordion/Accordion.jsx | 63 +- .../src/nfvo-components/datepicker/Datepicker.jsx | 151 +- .../src/nfvo-components/editor/TabulatedEditor.jsx | 165 +- .../fileupload/DraggableUploadFileBox.jsx | 35 +- openecomp-ui/src/nfvo-components/grid/GridItem.jsx | 21 +- .../src/nfvo-components/grid/GridSection.jsx | 35 +- .../src/nfvo-components/input/ExpandableInput.jsx | 177 +- .../src/nfvo-components/input/SelectInput.jsx | 68 +- .../src/nfvo-components/input/ToggleInput.jsx | 93 +- .../input/dualListbox/DualListboxView.jsx | 348 ++-- .../src/nfvo-components/input/validation/Form.jsx | 272 +-- .../src/nfvo-components/input/validation/Input.jsx | 404 +++-- .../input/validation/InputOptions.jsx | 545 +++--- .../input/validation/InputWrapper.jsx | 255 +-- .../src/nfvo-components/input/validation/Tabs.jsx | 116 +- .../input/validation/ValidationButtons.jsx | 81 +- .../listEditor/ListEditorItemView.jsx | 108 +- .../listEditor/ListEditorItemViewField.jsx | 6 +- .../nfvo-components/listEditor/ListEditorView.jsx | 148 +- .../listEditor/listEditor.stories.js | 77 +- openecomp-ui/src/nfvo-components/loader/Loader.jsx | 61 +- .../src/nfvo-components/loader/LoaderConstants.js | 8 +- .../src/nfvo-components/loader/LoaderReducer.js | 85 +- .../src/nfvo-components/modal/GlobalModal.js | 280 ++-- .../nfvo-components/modal/GlobalModalConstants.js | 26 +- .../nfvo-components/modal/GlobalModalReducer.js | 58 +- openecomp-ui/src/nfvo-components/modal/Modal.jsx | 102 +- .../src/nfvo-components/overlay/Overlay.jsx | 32 +- .../nfvo-components/panel/NavigationSideBar.jsx | 219 ++- .../panel/versionController/VersionController.jsx | 323 ++-- .../VersionControllerConstants.js | 10 +- .../versionController/components/ActionButtons.jsx | 227 ++- .../components/CommitCommentModal.jsx | 87 +- .../versionController/components/Permissions.jsx | 106 +- .../nfvo-components/progressBar/ProgressBar.jsx | 33 +- .../nfvo-components/table/SelectActionTable.jsx | 75 +- .../table/SelectActionTableCell.jsx | 36 +- .../nfvo-components/table/SelectActionTableRow.jsx | 77 +- openecomp-ui/src/nfvo-components/tree/Tree.jsx | 406 +++-- .../src/nfvo-components/tree/Tree.stories.js | 242 +-- openecomp-ui/src/nfvo-utils/DirectedGraph.js | 44 +- .../src/nfvo-utils/ErrorResponseHandler.js | 103 +- openecomp-ui/src/nfvo-utils/KeyMirror.js | 43 +- openecomp-ui/src/nfvo-utils/RestAPIUtil.js | 231 +-- openecomp-ui/src/nfvo-utils/ShowFileSaveDialog.js | 69 +- openecomp-ui/src/nfvo-utils/UUID.js | 60 +- openecomp-ui/src/nfvo-utils/Validator.js | 288 ++-- openecomp-ui/src/nfvo-utils/WebSocketUtil.js | 65 +- openecomp-ui/src/nfvo-utils/getValue.js | 54 +- openecomp-ui/src/nfvo-utils/i18n/i18n.js | 132 +- openecomp-ui/src/nfvo-utils/i18n/i18n.stories.js | 64 +- openecomp-ui/src/nfvo-utils/json/JSONPointer.js | 79 +- openecomp-ui/src/nfvo-utils/json/JSONSchema.js | 489 +++--- .../src/nfvo-utils/sortByStringProperty.js | 4 +- openecomp-ui/src/sdc-app/AppStore.js | 23 +- openecomp-ui/src/sdc-app/Application.jsx | 53 +- openecomp-ui/src/sdc-app/ModulesOptions.jsx | 292 ++-- openecomp-ui/src/sdc-app/Reducers.js | 16 +- .../src/sdc-app/common/activity-log/ActivityLog.js | 30 +- .../common/activity-log/ActivityLogActionHelper.js | 13 +- .../common/activity-log/ActivityLogConstants.js | 5 +- .../common/activity-log/ActivityLogReducer.js | 10 +- .../common/activity-log/ActivityLogView.jsx | 255 +-- .../src/sdc-app/common/activity-log/LogixUtil.jsx | 52 +- .../src/sdc-app/common/helpers/ItemsHelper.js | 148 +- .../src/sdc-app/common/helpers/ScreensHelper.js | 553 ++++--- .../src/sdc-app/common/helpers/ValidationHelper.js | 135 +- .../src/sdc-app/common/merge/MergeEditor.js | 45 +- .../common/merge/MergeEditorActionHelper.js | 881 +++++----- .../sdc-app/common/merge/MergeEditorConstants.js | 375 +++-- .../src/sdc-app/common/merge/MergeEditorReducer.js | 96 +- .../src/sdc-app/common/merge/MergeEditorView.jsx | 568 ++++--- .../src/sdc-app/common/modal/ModalContentMapper.js | 66 +- .../sdc-app/common/reducers/JSONSchemaReducer.js | 288 ++-- .../common/reducers/JSONSchemaReducerConstants.js | 8 +- .../sdc-app/common/reducers/PlainDataReducer.js | 206 ++- .../common/reducers/PlainDataReducerConstants.js | 6 +- openecomp-ui/src/sdc-app/config/Configuration.js | 66 +- .../src/sdc-app/features/FeaturesActionHelper.js | 32 +- .../src/sdc-app/features/FeaturesConstants.js | 8 +- .../src/sdc-app/features/FeaturesReducer.js | 18 +- openecomp-ui/src/sdc-app/features/featureToggle.js | 47 +- openecomp-ui/src/sdc-app/features/restToggle.js | 12 +- openecomp-ui/src/sdc-app/flows/FlowsActions.js | 321 ++-- openecomp-ui/src/sdc-app/flows/FlowsConstants.js | 32 +- openecomp-ui/src/sdc-app/flows/FlowsEditorModal.js | 77 +- .../src/sdc-app/flows/FlowsEditorModalView.jsx | 101 +- openecomp-ui/src/sdc-app/flows/FlowsListEditor.js | 66 +- .../src/sdc-app/flows/FlowsListEditorView.jsx | 261 +-- openecomp-ui/src/sdc-app/flows/FlowsListReducer.js | 162 +- openecomp-ui/src/sdc-app/flows/FlowsPunchOut.jsx | 97 +- openecomp-ui/src/sdc-app/flows/FlowsReducersMap.js | 4 +- openecomp-ui/src/sdc-app/flows/ImportantLogic.jsx | 58 +- openecomp-ui/src/sdc-app/flows/SequenceDiagram.jsx | 54 +- .../sdc-app/flows/SequenceDiagramModelHelper.js | 77 +- openecomp-ui/src/sdc-app/heatValidation.app.jsx | 8 +- .../src/sdc-app/heatvalidation/Attachments.js | 59 +- .../src/sdc-app/heatvalidation/HeatSetup.js | 28 +- .../src/sdc-app/heatvalidation/UploadScreen.jsx | 19 +- .../heatvalidation/UploadScreenActionHelper.js | 290 ++-- .../src/sdc-app/onboarding/GridStyling.stories.js | 342 ++-- openecomp-ui/src/sdc-app/onboarding/Onboarding.js | 4 +- .../sdc-app/onboarding/OnboardingActionHelper.js | 842 +++++++--- .../src/sdc-app/onboarding/OnboardingConstants.js | 153 +- .../src/sdc-app/onboarding/OnboardingPunchOut.jsx | 1250 +++++++++----- .../src/sdc-app/onboarding/OnboardingReducers.js | 273 ++-- .../sdc-app/onboarding/OnboardingReducersMap.js | 30 +- .../src/sdc-app/onboarding/OnboardingView.jsx | 361 ++-- .../ArchivedLicenseModelListReducer.js | 14 +- .../FinalizedLicenseModelListReducer.js | 14 +- .../onboarding/licenseModel/LicenseModel.js | 329 ++-- .../licenseModel/LicenseModelActionHelper.js | 392 +++-- .../licenseModel/LicenseModelConstants.js | 27 +- .../licenseModel/LicenseModelEditorReducer.js | 20 +- .../licenseModel/LicenseModelListReducer.js | 14 +- .../onboarding/licenseModel/LicenseModelReducer.js | 117 +- .../licenseModel/LicenseModelValidations.js | 42 +- .../licenseModel/creation/LicenseModelCreation.js | 98 +- .../creation/LicenseModelCreationActionHelper.js | 81 +- .../creation/LicenseModelCreationConstants.js | 6 +- .../creation/LicenseModelCreationReducer.js | 61 +- .../creation/LicenseModelCreationView.jsx | 164 +- .../EntitlementPoolsActionHelper.js | 410 +++-- .../entitlementPools/EntitlementPoolsConstants.js | 162 +- .../entitlementPools/EntitlementPoolsEditor.js | 100 +- .../EntitlementPoolsEditorReducer.js | 172 +- .../EntitlementPoolsEditorView.jsx | 730 +++++---- .../entitlementPools/EntitlementPoolsLimits.js | 92 +- .../entitlementPools/EntitlementPoolsListEditor.js | 83 +- .../EntitlementPoolsListEditorView.jsx | 244 +-- .../EntitlementPoolsListReducer.js | 38 +- .../featureGroups/FeatureGroupEditor.js | 124 +- .../featureGroups/FeatureGroupEditorView.jsx | 483 +++--- .../featureGroups/FeatureGroupListEditor.js | 90 +- .../featureGroups/FeatureGroupListEditorView.jsx | 313 ++-- .../featureGroups/FeatureGroupsActionHelper.js | 270 +-- .../featureGroups/FeatureGroupsConstants.js | 32 +- .../featureGroups/FeatureGroupsEditorReducer.js | 133 +- .../featureGroups/FeatureGroupsListReducer.js | 36 +- .../LicenseAgreementActionHelper.js | 228 ++- .../licenseAgreement/LicenseAgreementConstants.js | 61 +- .../licenseAgreement/LicenseAgreementEditor.js | 127 +- .../LicenseAgreementEditorReducer.js | 117 +- .../LicenseAgreementEditorView.jsx | 404 +++-- .../licenseAgreement/LicenseAgreementListEditor.js | 82 +- .../LicenseAgreementListEditorView.jsx | 230 +-- .../LicenseAgreementListReducer.js | 21 +- .../LicenseKeyGroupsActionHelper.js | 387 +++-- .../licenseKeyGroups/LicenseKeyGroupsConstants.js | 117 +- .../licenseKeyGroups/LicenseKeyGroupsEditor.js | 100 +- .../LicenseKeyGroupsEditorReducer.js | 165 +- .../LicenseKeyGroupsEditorView.jsx | 772 +++++---- .../licenseKeyGroups/LicenseKeyGroupsLimits.js | 92 +- .../licenseKeyGroups/LicenseKeyGroupsListEditor.js | 77 +- .../LicenseKeyGroupsListEditorView.jsx | 326 ++-- .../LicenseKeyGroupsListReducer.js | 39 +- .../onboarding/licenseModel/limits/LimitEditor.js | 39 +- .../onboarding/licenseModel/limits/LimitEditor.jsx | 517 +++--- .../licenseModel/limits/LimitEditorActionHelper.js | 68 +- .../licenseModel/limits/LimitEditorConstants.js | 89 +- .../licenseModel/limits/LimitEditorReducer.js | 119 +- .../onboarding/licenseModel/limits/Limits.jsx | 222 ++- .../onboarding/licenseModel/limits/LimitsServer.js | 46 +- .../licenseModel/overview/LicenseModelOverview.js | 349 ++-- .../overview/LicenseModelOverviewConstants.js | 24 +- .../overview/LicenseModelOverviewView.jsx | 194 ++- .../licenseModel/overview/SummaryView.jsx | 30 +- .../licenseModel/overview/VLMListView.jsx | 202 +-- .../overview/licenseModelOverviewActionHelper.js | 38 +- .../overview/listItems/EntitlementPool.jsx | 55 +- .../overview/listItems/FeatureGroup.jsx | 108 +- .../overview/listItems/LicenseAgreement.jsx | 89 +- .../overview/listItems/LicenseKeyGroup.jsx | 65 +- .../listItemsComponents/AdditionalDataCol.jsx | 46 +- .../listItems/listItemsComponents/ArrowCol.jsx | 26 +- .../listItems/listItemsComponents/IconCol.jsx | 14 +- .../listItems/listItemsComponents/ItemInfo.jsx | 34 +- .../summary/LicenseModelDescriptionEdit.jsx | 80 +- .../licenseModel/overview/summary/ListButtons.jsx | 50 +- .../overview/summary/SummaryCountItem.jsx | 50 +- .../overview/summary/SummaryCountList.js | 227 +-- .../overview/summary/VendorDataView.js | 196 ++- .../onboarding/onboard/CatalogItemDetails.jsx | 137 +- .../onboard/CatalogItemDetails.stories.js | 55 +- .../src/sdc-app/onboarding/onboard/CatalogList.jsx | 78 +- .../sdc-app/onboarding/onboard/CatalogModal.jsx | 75 +- .../onboarding/onboard/DetailsCatalogView.jsx | 88 +- .../src/sdc-app/onboarding/onboard/Onboard.js | 184 ++- .../onboarding/onboard/OnboardActionHelper.js | 219 ++- .../sdc-app/onboarding/onboard/OnboardConstants.js | 12 +- .../sdc-app/onboarding/onboard/OnboardReducer.js | 26 +- .../src/sdc-app/onboarding/onboard/OnboardView.jsx | 150 +- .../sdc-app/onboarding/onboard/filter/Filter.jsx | 205 ++- .../onboarding/onboard/filter/FilterConstants.js | 8 +- .../onboarding/onboard/filter/FilterReducer.js | 22 +- .../OnboardingCatalogActionHelper.js | 131 +- .../OnboardingCatalogConstants.js | 38 +- .../onboardingCatalog/OnboardingCatalogReducer.js | 19 +- .../onboardingCatalog/OnboardingCatalogUtils.js | 6 +- .../onboardingCatalog/OnboardingCatalogView.jsx | 274 ++-- .../onboard/onboardingCatalog/Tooltip.jsx | 24 +- .../onboard/onboardingCatalog/VSPOverlay.jsx | 68 +- .../onboardingCatalog/VendorCatalogReducer.js | 40 +- .../onboardingCatalog/VendorCatalogView.jsx | 134 +- .../onboard/onboardingCatalog/VendorItem.jsx | 158 +- .../onboarding/onboard/workspace/WorkspaceView.jsx | 58 +- .../permissions/PermissionsActionHelper.js | 170 +- .../onboarding/permissions/PermissionsConstants.js | 9 +- .../onboarding/permissions/PermissionsManager.js | 61 +- .../onboarding/permissions/PermissionsManager.jsx | 221 ++- .../onboarding/permissions/PermissionsReducer.js | 22 +- .../src/sdc-app/onboarding/revisions/Revisions.js | 35 +- .../onboarding/revisions/RevisionsActionHelper.js | 128 +- .../onboarding/revisions/RevisionsConstants.js | 2 +- .../onboarding/revisions/RevisionsReducer.js | 16 +- .../sdc-app/onboarding/revisions/RevisionsView.jsx | 160 +- .../ArchivedSoftwareProductReducer.js | 14 +- .../FinalizedSoftwareProductReducer.js | 14 +- .../onboarding/softwareProduct/SoftwareProduct.js | 947 +++++++---- .../softwareProduct/SoftwareProductActionHelper.js | 1174 +++++++------ .../SoftwareProductCategoriesHelper.js | 30 +- .../softwareProduct/SoftwareProductConstants.js | 49 +- .../softwareProduct/SoftwareProductListReducer.js | 26 +- .../softwareProduct/SoftwareProductReducer.js | 176 +- .../attachments/SoftwareProductAttachments.js | 206 ++- .../SoftwareProductAttachmentsActionHelper.js | 14 +- .../SoftwareProductAttachmentsConstants.js | 6 +- .../SoftwareProductAttachmentsReducer.js | 14 +- .../attachments/SoftwareProductAttachmentsUtils.js | 14 +- .../attachments/SoftwareProductAttachmentsView.jsx | 312 ++-- .../softwareProduct/attachments/setup/HeatSetup.js | 81 +- .../attachments/setup/HeatSetupActionHelper.js | 92 +- .../attachments/setup/HeatSetupConstants.js | 32 +- .../attachments/setup/HeatSetupReducer.js | 239 +-- .../attachments/setup/HeatSetupView.jsx | 713 +++++--- .../attachments/validation/HeatValidation.js | 74 +- .../validation/HeatValidationActionHelper.js | 37 +- .../validation/HeatValidationConstants.js | 55 +- .../validation/HeatValidationReducer.js | 371 +++-- .../attachments/validation/HeatValidationView.jsx | 542 +++--- .../SoftwareProductComponentEditorReducer.js | 150 +- .../components/SoftwareProductComponents.js | 93 +- .../SoftwareProductComponentsActionHelper.js | 360 ++-- .../SoftwareProductComponentsConstants.js | 50 +- .../SoftwareProductComponentsListReducer.js | 32 +- .../SoftwareProductComponentsListView.jsx | 168 +- .../compute/ComputeFlavorActionHelper.js | 362 ++-- .../compute/SoftwareProductComponentCompute.js | 74 +- .../SoftwareProductComponentComputeView.jsx | 144 +- .../compute/computeComponents/ComputeFlavors.js | 218 ++- .../compute/computeComponents/GuestOs.jsx | 136 +- .../compute/computeComponents/NumberOfVms.jsx | 97 +- .../computeFlavor/ComputeFlavorConstants.js | 20 +- .../computeFlavor/ComputeFlavorEditor.js | 99 +- .../computeFlavor/ComputeFlavorEditorView.jsx | 169 +- .../computeFlavor/ComputeFlavorListReducer.js | 36 +- .../computeFlavor/ComputeFlavorReducer.js | 53 +- .../computeComponents/computeFlavor/VmSizing.jsx | 223 ++- .../creation/SoftwareProductComponentCreation.js | 64 +- .../SoftwareProductComponentCreationView.jsx | 121 +- .../general/SoftwareProductComponentsGeneral.js | 92 +- .../SoftwareProductComponentsGeneralView.jsx | 572 ++++--- .../components/images/ImageValidations.js | 6 +- .../SoftwareProductComponentsImageActionHelper.js | 375 +++-- .../SoftwareProductComponentsImageConstants.js | 10 +- .../images/SoftwareProductComponentsImageEditor.js | 119 +- .../SoftwareProductComponentsImageEditorReducer.js | 47 +- .../SoftwareProductComponentsImageEditorView.jsx | 116 +- .../images/SoftwareProductComponentsImageList.js | 161 +- .../SoftwareProductComponentsImageListReducer.js | 15 +- .../SoftwareProductComponentsImageListView.jsx | 237 +-- .../images/imagesEditorComponents/FileDetails.jsx | 78 +- .../images/imagesEditorComponents/Format.jsx | 54 +- .../images/imagesEditorComponents/ImageDetails.jsx | 33 +- .../images/imagesEditorComponents/Version.jsx | 42 +- .../SoftwareProductComponentLoadBalancing.js | 55 +- ...oftwareProductComponentLoadBalancingRefView.jsx | 359 ++-- .../SoftwareProductComponentsMonitoring.js | 79 +- ...twareProductComponentsMonitoringActionHelper.js | 115 +- ...SoftwareProductComponentsMonitoringConstants.js | 27 +- .../SoftwareProductComponentsMonitoringReducer.js | 37 +- .../SoftwareProductComponentsMonitoringView.jsx | 232 +-- .../components/network/NICCreation/NICCreation.js | 66 +- .../network/NICCreation/NICCreationActionHelper.js | 54 +- .../network/NICCreation/NICCreationReducer.js | 65 +- .../network/NICCreation/NICCreationView.jsx | 217 +-- .../network/SoftwareProductComponentsNICEditor.js | 125 +- .../SoftwareProductComponentsNICEditorReducer.js | 62 +- .../SoftwareProductComponentsNICEditorView.jsx | 147 +- .../SoftwareProductComponentsNICListReducer.js | 26 +- ...SoftwareProductComponentsNetworkActionHelper.js | 300 ++-- .../SoftwareProductComponentsNetworkConstants.js | 26 +- .../SoftwareProductComponentsNetworkList.js | 179 +- .../SoftwareProductComponentsNetworkListView.jsx | 313 ++-- .../network/nicEditorComponents/Acceptable.jsx | 142 +- .../network/nicEditorComponents/FlowLength.jsx | 22 +- .../network/nicEditorComponents/InFlowTraffic.jsx | 22 +- .../network/nicEditorComponents/IpConfig.jsx | 52 +- .../network/nicEditorComponents/NameAndPurpose.jsx | 70 +- .../network/nicEditorComponents/Network.jsx | 110 +- .../network/nicEditorComponents/OutFlowTraffic.jsx | 22 +- .../network/nicEditorComponents/PacketsBytes.jsx | 93 +- .../network/nicEditorComponents/Protocols.jsx | 120 +- .../network/nicEditorComponents/Sizing.jsx | 41 +- ...oftwareProductComponentProcessesActionHelper.js | 263 +-- .../SoftwareProductComponentProcessesConstants.js | 27 +- .../SoftwareProductComponentProcessesEditor.js | 86 +- ...ftwareProductComponentProcessesEditorReducer.js | 78 +- ...SoftwareProductComponentProcessesEditorView.jsx | 17 +- .../SoftwareProductComponentProcessesList.js | 83 +- ...SoftwareProductComponentProcessesListReducer.js | 34 +- .../SoftwareProductComponentsProcessesListView.jsx | 110 +- .../storage/SoftwareProductComponentStorage.js | 59 +- .../SoftwareProductComponentStorageView.jsx | 450 +++-- .../creation/SoftwareProductCreation.js | 126 +- .../SoftwareProductCreationActionHelper.js | 98 +- .../creation/SoftwareProductCreationConstants.js | 6 +- .../creation/SoftwareProductCreationReducer.js | 114 +- .../creation/SoftwareProductCreationView.jsx | 468 ++++-- .../dependencies/SoftwareProductDependencies.js | 51 +- .../SoftwareProductDependenciesActionHelper.js | 130 +- .../SoftwareProductDependenciesConstants.js | 12 +- .../SoftwareProductDependenciesReducer.js | 68 +- .../SoftwareProductDependenciesUtils.js | 108 +- .../SoftwareProductDependenciesView.jsx | 292 ++-- .../deployment/SoftwareProductDeployment.js | 85 +- .../SoftwareProductDeploymentActionHelper.js | 232 ++- .../SoftwareProductDeploymentConstants.js | 12 +- .../SoftwareProductDeploymentListReducer.js | 14 +- .../deployment/SoftwareProductDeploymentView.jsx | 136 +- .../editor/SoftwareProductDeploymentEditor.js | 144 +- .../SoftwareProductDeploymentEditorReducer.js | 57 +- .../editor/SoftwareProductDeploymentEditorView.jsx | 351 ++-- .../details/SoftwareProductDetails.js | 190 ++- .../details/SoftwareProductDetailsReducer.js | 93 +- .../SoftwareProductDetailsVendorSelector.jsx | 122 +- .../details/SoftwareProductDetailsView.jsx | 993 ++++++----- .../landingPage/SoftwareProductLandingPage.js | 204 ++- .../landingPage/SoftwareProductLandingPageView.jsx | 396 +++-- .../networks/SoftwareProductNetworks.js | 13 +- .../SoftwareProductNetworksActionHelper.js | 29 +- .../networks/SoftwareProductNetworksConstants.js | 2 +- .../networks/SoftwareProductNetworksListReducer.js | 14 +- .../networks/SoftwareProductNetworksView.jsx | 125 +- .../processes/SoftwareProductProcessListView.jsx | 140 +- .../processes/SoftwareProductProcesses.js | 71 +- .../SoftwareProductProcessesActionHelper.js | 218 +-- .../processes/SoftwareProductProcessesConstants.js | 22 +- .../processes/SoftwareProductProcessesEditor.js | 73 +- .../SoftwareProductProcessesEditorForm.jsx | 341 ++-- .../SoftwareProductProcessesEditorReducer.js | 78 +- .../SoftwareProductProcessesEditorView.jsx | 16 +- .../SoftwareProductProcessesListReducer.js | 34 +- .../processes/SoftwareProductProcessesView.jsx | 88 +- .../userNotifications/NotificationsReducer.js | 113 +- .../userNotifications/NotificationsView.jsx | 202 ++- .../userNotifications/UserNotifications.jsx | 283 ++-- .../UserNotificationsActionHelper.js | 230 ++- .../UserNotificationsConstants.js | 31 +- .../sdc-app/onboarding/users/UsersActionHelper.js | 53 +- .../src/sdc-app/onboarding/users/UsersConstants.js | 4 +- .../src/sdc-app/onboarding/users/UsersReducers.js | 41 +- .../onboarding/versionsPage/VersionsPage.js | 134 +- .../onboarding/versionsPage/VersionsPage.jsx | 201 ++- .../versionsPage/VersionsPageActionHelper.js | 156 +- .../versionsPage/VersionsPageConstants.js | 10 +- .../onboarding/versionsPage/VersionsPageReducer.js | 44 +- .../versionsPage/components/PermissionsView.jsx | 141 +- .../versionsPage/components/VersionList.jsx | 251 +-- .../versionsPage/creation/VersionsPageCreation.js | 58 +- .../creation/VersionsPageCreationActionHelper.js | 109 +- .../creation/VersionsPageCreationConstants.js | 10 +- .../creation/VersionsPageCreationReducer.js | 59 +- .../creation/VersionsPageCreationView.jsx | 215 ++- openecomp-ui/src/sdc-app/sdc.app.jsx | 19 +- openecomp-ui/webpack.common.js | 102 +- openecomp-ui/webpack.production.js | 89 +- openecomp-ui/yarn.lock | 690 +++++--- 414 files changed, 38166 insertions(+), 27110 deletions(-) create mode 100644 dox-sequence-diagram-ui/.prettierrc create mode 100644 openecomp-ui/.prettierrc diff --git a/dox-sequence-diagram-ui/.prettierrc b/dox-sequence-diagram-ui/.prettierrc new file mode 100644 index 0000000000..40321d4ab2 --- /dev/null +++ b/dox-sequence-diagram-ui/.prettierrc @@ -0,0 +1,5 @@ +{ + "singleQuote": true, + "jsxBracketSameLine": true, + "tabWidth": 4 +} \ No newline at end of file diff --git a/dox-sequence-diagram-ui/eslintrc.json b/dox-sequence-diagram-ui/eslintrc.json index b2a3f24aaa..01b65f3845 100644 --- a/dox-sequence-diagram-ui/eslintrc.json +++ b/dox-sequence-diagram-ui/eslintrc.json @@ -1,32 +1,110 @@ { - "parserOptions": { - "ecmaVersion": 6, - "sourceType": "module", - "ecmaFeatures": { - "jsx": true + "parser": "babel-eslint", + "parserOptions": { + "ecmaVersion": 6, + "sourceType": "module", + "ecmaFeatures": { + "jsx": true, + "classes": true, + "modules": true, + "experimentalDecorators": true + } + }, + "env": { + "es6": true, + "jquery": true, + "node": true, + "jest": true + }, + "plugins": ["react", "import", "prettier"], + "extends": ["prettier"], + "globals": { + "Event": true, + "window": true, + "navigator": true, + "System": true, + "document": true, + "localStorage": true, + "sessionStorage": true, + "Image": true, + "requestAnimationFrame": true, + "cancelAnimationFrame": true, + "DEBUG": true, + "SVGElement": true, + "FormData": true, + "DEV": true, + "Blob": true, + "XMLHttpRequest": true, + "WebSocket": true, + "URL": true, + "PunchOutRegistry": true, + "it": true, + "describe": true + }, + "rules": { + "prettier/prettier": [ + "error", + { + "singleQuote": true, + "jsxBracketSameLine": true, + "tabWidth": 4 + } + ], + "linebreak-style": 0, + "no-unused-vars": 2, + "no-bitwise": 0, + "no-eq-null": 2, + "eqeqeq": 2, + "no-unused-expressions": 2, + "no-use-before-define": 2, + "new-cap": [ + 2, + { + "capIsNewExceptions": ["DataTable", "V"] + } + ], + "no-caller": 2, + "no-empty": 2, + "no-undef": 2, + "quotes": [2, "single", "avoid-escape"], + "no-plusplus": 0, + "no-cond-assign": [2, "except-parens"], + "no-invalid-this": 0, + "dot-notation": 0, + "camelcase": [ + 2, + { + "properties": "never" + } + ], + "curly": 2, + "semi": [2, "always"], + "import/default": 0, + "import/no-unresolved": 0, + "import/no-named-as-default": 2, + "import/no-duplicates": 0, + "import/imports-first": 2, + "import/export": 2, + "react/display-name": 0, + "react/forbid-prop-types": 0, + "react/jsx-boolean-value": 0, + "react/jsx-no-duplicate-props": 1, + "react/jsx-no-literals": 0, + "react/jsx-no-undef": 1, + "react/jsx-sort-prop-types": 0, + "react/jsx-sort-props": 0, + "react/jsx-uses-react": 1, + "react/jsx-uses-vars": 1, + "react/no-danger": 1, + "react/no-did-mount-set-state": 2, + "react/no-did-update-set-state": 2, + "react/no-direct-mutation-state": 1, + "react/no-multi-comp": 0, + "react/no-set-state": 0, + "react/no-unknown-property": 1, + "react/prop-types": 0, + "react/react-in-jsx-scope": 1, + "react/self-closing-comp": 1, + "react/sort-comp": 0 } - }, - "env": { - "browser": true - }, - "plugins": [ - "react" - ], - "extends": [ - "airbnb" - ], - "rules": { - "padded-blocks": 0, - "max-len": ["error", 160, 4], - "no-underscore-dangle": 0, - "global-require": 0, - "react/sort-comp": 0, - "new-cap": 0 - }, - "settings": { - "react": { - "pragma": "React", - "version": "0.14.8" - } - } } diff --git a/dox-sequence-diagram-ui/package.json b/dox-sequence-diagram-ui/package.json index aa9976e31e..dbbfd8465f 100644 --- a/dox-sequence-diagram-ui/package.json +++ b/dox-sequence-diagram-ui/package.json @@ -1,57 +1,59 @@ { - "name": "dox-sequence-diagram-ui", - "version": "1.0.0", - "description": "", - "main": "dist/index.js", - "scripts": { - "build": "webpack", - "start": "webpack-dev-server", - "lint": "eslint . --ext .js --ext .jsx --cache" - }, - "author": "ONAP", - "license": "SEE LICENSE IN LICENSE", - "dependencies": { - "d3": "^4.10.0", - "lodash": "^4.12.0", - "prop-types": "^15.6.0", - "react": "^15.6.2", - "react-dnd": "^2.5.4", - "react-dnd-html5-backend": "^2.5.4", - "react-dom": "^15.6.2", - "react-redux": "^5.0.6", - "react-select": "1.2.1", - "redux": "^3.7.2" - }, - "devDependencies": { - "babel-core": "^6.26.0", - "babel-eslint": "^8.2.1", - "babel-loader": "^7.1.2", - "babel-plugin-lodash": "^3.3.2", - "babel-preset-env": "^1.6.1", - "babel-preset-react": "^6.5.0", - "copy": "^0.2.0", - "css-loader": "^0.28.7", - "eslint": "^2.10.2", - "eslint-config-airbnb": "^9.0.1", - "eslint-loader": "^1.3.0", - "eslint-plugin-import": "^1.8.0", - "eslint-plugin-jsx-a11y": "^1.2.2", - "eslint-plugin-react": "^5.1.1", - "file-loader": "^1.1.6", - "node-sass": "^4.7.2", - "path": "^0.12.7", - "raw-loader": "^0.5.1", - "redux-devtools": "^3.3.1", - "sass-loader": "^6.0.6", - "style-loader": "^0.19.1", - "svg-sprite-loader": "0.0.19", - "url-loader": "^0.6.2", - "webpack": "^2.2.1", - "webpack-dev-server": "^2.4.2" - }, - "engines": { - "node": ">=8.0.0", - "npm": ">=5.0.0", - "yarn": "^1.3.2" - } -} \ No newline at end of file + "name": "dox-sequence-diagram-ui", + "version": "1.0.0", + "description": "", + "main": "dist/index.js", + "scripts": { + "build": "webpack", + "start": "webpack-dev-server", + "lint": "eslint . --ext .js --ext .jsx --cache -c eslintrc.json", + "lint-fix": "eslint --fix -c eslintrc.json --ext .js --ext .jsx src" + }, + "author": "ONAP", + "license": "SEE LICENSE IN LICENSE", + "dependencies": { + "d3": "^4.10.0", + "lodash": "^4.12.0", + "prop-types": "^15.6.0", + "react": "^15.6.2", + "react-dnd": "^2.5.4", + "react-dnd-html5-backend": "^2.5.4", + "react-dom": "^15.6.2", + "react-redux": "^5.0.6", + "react-select": "1.2.1", + "redux": "^3.7.2" + }, + "devDependencies": { + "babel-core": "^6.26.0", + "babel-eslint": "^8.2.1", + "babel-loader": "^7.1.2", + "babel-plugin-lodash": "^3.3.2", + "babel-preset-env": "^1.6.1", + "babel-preset-react": "^6.5.0", + "copy": "^0.2.0", + "css-loader": "^0.28.7", + "eslint": "^4.18.1", + "eslint-config-prettier": "^2.9.0", + "eslint-loader": "^1.9.0", + "eslint-plugin-import": "^2.9.0", + "eslint-plugin-prettier": "^2.6.0", + "eslint-plugin-react": "^7.7.0", + "file-loader": "^1.1.6", + "node-sass": "^4.7.2", + "path": "^0.12.7", + "prettier": "^1.10.2", + "raw-loader": "^0.5.1", + "redux-devtools": "^3.3.1", + "sass-loader": "^6.0.6", + "style-loader": "^0.19.1", + "svg-sprite-loader": "0.0.19", + "url-loader": "^0.6.2", + "webpack": "^2.2.1", + "webpack-dev-server": "^2.4.2" + }, + "engines": { + "node": ">=8.0.0", + "npm": ">=5.0.0", + "yarn": "^1.3.2" + } +} diff --git a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/Sequencer.jsx b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/Sequencer.jsx index fc2bfbc0e3..c0e9483e92 100644 --- a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/Sequencer.jsx +++ b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/Sequencer.jsx @@ -28,176 +28,177 @@ import '../../../../res/sdc-sequencer.scss'; * ASDC Sequencer entry point. */ class Sequencer extends React.Component { + // ////////////////////////////////////////////////////////////////////////////////////////////// - // ////////////////////////////////////////////////////////////////////////////////////////////// - - constructor(props, context) { - super(props, context); - - - this.setMetamodel.bind(this); - this.setModel.bind(this); - this.getModel.bind(this); - this.getMetamodel.bind(this); - this.getSVG.bind(this); - this.getDemoScenarios.bind(this); - this.newModel.bind(this); - - // Parse options. - - this.options = new Options(props.options); - - // Default scenarios. - - const scenarios = this.getDemoScenarios(); - this.setMetamodel(scenarios.getMetamodels()); - - // this.setModel(scenarios.getBlank()); - this.setModel(scenarios.getDimensions()); - // this.setModel(scenarios.getECOMP()); - - } - - // ////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Optionally save known metamodels so that subsequent loading and unloading - * of models needn't include the corresponding metamodel. - * @param metamodels array of conformant metamodel JSON definitions. - * @return this. - */ - setMetamodel(metamodels) { - Common.assertType(metamodels, 'Array'); - this.metamodels = new Metamodels(metamodels); - return this; - } - - // ////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Set current diagram. - * @param modelJSON JSON diagram spec. - * @param metamodelIdOrDefinition optional metamodel definition or reference. Defaults to - * the model's metadata @ref, or the default (permissive) metamodel. - * @return this. - */ - setModel(modelJSON, metamodelIdOrDefinition) { - Common.assertType(modelJSON, 'Object'); - const ref = (modelJSON.metadata) ? modelJSON.metadata.ref : undefined; - const metamodel = this.getMetamodel(metamodelIdOrDefinition || ref); - Common.assertInstanceOf(metamodel, Metamodel); - this.model = new Model(modelJSON, metamodel); - if (this.application) { - this.application.setModel(this.model); + constructor(props, context) { + super(props, context); + + this.setMetamodel.bind(this); + this.setModel.bind(this); + this.getModel.bind(this); + this.getMetamodel.bind(this); + this.getSVG.bind(this); + this.getDemoScenarios.bind(this); + this.newModel.bind(this); + + // Parse options. + + this.options = new Options(props.options); + + // Default scenarios. + + const scenarios = this.getDemoScenarios(); + this.setMetamodel(scenarios.getMetamodels()); + + // this.setModel(scenarios.getBlank()); + this.setModel(scenarios.getDimensions()); + // this.setModel(scenarios.getECOMP()); } - return this; - } - - // ////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get current diagram state. At any given instant the diagram might not make *sense* - * but it should always be syntactically valid. - * @return current Model. - */ - getModel() { - - if (this.application) { - const model = this.application.getModel(); - if (model) { - return model.unwrap(); - } + + // ////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Optionally save known metamodels so that subsequent loading and unloading + * of models needn't include the corresponding metamodel. + * @param metamodels array of conformant metamodel JSON definitions. + * @return this. + */ + setMetamodel(metamodels) { + Common.assertType(metamodels, 'Array'); + this.metamodels = new Metamodels(metamodels); + return this; } - return this.model; - } - - // ////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Extract SVG element. - * @return stringified SVG element. - */ - getSVG() { - return this.application.getSVG(); - } - - // ////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get demo scenarios, allowing initialization in demo mode from the outside. - * @returns {Scenarios} - */ - getDemoScenarios() { - return new Scenarios(); - } - - // ////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Create new model. - * @param metamodelIdOrDefinition - * @return newly-created model. - */ - newModel(metamodelIdOrDefinition) { - const metamodel = this.getMetamodel(metamodelIdOrDefinition); - Common.assertInstanceOf(metamodel, Metamodel); - const model = new Model({}, metamodel); - if (this.application) { - this.application.setModel(model); + // ////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Set current diagram. + * @param modelJSON JSON diagram spec. + * @param metamodelIdOrDefinition optional metamodel definition or reference. Defaults to + * the model's metadata @ref, or the default (permissive) metamodel. + * @return this. + */ + setModel(modelJSON, metamodelIdOrDefinition) { + Common.assertType(modelJSON, 'Object'); + const ref = modelJSON.metadata ? modelJSON.metadata.ref : undefined; + const metamodel = this.getMetamodel(metamodelIdOrDefinition || ref); + Common.assertInstanceOf(metamodel, Metamodel); + this.model = new Model(modelJSON, metamodel); + if (this.application) { + this.application.setModel(this.model); + } + return this; } - return model; - } - - // ////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get Metamodel instance corresponding to an ID or JSON definition. - * @param metamodelIdOrDefinition String ID or JSON definition. - * @returns Metamodel instance. - * @private - */ - getMetamodel(metamodelIdOrDefinition) { - const metamodelType = Common.getType(metamodelIdOrDefinition); - if (metamodelType === 'Object') { - return new Metamodel(metamodelIdOrDefinition); + + // ////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Get current diagram state. At any given instant the diagram might not make *sense* + * but it should always be syntactically valid. + * @return current Model. + */ + getModel() { + if (this.application) { + const model = this.application.getModel(); + if (model) { + return model.unwrap(); + } + } + + return this.model; } - return this.metamodels.getMetamodelOrDefault(metamodelIdOrDefinition); - } - // ////////////////////////////////////////////////////////////////////////////////////////////// + // ////////////////////////////////////////////////////////////////////////////////////////////// - /** - * Render current diagram state. - */ - render() { + /** + * Extract SVG element. + * @return stringified SVG element. + */ + getSVG() { + return this.application.getSVG(); + } - if (this.props.model) { + // ////////////////////////////////////////////////////////////////////////////////////////////// - // If a model was specified as a property, apply it. Otherwise - // fall back to the demo model. + /** + * Get demo scenarios, allowing initialization in demo mode from the outside. + * @returns {Scenarios} + */ + getDemoScenarios() { + return new Scenarios(); + } - const scenarios = this.getDemoScenarios(); - const metamodel = [scenarios.getBlankMetamodel(), scenarios.getECOMPMetamodel()]; - if (this.props.metamodel) { - metamodel.push(this.props.metamodel); - } - this.setMetamodel(metamodel); - this.setModel(this.props.model); + // ////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Create new model. + * @param metamodelIdOrDefinition + * @return newly-created model. + */ + newModel(metamodelIdOrDefinition) { + const metamodel = this.getMetamodel(metamodelIdOrDefinition); + Common.assertInstanceOf(metamodel, Metamodel); + const model = new Model({}, metamodel); + if (this.application) { + this.application.setModel(model); + } + return model; } - return ( - { this.application = a; }} /> - ); - } + // ////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Get Metamodel instance corresponding to an ID or JSON definition. + * @param metamodelIdOrDefinition String ID or JSON definition. + * @returns Metamodel instance. + * @private + */ + getMetamodel(metamodelIdOrDefinition) { + const metamodelType = Common.getType(metamodelIdOrDefinition); + if (metamodelType === 'Object') { + return new Metamodel(metamodelIdOrDefinition); + } + return this.metamodels.getMetamodelOrDefault(metamodelIdOrDefinition); + } + // ////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Render current diagram state. + */ + render() { + if (this.props.model) { + // If a model was specified as a property, apply it. Otherwise + // fall back to the demo model. + + const scenarios = this.getDemoScenarios(); + const metamodel = [ + scenarios.getBlankMetamodel(), + scenarios.getECOMPMetamodel() + ]; + if (this.props.metamodel) { + metamodel.push(this.props.metamodel); + } + this.setMetamodel(metamodel); + this.setModel(this.props.model); + } + + return ( + { + this.application = a; + }} + /> + ); + } } Sequencer.propTypes = { - options: PropTypes.object.isRequired, - model: PropTypes.object, - metamodel: PropTypes.object, + options: PropTypes.object.isRequired, + model: PropTypes.object, + metamodel: PropTypes.object }; - export default Sequencer; diff --git a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Common.js b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Common.js index 7337367dca..1c6bd69dc2 100644 --- a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Common.js +++ b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Common.js @@ -18,339 +18,347 @@ * Common operations. */ export default class Common { + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Retrieve and start a simple timer. Retrieve elapsed time by calling #ms(). + * @returns {*} + */ + static timer() { + const start = new Date().getTime(); + return { + ms() { + return new Date().getTime() - start; + } + }; + } - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Retrieve and start a simple timer. Retrieve elapsed time by calling #ms(). - * @returns {*} - */ - static timer() { - const start = new Date().getTime(); - return { - ms() { - return (new Date().getTime() - start); - }, - }; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get datatype, stripping '[object Boolean]' to just 'Boolean'. - * @param o JS object. - * @return String like String, Number, Date, Null, Undefined, stuff like that. - */ - static getType(o) { - const str = Object.prototype.toString.call(o); - const prefix = '[object '; - if (str.substr(str, prefix.length) === prefix) { - return str.substr(prefix.length, str.length - (prefix.length + 1)); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Get datatype, stripping '[object Boolean]' to just 'Boolean'. + * @param o JS object. + * @return String like String, Number, Date, Null, Undefined, stuff like that. + */ + static getType(o) { + const str = Object.prototype.toString.call(o); + const prefix = '[object '; + if (str.substr(str, prefix.length) === prefix) { + return str.substr(prefix.length, str.length - (prefix.length + 1)); + } + return str; } - return str; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Assert that an argument was provided. - * @param value to be checked. - * @param message message on assertion failure. - * @return value. - */ - static assertNotNull(value, message = 'Unexpected null value') { - if (!value) { - throw new Error(message); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Assert that an argument was provided. + * @param value to be checked. + * @param message message on assertion failure. + * @return value. + */ + static assertNotNull(value, message = 'Unexpected null value') { + if (!value) { + throw new Error(message); + } + return value; } - return value; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Assert argument type. - * @param value to be checked. - * @param expected expected type string, e,g. Number from [object Number]. - * @return value. - */ - static assertType(value, expected) { - const type = this.getType(value); - if (type !== expected) { - throw new Error(`Expected type ${expected}, got ${type}`); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Assert argument type. + * @param value to be checked. + * @param expected expected type string, e,g. Number from [object Number]. + * @return value. + */ + static assertType(value, expected) { + const type = this.getType(value); + if (type !== expected) { + throw new Error(`Expected type ${expected}, got ${type}`); + } + return value; } - return value; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Assert argument type. - * @param value to be checked. - * @param unexpected unexpected type string, e,g. Number from [object Number]. - * @return value. - */ - static assertNotType(value, unexpected) { - const type = this.getType(value); - if (type === unexpected) { - throw new Error(`Forbidden type "${unexpected}"`); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Assert argument type. + * @param value to be checked. + * @param unexpected unexpected type string, e,g. Number from [object Number]. + * @return value. + */ + static assertNotType(value, unexpected) { + const type = this.getType(value); + if (type === unexpected) { + throw new Error(`Forbidden type "${unexpected}"`); + } + return value; } - return value; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Assert argument is a simple JSON object, and specifically not (something like an) ES6 class. - * @param value to be checked. - * @return value. - */ - static assertPlainObject(value) { - Common.assertType(value, 'Object'); - // TODO - /* + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Assert argument is a simple JSON object, and specifically not (something like an) ES6 class. + * @param value to be checked. + * @return value. + */ + static assertPlainObject(value) { + Common.assertType(value, 'Object'); + // TODO + /* if (!($.isPlainObject(value))) { throw new Error(`Expected plain object: ${value}`); } */ - return value; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Assert argument type. - * @param value to be checked. - * @param c expected class. - * @return value. - */ - static assertInstanceOf(value, c) { - Common.assertNotNull(value); - if (!(value instanceof c)) { - throw new Error(`Expected instanceof ${c}: ${value}`); - } - return value; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Assert that a string matches a regex. - * @param value value to be tested. - * @param re pattern to be applied. - * @return value. - */ - static assertMatches(value, re) { - this.assertType(value, 'String'); - this.assertType(re, 'RegExp'); - if (!re.test(value)) { - throw new Error(`Value ${value} doesn't match pattern ${re}`); + return value; } - return value; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Assert the value of a boolean. - * - * @param bool to be checked. - * @param message optional message on assertion failure. - * @return value. - */ - static assertThat(bool, message) { - if (!bool) { - throw new Error(message || `Unexpected: ${bool}`); - } - return bool; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Verify that a value, generally a function arg, is a DOM element. - * @param value to be checked. - * @return value. - */ - static assertHTMLElement(value) { - if (!Common.isHTMLElement(value)) { - throw new Error(`Expected HTMLElement: ${value}`); - } - return value; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Check whether a value, generally a function arg, is an HTML DOM element. - * @param o to be checked. - * @return true if DOM element. - */ - static isHTMLElement(o) { - if (typeof HTMLElement === 'object') { - return o instanceof HTMLElement; + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Assert argument type. + * @param value to be checked. + * @param c expected class. + * @return value. + */ + static assertInstanceOf(value, c) { + Common.assertNotNull(value); + if (!(value instanceof c)) { + throw new Error(`Expected instanceof ${c}: ${value}`); + } + return value; } - return o && typeof o === 'object' && o !== null - && o.nodeType === 1 && typeof o.nodeName === 'string'; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Check if a string is non-empty. - * @param s string to be checked. - * @returns false if non-blank string, true otherwise. - */ - static isBlank(s) { - if (Common.getType(s) === 'String') { - return (s.trim().length === 0); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Assert that a string matches a regex. + * @param value value to be tested. + * @param re pattern to be applied. + * @return value. + */ + static assertMatches(value, re) { + this.assertType(value, 'String'); + this.assertType(re, 'RegExp'); + if (!re.test(value)) { + throw new Error(`Value ${value} doesn't match pattern ${re}`); + } + return value; } - return true; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Detect dates that are numbers, milli/seconds since epoch.. - * - * @param n candidate number. - * @returns {boolean} - */ - static isNumber(n) { - return !isNaN(parseFloat(n)) && isFinite(n); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Parse the text output from a template to a DOM element. - * @param txt input text. - * @returns {Element} - */ - static txt2dom(txt) { - return new DOMParser().parseFromString(txt, 'image/svg+xml').documentElement; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Recursively convert a DOM element to an SVG (namespaced) element. Otherwise - * you get HTML elements that *happen* to have SVG names, but which aren't actually SVG. - * - * @param node DOM node to be converted. - * @param svg to be updated. - * @returns {*} for chaining. - */ - static dom2svg(node, svg) { - - Common.assertNotType(node, 'String'); - - if (node.childNodes && node.childNodes.length > 0) { - - for (const c of node.childNodes) { - switch (c.nodeType) { - case document.TEXT_NODE: - svg.text(c.nodeValue); - break; - default: - break; + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Assert the value of a boolean. + * + * @param bool to be checked. + * @param message optional message on assertion failure. + * @return value. + */ + static assertThat(bool, message) { + if (!bool) { + throw new Error(message || `Unexpected: ${bool}`); } - } - - for (const c of node.childNodes) { - switch (c.nodeType) { - case document.ELEMENT_NODE: - Common.dom2svg(c, svg.append(`svg:${c.nodeName.toLowerCase()}`)); - break; - default: - break; + return bool; + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Verify that a value, generally a function arg, is a DOM element. + * @param value to be checked. + * @return value. + */ + static assertHTMLElement(value) { + if (!Common.isHTMLElement(value)) { + throw new Error(`Expected HTMLElement: ${value}`); } - } + return value; } - if (node.hasAttributes()) { - for (let i = 0; i < node.attributes.length; i++) { - const a = node.attributes.item(i); - svg.attr(a.name, a.value); - } + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Check whether a value, generally a function arg, is an HTML DOM element. + * @param o to be checked. + * @return true if DOM element. + */ + static isHTMLElement(o) { + /* eslint-disable no-undef */ + if (typeof HTMLElement === 'object') { + return o instanceof HTMLElement; + } + /* eslint-enable no-undef */ + return ( + o && + typeof o === 'object' && + o !== null && + o.nodeType === 1 && + typeof o.nodeName === 'string' + ); } - return svg; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get the lines to be shown in the label. - * - * @param labelText original label text. - * @param wordWrapAt chars at which to break words. - * @param lineWrapAt chars at which to wrap. - * @param maximumLines lines at which to truncate. - * @returns {Array} - */ - static tokenize(labelText = '', wordWrapAt, lineWrapAt, maximumLines) { - - let l = labelText; - - // Hyphenate and break long words. - - const regex = new RegExp(`(\\w{${wordWrapAt - 1}})(?=\\w)`, 'g'); - l = l.replace(regex, '$1- '); - - const labelTokens = l.split(/\s+/); - const lines = []; - let label = ''; - for (const labelToken of labelTokens) { - if (label.length > 0) { - const length = label.length + labelToken.length + 1; - if (length > lineWrapAt) { - lines.push(label.trim()); - label = labelToken; - continue; + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Check if a string is non-empty. + * @param s string to be checked. + * @returns false if non-blank string, true otherwise. + */ + static isBlank(s) { + if (Common.getType(s) === 'String') { + return s.trim().length === 0; } - } - label = `${label} ${labelToken}`; + return true; } - if (label) { - lines.push(label.trim()); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Detect dates that are numbers, milli/seconds since epoch.. + * + * @param n candidate number. + * @returns {boolean} + */ + static isNumber(n) { + return !isNaN(parseFloat(n)) && isFinite(n); } - const truncated = lines.slice(0, maximumLines); - if (truncated.length < lines.length) { - let finalLine = truncated[maximumLines - 1]; - if (finalLine.length > (lineWrapAt - 4)) { - finalLine = finalLine.substring(0, lineWrapAt - 4); - } - finalLine = `${finalLine} ...`; - truncated[maximumLines - 1] = finalLine; + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Parse the text output from a template to a DOM element. + * @param txt input text. + * @returns {Element} + */ + static txt2dom(txt) { + /* eslint-disable no-undef */ + return new DOMParser().parseFromString(txt, 'image/svg+xml') + .documentElement; + /* eslint-enable no-undef */ } - return truncated; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Brutally sanitize an input string. We have no syntax rules, and hence no specific - * rules to apply, but we have very few unconstrained fields, so we can implement a - * crude default and devolve the rest to options. - * @param value value to be sanitized. - * @param options control options including validation rules. - * @param type validation type. - * @returns {*} sanitized string. - * @private - */ - static sanitizeText(value, options, type) { - const rules = Common.assertNotNull(options.validation[type]); - let v = value || rules.defaultValue || ''; - if (rules.replace) { - v = v.replace(rules.replace, ''); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Recursively convert a DOM element to an SVG (namespaced) element. Otherwise + * you get HTML elements that *happen* to have SVG names, but which aren't actually SVG. + * + * @param node DOM node to be converted. + * @param svg to be updated. + * @returns {*} for chaining. + */ + static dom2svg(node, svg) { + Common.assertNotType(node, 'String'); + + if (node.childNodes && node.childNodes.length > 0) { + for (const c of node.childNodes) { + switch (c.nodeType) { + case document.TEXT_NODE: + svg.text(c.nodeValue); + break; + default: + break; + } + } + + for (const c of node.childNodes) { + switch (c.nodeType) { + case document.ELEMENT_NODE: + Common.dom2svg( + c, + svg.append(`svg:${c.nodeName.toLowerCase()}`) + ); + break; + default: + break; + } + } + } + + if (node.hasAttributes()) { + for (let i = 0; i < node.attributes.length; i++) { + const a = node.attributes.item(i); + svg.attr(a.name, a.value); + } + } + + return svg; } - if (v.length > rules.maxLength) { - v = `${v.substring(0, rules.maxLength)}...`; + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Get the lines to be shown in the label. + * + * @param labelText original label text. + * @param wordWrapAt chars at which to break words. + * @param lineWrapAt chars at which to wrap. + * @param maximumLines lines at which to truncate. + * @returns {Array} + */ + static tokenize(labelText = '', wordWrapAt, lineWrapAt, maximumLines) { + let l = labelText; + + // Hyphenate and break long words. + + const regex = new RegExp(`(\\w{${wordWrapAt - 1}})(?=\\w)`, 'g'); + l = l.replace(regex, '$1- '); + + const labelTokens = l.split(/\s+/); + const lines = []; + let label = ''; + for (const labelToken of labelTokens) { + if (label.length > 0) { + const length = label.length + labelToken.length + 1; + if (length > lineWrapAt) { + lines.push(label.trim()); + label = labelToken; + continue; + } + } + label = `${label} ${labelToken}`; + } + + if (label) { + lines.push(label.trim()); + } + + const truncated = lines.slice(0, maximumLines); + if (truncated.length < lines.length) { + let finalLine = truncated[maximumLines - 1]; + if (finalLine.length > lineWrapAt - 4) { + finalLine = finalLine.substring(0, lineWrapAt - 4); + } + finalLine = `${finalLine} ...`; + truncated[maximumLines - 1] = finalLine; + } + + return truncated; } - return v; - } + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Brutally sanitize an input string. We have no syntax rules, and hence no specific + * rules to apply, but we have very few unconstrained fields, so we can implement a + * crude default and devolve the rest to options. + * @param value value to be sanitized. + * @param options control options including validation rules. + * @param type validation type. + * @returns {*} sanitized string. + * @private + */ + static sanitizeText(value, options, type) { + const rules = Common.assertNotNull(options.validation[type]); + let v = value || rules.defaultValue || ''; + if (rules.replace) { + v = v.replace(rules.replace, ''); + } + if (v.length > rules.maxLength) { + v = `${v.substring(0, rules.maxLength)}...`; + } + return v; + } } diff --git a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Logger.js b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Logger.js index 187f49bb08..8b6ae67ca7 100644 --- a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Logger.js +++ b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Logger.js @@ -23,108 +23,107 @@ import Common from './Common'; * disable them for production. */ export default class Logger { + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * No-op call so that we can leave imports in place, + * even when there's no debugging. + */ + static noop() { + // Nothing. + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Set debug level. + * @param level threshold. + */ + static setLevel(level) { + this.level = Logger.OFF; + if (Common.getType(level) === 'Number') { + this.level = level; + } else { + this.level = Logger[level]; + } + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Get debug level. + * @returns {number|*} + */ + static getLevel() { + return this.level; + } - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * No-op call so that we can leave imports in place, - * even when there's no debugging. - */ - static noop() { - // Nothing. - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Set debug level. - * @param level threshold. - */ - static setLevel(level) { - this.level = Logger.OFF; - if (Common.getType(level) === 'Number') { - this.level = level; - } else { - this.level = Logger[level]; + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Write DEBUG-level log. + * @param msg message or tokens. + */ + static debug(...msg) { + if (this.level >= Logger.DEBUG) { + const out = this.serialize(msg); + console.info(`ASDCS [DEBUG] ${out}`); + } } - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get debug level. - * @returns {number|*} - */ - static getLevel() { - return this.level; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Write DEBUG-level log. - * @param msg message or tokens. - */ - static debug(...msg) { - if (this.level >= Logger.DEBUG) { - const out = this.serialize(msg); - console.info(`ASDCS [DEBUG] ${out}`); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Write INFO-level log. + * @param msg message or tokens. + */ + static info(...msg) { + if (this.level >= Logger.INFO) { + const out = this.serialize(msg); + console.info(`ASDCS [INFO] ${out}`); + } } - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Write INFO-level log. - * @param msg message or tokens. - */ - static info(...msg) { - if (this.level >= Logger.INFO) { - const out = this.serialize(msg); - console.info(`ASDCS [INFO] ${out}`); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Write debug. + * @param msg message or tokens. + */ + static warn(msg) { + if (this.level >= Logger.WARN) { + const out = this.serialize(msg); + console.warn(`ASDCS [WARN] ${out}`); + } } - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Write debug. - * @param msg message or tokens. - */ - static warn(msg) { - if (this.level >= Logger.WARN) { - const out = this.serialize(msg); - console.warn(`ASDCS [WARN] ${out}`); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Write error. + * @param msg message or tokens. + */ + static error(...msg) { + if (this.level >= Logger.ERROR) { + const out = this.serialize(msg); + console.error(`ASDCS [ERROR] ${out}`); + } } - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Write error. - * @param msg message or tokens. - */ - static error(...msg) { - if (this.level >= Logger.ERROR) { - const out = this.serialize(msg); - console.error(`ASDCS [ERROR] ${out}`); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Serialize msg. + * @param msg message or tokens. + * @returns {string} + */ + static serialize(...msg) { + let out = ''; + msg.forEach(token => { + out = `${out}${token}`; + }); + return out; } - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Serialize msg. - * @param msg message or tokens. - * @returns {string} - */ - static serialize(...msg) { - let out = ''; - msg.forEach((token) => { - out = `${out}${token}`; - }); - return out; - } } // ///////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Options.js b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Options.js index 15897d7ee3..b054cb26e7 100644 --- a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Options.js +++ b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/common/Options.js @@ -23,26 +23,25 @@ import Logger from './Logger'; * and the result -- runtime options -- are available by calling #getOptions(). */ export default class Options { + // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// + /** + * Construct options, applying defaults. + * @param options optional override options. + */ + constructor(options = {}) { + this.options = _merge({}, Options.DEFAULTS, options); + } - /** - * Construct options, applying defaults. - * @param options optional override options. - */ - constructor(options = {}) { - this.options = _merge({}, Options.DEFAULTS, options); - } + // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Unwrap options. - * @returns {*} - */ - unwrap() { - return this.options; - } + /** + * Unwrap options. + * @returns {*} + */ + unwrap() { + return this.options; + } } // ///////////////////////////////////////////////////////////////////////////////////////////////// @@ -51,86 +50,86 @@ export default class Options { * Default options, overridden by anything of the same name. */ Options.DEFAULTS = { - log: { - level: Logger.WARN, - }, - demo: false, - useHtmlSelect: true, - diagram: { - svg: { - x: 0, - y: 0, - width: 1600, - height: 1200, - margin: 50, - floodColor: '#009fdb', - scale: { - height: true, - width: true, - minimum: 0.25, - }, - }, - title: { - height: 0, - }, - metadata: false, - lifelines: { - header: { - height: 225, - width: 350, - wrapWords: 14, - wrapLines: 18, - maxLines: 5, - }, - occurrences: { - marginTop: 50, - marginBottom: 75, - foreshortening: 5, - width: 50, - }, - spacing: { - horizontal: 400, - vertical: 400, - }, - }, - messages: { - label: { - wrapWords: 14, - wrapLines: 18, - maxLines: 4, - }, - }, - fragments: { - leftMargin: 150, - topMargin: 200, - widthMargin: 300, - heightMargin: 350, - label: { - wrapWords: 50, - wrapLines: 50, - maxLines: 2, - }, - }, - }, - validation: { - lifeline: { - maxLength: 100, - defaultValue: '', - replace: /[^\-\.\+ &%#@\?\(\)\[\]<>\w\d]/g, - }, - message: { - maxLength: 100, - defaultValue: '', - replace: /[^\-\.\+ &%#@\?\(\)\[\]<>\w\d]/g, - }, - notes: { - maxLength: 255, - defaultValue: '', + log: { + level: Logger.WARN }, - guard: { - maxLength: 80, - defaultValue: '', - replace: /[^\-\.\+ &%#@\?\(\)\[\]<>\w\d]/g, + demo: false, + useHtmlSelect: true, + diagram: { + svg: { + x: 0, + y: 0, + width: 1600, + height: 1200, + margin: 50, + floodColor: '#009fdb', + scale: { + height: true, + width: true, + minimum: 0.25 + } + }, + title: { + height: 0 + }, + metadata: false, + lifelines: { + header: { + height: 225, + width: 350, + wrapWords: 14, + wrapLines: 18, + maxLines: 5 + }, + occurrences: { + marginTop: 50, + marginBottom: 75, + foreshortening: 5, + width: 50 + }, + spacing: { + horizontal: 400, + vertical: 400 + } + }, + messages: { + label: { + wrapWords: 14, + wrapLines: 18, + maxLines: 4 + } + }, + fragments: { + leftMargin: 150, + topMargin: 200, + widthMargin: 300, + heightMargin: 350, + label: { + wrapWords: 50, + wrapLines: 50, + maxLines: 2 + } + } }, - }, + validation: { + lifeline: { + maxLength: 100, + defaultValue: '', + replace: /[^\-\.\+ &%#@\?\(\)\[\]<>\w\d]/g + }, + message: { + maxLength: 100, + defaultValue: '', + replace: /[^\-\.\+ &%#@\?\(\)\[\]<>\w\d]/g + }, + notes: { + maxLength: 255, + defaultValue: '' + }, + guard: { + maxLength: 80, + defaultValue: '', + replace: /[^\-\.\+ &%#@\?\(\)\[\]<>\w\d]/g + } + } }; diff --git a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/application/Application.jsx b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/application/Application.jsx index 6889e0ab9f..b63e69a4ed 100644 --- a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/application/Application.jsx +++ b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/application/Application.jsx @@ -28,258 +28,274 @@ import Overlay from '../overlay/Overlay'; * Application controller, also a view. */ class Application extends React.Component { + /** + * Construct application view. + * @param props element properties. + * @param context react context. + */ + constructor(props, context) { + super(props, context); + + this.sequencer = Common.assertNotNull(props.sequencer); + this.model = this.sequencer.getModel(); + this.metamodel = this.sequencer.getMetamodel(); + this.options = props.options; + Logger.setLevel(this.options.unwrap().log.level); + + // Bindings. + + this.showInfoDialog = this.showInfoDialog.bind(this); + this.showEditDialog = this.showEditDialog.bind(this); + this.showConfirmDialog = this.showConfirmDialog.bind(this); + this.hideOverlay = this.hideOverlay.bind(this); + this.onMouseMove = this.onMouseMove.bind(this); + this.onMouseUp = this.onMouseUp.bind(this); + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// - /** - * Construct application view. - * @param props element properties. - * @param context react context. - */ - constructor(props, context) { - super(props, context); - - this.sequencer = Common.assertNotNull(props.sequencer); - this.model = this.sequencer.getModel(); - this.metamodel = this.sequencer.getMetamodel(); - this.options = props.options; - Logger.setLevel(this.options.unwrap().log.level); - - // Bindings. - - this.showInfoDialog = this.showInfoDialog.bind(this); - this.showEditDialog = this.showEditDialog.bind(this); - this.showConfirmDialog = this.showConfirmDialog.bind(this); - this.hideOverlay = this.hideOverlay.bind(this); - this.onMouseMove = this.onMouseMove.bind(this); - this.onMouseUp = this.onMouseUp.bind(this); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get application options. - * @returns JSON options, see Options.js. - */ - getOptions() { - return this.options.unwrap(); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Set diagram name. - * @param n diagram (human-readable) name. - */ - setName(n) { - this.diagram.setName(n); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Set diagram model. - * @param model diagram instance. - */ - setModel(model) { - - Common.assertNotNull(model); - - this.model = model; - - if (this.editor) { - this.editor.render(); + /** + * Get application options. + * @returns JSON options, see Options.js. + */ + getOptions() { + return this.options.unwrap(); } - if (this.diagram) { - this.diagram.render(); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Set diagram name. + * @param n diagram (human-readable) name. + */ + setName(n) { + this.diagram.setName(n); } - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get Model wrapper. - * @returns Model. - */ - getModel() { - return this.model; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get SVG element. - * @returns {*} - */ - getSVG() { - return this.diagram.getSVG(); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get top-level widget. Provides the demo toolbar with access to the public API. - * @returns {*} - */ - getSequencer() { - return this.sequencer; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Present info dialog. - * @param msg info message. - */ - showInfoDialog(msg) { - this.dialog.showInfoDialog(msg); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Present error dialog. - * @param msg error message. - */ - showErrorDialog(msg) { - this.dialog.showErrorDialog(msg); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Present confirmation dialog. - * @param msg info message. - * @param cb callback function to be invoked on OK. - */ - showConfirmDialog(msg, cb) { - Common.assertType(cb, 'Function'); - this.dialog.showConfirmDialog(msg, cb); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Present edit (textarea) dialog. - * @param msg prompt. - * @param text current edit text. - * @param cb callback function to be invoked on OK, taking the updated text - * as an argument. - */ - showEditDialog(msg, text, cb) { - this.dialog.showEditDialog(msg, text, cb); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Select lifeline by ID. - * @param id lifeline ID. - */ - selectLifeline(id) { - if (this.editor) { - this.editor.selectLifeline(id); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Set diagram model. + * @param model diagram instance. + */ + setModel(model) { + Common.assertNotNull(model); + + this.model = model; + + if (this.editor) { + this.editor.render(); + } + + if (this.diagram) { + this.diagram.render(); + } } - if (this.diagram) { - this.diagram.selectLifeline(id); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Get Model wrapper. + * @returns Model. + */ + getModel() { + return this.model; } - } - // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// - /** - * Select message by ID. - * @param id message ID. - */ - selectMessage(id) { - if (this.editor) { - this.editor.selectMessage(id); + /** + * Get SVG element. + * @returns {*} + */ + getSVG() { + return this.diagram.getSVG(); } - if (this.diagram) { - this.diagram.selectMessage(id); + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Get top-level widget. Provides the demo toolbar with access to the public API. + * @returns {*} + */ + getSequencer() { + return this.sequencer; } - } - // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// - /** - * (Re)render just the diagram. - */ - renderDiagram() { - this.diagram.redraw(); - } + /** + * Present info dialog. + * @param msg info message. + */ + showInfoDialog(msg) { + this.dialog.showInfoDialog(msg); + } - // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// - /** - * Show overlay between application and modal dialog. - */ - showOverlay() { - if (this.overlay) { - this.overlay.setVisible(true); + /** + * Present error dialog. + * @param msg error message. + */ + showErrorDialog(msg) { + this.dialog.showErrorDialog(msg); } - } - // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Present confirmation dialog. + * @param msg info message. + * @param cb callback function to be invoked on OK. + */ + showConfirmDialog(msg, cb) { + Common.assertType(cb, 'Function'); + this.dialog.showConfirmDialog(msg, cb); + } - /** - * Hide overlay between application and modal dialog. - */ - hideOverlay() { - if (this.overlay) { - this.overlay.setVisible(false); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Present edit (textarea) dialog. + * @param msg prompt. + * @param text current edit text. + * @param cb callback function to be invoked on OK, taking the updated text + * as an argument. + */ + showEditDialog(msg, text, cb) { + this.dialog.showEditDialog(msg, text, cb); } - } - // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Select lifeline by ID. + * @param id lifeline ID. + */ + selectLifeline(id) { + if (this.editor) { + this.editor.selectLifeline(id); + } + if (this.diagram) { + this.diagram.selectLifeline(id); + } + } - /** - * Capture mouse move events, for resize. - * @param event move event. - */ - onMouseMove(event) { - if (this.editor) { - this.editor.onMouseMove(event); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Select message by ID. + * @param id message ID. + */ + selectMessage(id) { + if (this.editor) { + this.editor.selectMessage(id); + } + if (this.diagram) { + this.diagram.selectMessage(id); + } } - } - // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// - /** - * Propagate mouse event to the editor that manages the resize. - */ - onMouseUp() { - if (this.editor) { - this.editor.onMouseUp(); + /** + * (Re)render just the diagram. + */ + renderDiagram() { + this.diagram.redraw(); } - } - // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// - /** - * Render current model state. - */ - render() { + /** + * Show overlay between application and modal dialog. + */ + showOverlay() { + if (this.overlay) { + this.overlay.setVisible(true); + } + } - return ( + // /////////////////////////////////////////////////////////////////////////////////////////////// -
+ /** + * Hide overlay between application and modal dialog. + */ + hideOverlay() { + if (this.overlay) { + this.overlay.setVisible(false); + } + } - { this.editor = r; }} /> - { this.diagram = r; }} /> - { this.dialog = r; }} /> - - { this.overlay = r; }} /> + // /////////////////////////////////////////////////////////////////////////////////////////////// -
- ); - } + /** + * Capture mouse move events, for resize. + * @param event move event. + */ + onMouseMove(event) { + if (this.editor) { + this.editor.onMouseMove(event); + } + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + /** + * Propagate mouse event to the editor that manages the resize. + */ + onMouseUp() { + if (this.editor) { + this.editor.onMouseUp(); + } + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Render current model state. + */ + render() { + return ( +
+ { + this.editor = r; + }} + /> + { + this.diagram = r; + }} + /> + { + this.dialog = r; + }} + /> + + { + this.overlay = r; + }} + /> +
+ ); + } } /** React properties. */ Application.propTypes = { - options: PropTypes.object.isRequired, - sequencer: PropTypes.object.isRequired, + options: PropTypes.object.isRequired, + sequencer: PropTypes.object.isRequired }; export default Application; diff --git a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/diagram/Diagram.jsx b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/diagram/Diagram.jsx index b3544d7066..129a1afc2b 100644 --- a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/diagram/Diagram.jsx +++ b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/diagram/Diagram.jsx @@ -28,898 +28,1013 @@ import Popup from './components/popup/Popup'; * SVG diagram view. */ class Diagram extends React.Component { - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Construct React view. - * @param props properties. - * @param context context. - */ - constructor(props, context) { - super(props, context); - - this.application = Common.assertNotNull(props.application); - this.options = this.application.getOptions().diagram; - - this.events = {}; - this.state = { - height: 0, - width: 0, - }; - - this.templates = { - diagram: _template(require('./templates/diagram.html')), - lifeline: _template(require('./templates/lifeline.html')), - message: _template(require('./templates/message.html')), - occurrence: _template(require('./templates/occurrence.html')), - fragment: _template(require('./templates/fragment.html')), - title: _template(require('./templates/title.html')), - }; - - this.handleResize = this.handleResize.bind(this); - this.initialTransformX = 0; - this.initialTransformY = 0; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Set diagram name. - * @param n name. - */ - setName(n) { - this.svg.select('').text(n); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get SVG from diagram. - * @returns {*|string} - */ - getSVG() { - const svg = this.svg.node().outerHTML; - return svg.replace(' 0) ? `height:${titleHeight}` : 'asdcs-hidden'; - - return ( -
-
{name}
-
{ this.wrapper = r; }}>
- { this.popup = r; }} /> -
- ); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - redraw() { - this.updateSVG(); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Initial render. - */ - componentDidMount() { - window.addEventListener('resize', this.handleResize); - this.updateSVG(); - - // Insurance: - - setTimeout(() => { - this.handleResize(); - }, 500); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - componentWillUnmount() { - window.removeEventListener('resize', this.handleResize); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Render on update. - */ - componentDidUpdate() { - this.updateSVG(); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Redraw SVG diagram. So far it's fast enough that it doesn't seem to matter whether - * it's completely redrawn. - */ - updateSVG() { - - if (!this.svg) { - const svgparams = _merge({}, this.options.svg); - this.wrapper.innerHTML = this.templates.diagram(svgparams); - this.svg = d3.select(this.wrapper).select('svg'); - } - - if (this.state.height === 0) { - - // We'll get a resize event, and the height will be non-zero when it's actually time. - return; - } + // /////////////////////////////////////////////////////////////////////////////////////////////// - if (this.state.height && this.state.width) { - const margin = this.options.svg.margin; - const x = -margin; - const y = -margin; - const height = this.state.height + (margin * 2); - const width = this.state.width + (margin * 2); - const viewBox = `${x} ${y} ${width} ${height}`; - this.svg.attr('viewBox', viewBox); + /** + * Set diagram name. + * @param n name. + */ + setName(n) { + this.svg.select('').text(n); } + // /////////////////////////////////////////////////////////////////////////////////////////////// - // If we've already rendered, then save the current scale/translate so that we - // can reapply it after rendering. - - const gContentSelection = this.svg.selectAll('g.asdcs-diagram-content'); - if (gContentSelection.size() === 1) { - const transform = gContentSelection.attr('transform'); - if (transform) { - this.savedTransform = transform; - } + /** + * Get SVG from diagram. + * @returns {*|string} + */ + getSVG() { + const svg = this.svg.node().outerHTML; + return svg.replace(' 0 + ? `height:${titleHeight}` + : 'asdcs-hidden'; + + return ( +
+
{name}
+
{ + this.wrapper = r; + }} + /> + { + this.popup = r; + }} + /> +
+ ); + } - const header = this.options.lifelines.header; - const spacing = this.options.lifelines.spacing; + // /////////////////////////////////////////////////////////////////////////////////////////////// - // Make separate container elements so that we can control Z order. + redraw() { + this.updateSVG(); + } - const gContent = this.svg.append('g').attr('class', 'asdcs-diagram-content'); - const gLifelines = gContent.append('g').attr('class', 'asdcs-diagram-lifelines'); - const gCanvas = gContent.append('g').attr('class', 'asdcs-diagram-canvas'); - gCanvas.append('g').attr('class', 'asdcs-diagram-occurrences'); - gCanvas.append('g').attr('class', 'asdcs-diagram-fragments'); - gCanvas.append('g').attr('class', 'asdcs-diagram-messages'); + // /////////////////////////////////////////////////////////////////////////////////////////////// - // Lifelines ----------------------------------------------------------------------------------- + /** + * Initial render. + */ + componentDidMount() { + window.addEventListener('resize', this.handleResize); + this.updateSVG(); - const actorsById = {}; - const positionsByMessageId = {}; - const lifelines = []; - for (const actor of modelJSON.diagram.lifelines) { - const x = (header.width / 2) + (lifelines.length * spacing.horizontal); - Diagram._processLifeline(actor, x); - lifelines.push({ x, actor }); - actorsById[actor.id] = actor; - } + // Insurance: - // Messages ------------------------------------------------------------------------------------ - - // Analyze occurrence information. - - const occurrences = model.analyzeOccurrences(); - const fragments = model.analyzeFragments(); - let y = this.options.lifelines.header.height + spacing.vertical; - let messageIndex = 0; - for (const step of modelJSON.diagram.steps) { - if (step.message) { - positionsByMessageId[step.message.id] = positionsByMessageId[step.message.id] || {}; - positionsByMessageId[step.message.id].y = y; - this._drawMessage(gCanvas, step.message, y, actorsById, - positionsByMessageId, ++messageIndex, occurrences, fragments); - } - y += spacing.vertical; + setTimeout(() => { + this.handleResize(); + }, 500); } - // --------------------------------------------------------------------------------------------- - - // Draw the actual (dashed) lifelines in a background . - - this._drawLifelines(gLifelines, lifelines, y); - - // Initialize mouse event handlers. - - this._initMouseEvents(gLifelines, gCanvas); - - // Scale to fit. - - const bb = gContent.node().getBBox(); - this._initZoom(gContent, bb.width, bb.height); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Draw message into SVG canvas. - * @param gCanvas container. - * @param message message to be rendered. - * @param y current y position. - * @param actorsById actor lookup. - * @param positionsByMessageId x- and y-position of each message. - * @param messageIndex where we are in the set of messages to be rendered. - * @param oData occurrences info. - * @param fData fragments info. - * @private - */ - _drawMessage(gCanvas, message, y, actorsById, positionsByMessageId, - messageIndex, oData, fData) { - - Common.assertNotNull(oData); - - const request = message.type === 'request'; - const fromActor = request ? actorsById[message.from] : actorsById[message.to]; - const toActor = request ? actorsById[message.to] : actorsById[message.from]; - - if (!fromActor) { - Logger.warn(`Cannot draw message ${JSON.stringify(message)}: 'from' not found.`); - return; - } + // /////////////////////////////////////////////////////////////////////////////////////////////// - if (!toActor) { - Logger.warn(`Cannot draw message ${JSON.stringify(message)}: 'to' not found.`); - return; + componentWillUnmount() { + window.removeEventListener('resize', this.handleResize); } - // Occurrences. -------------------------------------------------------------------------------- + // /////////////////////////////////////////////////////////////////////////////////////////////// - if (message.occurrence) { - Logger.debug(`Found occurrence for ${message.name}: ${JSON.stringify(message.occurrence)}`); + /** + * Render on update. + */ + componentDidUpdate() { + this.updateSVG(); } - const activeTo = Diagram._calcActive(oData, toActor.id); - this._drawOccurrence(gCanvas, oData, positionsByMessageId, fromActor, message.id); - this._drawOccurrence(gCanvas, oData, positionsByMessageId, toActor, message.id); - const activeFrom = Diagram._calcActive(oData, fromActor.id); - - // Messages. ----------------------------------------------------------------------------------- - - const gMessages = gCanvas.select('g.asdcs-diagram-messages'); - - // Save positions for later. - - const positions = positionsByMessageId[message.id]; - positions.x0 = fromActor.x; - positions.x1 = toActor.x; - - // Calculate. - const leftToRight = fromActor.x < toActor.x; - const loopback = (message.to === message.from); - const x1 = this._calcMessageX(activeTo, toActor.x, true, leftToRight); - const x0 = loopback ? x1 : this._calcMessageX(activeFrom, fromActor.x, false, leftToRight); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Redraw SVG diagram. So far it's fast enough that it doesn't seem to matter whether + * it's completely redrawn. + */ + updateSVG() { + if (!this.svg) { + const svgparams = _merge({}, this.options.svg); + this.wrapper.innerHTML = this.templates.diagram(svgparams); + this.svg = d3.select(this.wrapper).select('svg'); + } - let messagePath; - if (loopback) { + if (this.state.height === 0) { + // We'll get a resize event, and the height will be non-zero when it's actually time. - // To self. + return; + } - messagePath = `M${x1},${y}`; - messagePath = `${messagePath} L${x1 + 200},${y}`; - messagePath = `${messagePath} L${x1 + 200},${y + 50}`; - messagePath = `${messagePath} L${x1},${y + 50}`; - } else { + if (this.state.height && this.state.width) { + const margin = this.options.svg.margin; + const x = -margin; + const y = -margin; + const height = this.state.height + margin * 2; + const width = this.state.width + margin * 2; + const viewBox = `${x} ${y} ${width} ${height}`; + this.svg.attr('viewBox', viewBox); + } - // Between lifelines. + // If we've already rendered, then save the current scale/translate so that we + // can reapply it after rendering. - messagePath = `M${x0},${y}`; - messagePath = `${messagePath} L${x1},${y}`; - } + const gContentSelection = this.svg.selectAll('g.asdcs-diagram-content'); + if (gContentSelection.size() === 1) { + const transform = gContentSelection.attr('transform'); + if (transform) { + this.savedTransform = transform; + } + } - const styles = Diagram._getMessageStyles(message); + // Empty the document. We're starting again. - // Split message over lines. + this.svg.selectAll('.asdcs-diagram-content').remove(); - const messageWithPrefix = `${messageIndex}. ${message.name}`; - const maxLines = this.options.messages.label.maxLines; - const wrapWords = this.options.messages.label.wrapWords; - const wrapLines = this.options.messages.label.wrapLines; - const messageLines = Common.tokenize(messageWithPrefix, wrapWords, wrapLines, maxLines); + // Extract the model. - const messageTxt = this.templates.message({ - id: message.id, - classes: styles.css, - marker: styles.marker, - dasharray: styles.dasharray, - labels: messageLines, - lines: maxLines, - path: messagePath, - index: messageIndex, - x0, x1, y, - }); + const model = this.application.getModel(); + if (!model) { + return; + } + const modelJSON = model.unwrap(); + + // Extract dimension options. + + const header = this.options.lifelines.header; + const spacing = this.options.lifelines.spacing; + + // Make separate container elements so that we can control Z order. + + const gContent = this.svg + .append('g') + .attr('class', 'asdcs-diagram-content'); + const gLifelines = gContent + .append('g') + .attr('class', 'asdcs-diagram-lifelines'); + const gCanvas = gContent + .append('g') + .attr('class', 'asdcs-diagram-canvas'); + gCanvas.append('g').attr('class', 'asdcs-diagram-occurrences'); + gCanvas.append('g').attr('class', 'asdcs-diagram-fragments'); + gCanvas.append('g').attr('class', 'asdcs-diagram-messages'); + + // Lifelines ----------------------------------------------------------------------------------- + + const actorsById = {}; + const positionsByMessageId = {}; + const lifelines = []; + for (const actor of modelJSON.diagram.lifelines) { + const x = header.width / 2 + lifelines.length * spacing.horizontal; + Diagram._processLifeline(actor, x); + lifelines.push({ x, actor }); + actorsById[actor.id] = actor; + } - const messageEl = Common.txt2dom(messageTxt); - const gMessage = gMessages.append('g'); - Common.dom2svg(messageEl, gMessage); + // Messages ------------------------------------------------------------------------------------ + + // Analyze occurrence information. + + const occurrences = model.analyzeOccurrences(); + const fragments = model.analyzeFragments(); + let y = this.options.lifelines.header.height + spacing.vertical; + let messageIndex = 0; + for (const step of modelJSON.diagram.steps) { + if (step.message) { + positionsByMessageId[step.message.id] = + positionsByMessageId[step.message.id] || {}; + positionsByMessageId[step.message.id].y = y; + this._drawMessage( + gCanvas, + step.message, + y, + actorsById, + positionsByMessageId, + ++messageIndex, + occurrences, + fragments + ); + } + y += spacing.vertical; + } - // Set the background's bounding box to that of the text, - // so that they fit snugly. + // --------------------------------------------------------------------------------------------- - const labelBB = gMessage.select('.asdcs-diagram-message-label').node().getBBox(); - gMessage.select('.asdcs-diagram-message-label-bg') - .attr('x', labelBB.x) - .attr('y', labelBB.y) - .attr('height', labelBB.height) - .attr('width', labelBB.width); + // Draw the actual (dashed) lifelines in a background . - // Fragments. ---------------------------------------------------------------------------------- + this._drawLifelines(gLifelines, lifelines, y); - const fragment = fData[message.id]; - if (fragment) { + // Initialize mouse event handlers. - // It ends on this message. + this._initMouseEvents(gLifelines, gCanvas); - this._drawFragment(gCanvas, fragment, positionsByMessageId); + // Scale to fit. + const bb = gContent.node().getBBox(); + this._initZoom(gContent, bb.width, bb.height); } - } - // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Draw message into SVG canvas. + * @param gCanvas container. + * @param message message to be rendered. + * @param y current y position. + * @param actorsById actor lookup. + * @param positionsByMessageId x- and y-position of each message. + * @param messageIndex where we are in the set of messages to be rendered. + * @param oData occurrences info. + * @param fData fragments info. + * @private + */ + _drawMessage( + gCanvas, + message, + y, + actorsById, + positionsByMessageId, + messageIndex, + oData, + fData + ) { + Common.assertNotNull(oData); + + const request = message.type === 'request'; + const fromActor = request + ? actorsById[message.from] + : actorsById[message.to]; + const toActor = request + ? actorsById[message.to] + : actorsById[message.from]; + + if (!fromActor) { + Logger.warn( + `Cannot draw message ${JSON.stringify( + message + )}: 'from' not found.` + ); + return; + } - /** - * Draw a single occurrence. - * @param gCanvas container. - * @param oData occurrence data. - * @param positionsByMessageId map of y positions by message ID. - * @param actor wrapper containing lifeline ID (.id), position (.x) and name (.name). - * @param messageId message identifier. - * @private - */ - _drawOccurrence(gCanvas, oData, positionsByMessageId, actor, messageId) { + if (!toActor) { + Logger.warn( + `Cannot draw message ${JSON.stringify( + message + )}: 'to' not found.` + ); + return; + } - Common.assertType(oData, 'Object'); - Common.assertType(positionsByMessageId, 'Object'); - Common.assertType(actor, 'Object'); - Common.assertType(messageId, 'String'); + // Occurrences. -------------------------------------------------------------------------------- - const gOccurrences = gCanvas.select('g.asdcs-diagram-occurrences'); + if (message.occurrence) { + Logger.debug( + `Found occurrence for ${message.name}: ${JSON.stringify( + message.occurrence + )}` + ); + } + const activeTo = Diagram._calcActive(oData, toActor.id); + this._drawOccurrence( + gCanvas, + oData, + positionsByMessageId, + fromActor, + message.id + ); + this._drawOccurrence( + gCanvas, + oData, + positionsByMessageId, + toActor, + message.id + ); + const activeFrom = Diagram._calcActive(oData, fromActor.id); + + // Messages. ----------------------------------------------------------------------------------- + + const gMessages = gCanvas.select('g.asdcs-diagram-messages'); + + // Save positions for later. + + const positions = positionsByMessageId[message.id]; + positions.x0 = fromActor.x; + positions.x1 = toActor.x; + + // Calculate. + + const leftToRight = fromActor.x < toActor.x; + const loopback = message.to === message.from; + const x1 = this._calcMessageX(activeTo, toActor.x, true, leftToRight); + const x0 = loopback + ? x1 + : this._calcMessageX(activeFrom, fromActor.x, false, leftToRight); + + let messagePath; + if (loopback) { + // To self. + + messagePath = `M${x1},${y}`; + messagePath = `${messagePath} L${x1 + 200},${y}`; + messagePath = `${messagePath} L${x1 + 200},${y + 50}`; + messagePath = `${messagePath} L${x1},${y + 50}`; + } else { + // Between lifelines. - const oOptions = this.options.lifelines.occurrences; - const oWidth = oOptions.width; - const oHalfWidth = oWidth / 2; - const oForeshortening = oOptions.foreshortening; - const oMarginTop = oOptions.marginTop; - const oMarginBottom = oOptions.marginBottom; - const o = oData[actor.id]; + messagePath = `M${x0},${y}`; + messagePath = `${messagePath} L${x1},${y}`; + } - const active = Diagram._calcActive(oData, actor.id); + const styles = Diagram._getMessageStyles(message); + + // Split message over lines. + + const messageWithPrefix = `${messageIndex}. ${message.name}`; + const maxLines = this.options.messages.label.maxLines; + const wrapWords = this.options.messages.label.wrapWords; + const wrapLines = this.options.messages.label.wrapLines; + const messageLines = Common.tokenize( + messageWithPrefix, + wrapWords, + wrapLines, + maxLines + ); + + const messageTxt = this.templates.message({ + id: message.id, + classes: styles.css, + marker: styles.marker, + dasharray: styles.dasharray, + labels: messageLines, + lines: maxLines, + path: messagePath, + index: messageIndex, + x0, + x1, + y + }); + + const messageEl = Common.txt2dom(messageTxt); + const gMessage = gMessages.append('g'); + Common.dom2svg(messageEl, gMessage); + + // Set the background's bounding box to that of the text, + // so that they fit snugly. + + const labelBB = gMessage + .select('.asdcs-diagram-message-label') + .node() + .getBBox(); + gMessage + .select('.asdcs-diagram-message-label-bg') + .attr('x', labelBB.x) + .attr('y', labelBB.y) + .attr('height', labelBB.height) + .attr('width', labelBB.width); - const x = (actor.x - oHalfWidth) + (active * oWidth); - const positions = positionsByMessageId[messageId]; - const y = positions.y; + // Fragments. ---------------------------------------------------------------------------------- - let draw = true; - if (o) { + const fragment = fData[message.id]; + if (fragment) { + // It ends on this message. - if (o.start[messageId]) { + this._drawFragment(gCanvas, fragment, positionsByMessageId); + } + } - // Starting, but drawing nothing until we find the end. + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Draw a single occurrence. + * @param gCanvas container. + * @param oData occurrence data. + * @param positionsByMessageId map of y positions by message ID. + * @param actor wrapper containing lifeline ID (.id), position (.x) and name (.name). + * @param messageId message identifier. + * @private + */ + _drawOccurrence(gCanvas, oData, positionsByMessageId, actor, messageId) { + Common.assertType(oData, 'Object'); + Common.assertType(positionsByMessageId, 'Object'); + Common.assertType(actor, 'Object'); + Common.assertType(messageId, 'String'); + + const gOccurrences = gCanvas.select('g.asdcs-diagram-occurrences'); + + const oOptions = this.options.lifelines.occurrences; + const oWidth = oOptions.width; + const oHalfWidth = oWidth / 2; + const oForeshortening = oOptions.foreshortening; + const oMarginTop = oOptions.marginTop; + const oMarginBottom = oOptions.marginBottom; + const o = oData[actor.id]; + + const active = Diagram._calcActive(oData, actor.id); + + const x = actor.x - oHalfWidth + active * oWidth; + const positions = positionsByMessageId[messageId]; + const y = positions.y; + + let draw = true; + if (o) { + if (o.start[messageId]) { + // Starting, but drawing nothing until we find the end. + + o.active.push(messageId); + draw = false; + } else if (active > 0) { + const startMessageId = o.stop[messageId]; + if (startMessageId) { + // OK, it ends here. Draw the occurrence box. + + o.active.pop(); + const foreshorteningY = active * oForeshortening; + const startY = positionsByMessageId[startMessageId].y; + const height = + oMarginTop + + oMarginBottom + + (y - startY) - + foreshorteningY * 2; + const oProps = { + x: actor.x - oHalfWidth + (active - 1) * oWidth, + y: startY - oMarginTop + foreshorteningY, + height, + width: oWidth + }; + + const occurrenceTxt = this.templates.occurrence(oProps); + const occurrenceEl = Common.txt2dom(occurrenceTxt); + Common.dom2svg(occurrenceEl, gOccurrences.append('g')); + } + draw = false; + } + } - o.active.push(messageId); - draw = false; + if (draw) { + // Seems this is a singleton occurrence. We just draw a wee box around it. + + const height = oMarginTop + oMarginBottom; + const occurrenceProperties = { + x, + y: y - oMarginTop, + height, + width: oWidth + }; + const defaultTxt = this.templates.occurrence(occurrenceProperties); + const defaultEl = Common.txt2dom(defaultTxt); + Common.dom2svg(defaultEl, gOccurrences.append('g')); + } + } - } else if (active > 0) { + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Draw box(es) around fragment(s). + * @param gCanvas container. + * @param fragment fragment definition, corresponding to its final (stop) message. + * @param positionsByMessageId message dimensions. + * @private + */ + _drawFragment(gCanvas, fragment, positionsByMessageId) { + const optFragments = this.options.fragments; + const gFragments = gCanvas.select('g.asdcs-diagram-fragments'); + const p1 = positionsByMessageId[fragment.stop]; + if (p1 && fragment.start && fragment.start.length > 0) { + for (const start of fragment.start) { + const message = this.application + .getModel() + .getMessageById(start); + const bounds = this._calcFragmentBounds( + message, + fragment, + positionsByMessageId + ); + if (bounds) { + const maxLines = this.options.fragments.label.maxLines; + const wrapWords = this.options.fragments.label.wrapWords; + const wrapLines = this.options.fragments.label.wrapLines; + const lines = Common.tokenize( + message.fragment.guard, + wrapWords, + wrapLines, + maxLines + ); + + const params = { + id: start, + x: bounds.x0 - optFragments.leftMargin, + y: bounds.y0 - optFragments.topMargin, + height: + bounds.y1 - bounds.y0 + optFragments.heightMargin, + width: bounds.x1 - bounds.x0 + optFragments.widthMargin, + operator: message.fragment.operator || 'alt', + lines + }; + + const fragmentTxt = this.templates.fragment(params); + const fragmentEl = Common.txt2dom(fragmentTxt); + const gFragment = gFragments.append('g'); + Common.dom2svg(fragmentEl, gFragment); + + const labelBB = gFragment + .select('.asdcs-diagram-fragment-guard') + .node() + .getBBox(); + gFragment + .select('.asdcs-diagram-fragment-guard-bg') + .attr('x', labelBB.x) + .attr('y', labelBB.y) + .attr('height', labelBB.height) + .attr('width', labelBB.width); + } else { + Logger.warn(`Bad fragment: ${JSON.stringify(fragment)}`); + } + } + } + } - const startMessageId = o.stop[messageId]; - if (startMessageId) { + // /////////////////////////////////////////////////////////////////////////////////////////////// + + _calcFragmentBounds(startMessage, fragment, positionsByMessageId) { + if (startMessage) { + const steps = this.application.getModel().unwrap().diagram.steps; + const bounds = { x0: 99999, x1: 0, y0: 99999, y1: 0 }; + let foundStart = false; + let foundStop = false; + for (const step of steps) { + const message = step.message; + if (message) { + if (message.id === startMessage.id) { + foundStart = true; + } + if (foundStart && !foundStop) { + const positions = positionsByMessageId[message.id]; + if (positions) { + bounds.x0 = Math.min( + bounds.x0, + Math.min(positions.x0, positions.x1) + ); + bounds.y0 = Math.min(bounds.y0, positions.y); + bounds.x1 = Math.max( + bounds.x1, + Math.max(positions.x0, positions.x1) + ); + bounds.y1 = Math.max(bounds.y1, positions.y); + } else { + // This probably means it hasn't been recorded yet, which is fine, because + // we draw fragments from where they END. + foundStop = true; + } + } + + if (message.id === fragment.stop) { + foundStop = true; + } + } + } + return bounds; + } + return undefined; + } - // OK, it ends here. Draw the occurrence box. + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Draw all lifelines. + * @param gLifelines lifelines container. + * @param lifelines lifelines definitions. + * @param y height. + * @private + */ + _drawLifelines(gLifelines, lifelines, y) { + const maxLines = this.options.lifelines.header.maxLines; + const wrapWords = this.options.lifelines.header.wrapWords; + const wrapLines = this.options.lifelines.header.wrapLines; + + for (const lifeline of lifelines) { + const lines = Common.tokenize( + lifeline.actor.name, + wrapWords, + wrapLines, + maxLines + ); + const lifelineTxt = this.templates.lifeline({ + x: lifeline.x, + y0: 0, + y1: y, + lines, + rows: maxLines, + headerHeight: this.options.lifelines.header.height, + headerWidth: this.options.lifelines.header.width, + id: lifeline.actor.id + }); + + const lifelineEl = Common.txt2dom(lifelineTxt); + Common.dom2svg(lifelineEl, gLifelines.append('g')); + } + } - o.active.pop(); - const foreshorteningY = active * oForeshortening; - const startY = positionsByMessageId[startMessageId].y; - const height = ((oMarginTop + oMarginBottom) + (y - startY)) - (foreshorteningY * 2); - const oProps = { - x: (actor.x - oHalfWidth) + ((active - 1) * oWidth), - y: ((startY - oMarginTop) + foreshorteningY), - height, - width: oWidth, - }; + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Initialize all mouse events. + * @param gLifelines lifelines container. + * @param gCanvas top-level canvas container. + * @private + */ + _initMouseEvents(gLifelines, gCanvas) { + const self = this; + const source = 'asdcs'; + const origin = `${window.location.protocol}//${window.location.host}`; + + let timer; + gLifelines + .selectAll('.asdcs-diagram-lifeline-selectable') + .on('mouseenter', function f() { + timer = setTimeout(() => { + self.application.selectLifeline( + d3.select(this.parentNode).attr('data-id') + ); + }, 150); + }) + .on('mouseleave', () => { + clearTimeout(timer); + self.application.selectLifeline(); + }) + .on('click', function f() { + const id = d3.select(this.parentNode).attr('data-id'); + window.postMessage({ source, id, type: 'lifeline' }, origin); + }); + + gLifelines + .selectAll('.asdcs-diagram-lifeline-heading-box') + .on('mouseenter', function f() { + timer = setTimeout(() => { + self.application.selectLifeline( + d3.select(this.parentNode).attr('data-id') + ); + }, 150); + }) + .on('mouseleave', () => { + clearTimeout(timer); + self.application.selectLifeline(); + }) + .on('click', function f() { + const id = d3.select(this.parentNode).attr('data-id'); + window.postMessage( + { source, id, type: 'lifelineHeader' }, + origin + ); + }); + + gCanvas + .selectAll('.asdcs-diagram-message-selectable') + .on('mouseenter', function f() { + self.events.message = { x: d3.event.pageX, y: d3.event.pageY }; + timer = setTimeout(() => { + self.application.selectMessage( + d3.select(this.parentNode).attr('data-id') + ); + }, 200); + }) + .on('mouseleave', () => { + delete self.events.message; + clearTimeout(timer); + self.application.selectMessage(); + }) + .on('click', function f() { + const id = d3.select(this.parentNode).attr('data-id'); + window.postMessage({ source, id, type: 'message' }, origin); + }); + } - const occurrenceTxt = this.templates.occurrence(oProps); - const occurrenceEl = Common.txt2dom(occurrenceTxt); - Common.dom2svg(occurrenceEl, gOccurrences.append('g')); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Get CSS classes to be applied to a message, according to whether request/response + * or synchronous/asynchronous. + * @param message message being rendered. + * @returns CSS class name(s). + * @private + */ + static _getMessageStyles(message) { + let marker = 'asdcsDiagramArrowSolid'; + let dasharray = ''; + let css = 'asdcs-diagram-message'; + if (message.type === 'request') { + css = `${css} asdcs-diagram-message-request`; + } else { + css = `${css} asdcs-diagram-message-response`; + marker = 'asdcsDiagramArrowOpen'; + dasharray = '30, 10'; + } + if (message.asynchronous) { + css = `${css} asdcs-diagram-message-asynchronous`; + marker = 'asdcsDiagramArrowOpen'; + } else { + css = `${css} asdcs-diagram-message-synchronous`; } - draw = false; - } + + return { css, marker, dasharray }; } - if (draw) { + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Initialize or reinitialize zoom. This sets the initial zoom in the case of + * a re-rendering, and initializes the eventhandling in all cases. + * + * It does some fairly risky parsing of the 'transform' attribute, assuming that it + * can contain scale() and translate(). But only the zoom handler and us are writing + * the transform values, so that's probably OK. + * + * @param gContent container. + * @param width diagram width. + * @param height diagram height. + * @private + */ + _initZoom(gContent, width, height) { + const zoomed = function zoomed() { + if (!this.initialTransformX && !this.initialTransformY) { + this.initialTransformX = d3.event.transform.x; + this.initialTransformY = d3.event.transform.y; + } - // Seems this is a singleton occurrence. We just draw a wee box around it. + gContent.attr( + 'transform', + `translate(${d3.event.transform.x - + this.initialTransformX}, ${d3.event.transform.y - + this.initialTransformY})scale(${d3.event.transform.k}, ${ + d3.event.transform.k + })` + ); + }; + + const viewWidth = this.state.width || this.options.svg.width; + const viewHeight = this.state.height || this.options.svg.height; + const scaleMinimum = this.options.svg.scale.minimum; + const scaleWidth = viewWidth / width; + const scaleHeight = viewHeight / height; + + let scale = scaleMinimum; + if (this.options.svg.scale.width) { + scale = Math.max(scale, scaleWidth); + } + if (this.options.svg.scale.height) { + scale = Math.min(scale, scaleHeight); + } - const height = (oMarginTop + oMarginBottom); - const occurrenceProperties = { x, y: y - oMarginTop, height, width: oWidth }; - const defaultTxt = this.templates.occurrence(occurrenceProperties); - const defaultEl = Common.txt2dom(defaultTxt); - Common.dom2svg(defaultEl, gOccurrences.append('g')); - } + scale = Math.max(scale, scaleMinimum); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Draw box(es) around fragment(s). - * @param gCanvas container. - * @param fragment fragment definition, corresponding to its final (stop) message. - * @param positionsByMessageId message dimensions. - * @private - */ - _drawFragment(gCanvas, fragment, positionsByMessageId) { - - const optFragments = this.options.fragments; - const gFragments = gCanvas.select('g.asdcs-diagram-fragments'); - const p1 = positionsByMessageId[fragment.stop]; - if (p1 && fragment.start && fragment.start.length > 0) { - - for (const start of fragment.start) { - - const message = this.application.getModel().getMessageById(start); - const bounds = this._calcFragmentBounds(message, fragment, positionsByMessageId); - if (bounds) { - - const maxLines = this.options.fragments.label.maxLines; - const wrapWords = this.options.fragments.label.wrapWords; - const wrapLines = this.options.fragments.label.wrapLines; - const lines = Common.tokenize(message.fragment.guard, wrapWords, wrapLines, maxLines); - - const params = { - id: start, - x: bounds.x0 - optFragments.leftMargin, - y: bounds.y0 - optFragments.topMargin, - height: (bounds.y1 - bounds.y0) + optFragments.heightMargin, - width: (bounds.x1 - bounds.x0) + optFragments.widthMargin, - operator: (message.fragment.operator || 'alt'), - lines, - }; - - const fragmentTxt = this.templates.fragment(params); - const fragmentEl = Common.txt2dom(fragmentTxt); - const gFragment = gFragments.append('g'); - Common.dom2svg(fragmentEl, gFragment); - - const labelBB = gFragment.select('.asdcs-diagram-fragment-guard').node().getBBox(); - gFragment.select('.asdcs-diagram-fragment-guard-bg') - .attr('x', labelBB.x) - .attr('y', labelBB.y) - .attr('height', labelBB.height) - .attr('width', labelBB.width); + let translate = [0, 0]; + if (this.savedTransform) { + const s = this.savedTransform; + const scaleStart = s.indexOf('scale('); + if (scaleStart !== -1) { + scale = parseFloat(s.substring(scaleStart + 6, s.length - 1)); + } + const translateStart = s.indexOf('translate('); + if (translateStart !== -1) { + const spec = s.substring( + translateStart + 10, + s.indexOf(')', translateStart) + ); + const tokens = spec.split(','); + translate = [parseFloat(tokens[0]), parseFloat(tokens[1])]; + } + gContent.attr('transform', this.savedTransform); } else { - Logger.warn(`Bad fragment: ${JSON.stringify(fragment)}`); + gContent.attr('transform', `scale(${scale})`); } - } - } - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - _calcFragmentBounds(startMessage, fragment, positionsByMessageId) { - if (startMessage) { - const steps = this.application.getModel().unwrap().diagram.steps; - const bounds = { x0: 99999, x1: 0, y0: 99999, y1: 0 }; - let foundStart = false; - let foundStop = false; - for (const step of steps) { - const message = step.message; - if (message) { - if (message.id === startMessage.id) { - foundStart = true; - } - if (foundStart && !foundStop) { - const positions = positionsByMessageId[message.id]; - if (positions) { - bounds.x0 = Math.min(bounds.x0, Math.min(positions.x0, positions.x1)); - bounds.y0 = Math.min(bounds.y0, positions.y); - bounds.x1 = Math.max(bounds.x1, Math.max(positions.x0, positions.x1)); - bounds.y1 = Math.max(bounds.y1, positions.y); - } else { - // This probably means it hasn't been recorded yet, which is fine, because - // we draw fragments from where they END. - foundStop = true; - } - } - if (message.id === fragment.stop) { - foundStop = true; - } - } - } - return bounds; - } - return undefined; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Draw all lifelines. - * @param gLifelines lifelines container. - * @param lifelines lifelines definitions. - * @param y height. - * @private - */ - _drawLifelines(gLifelines, lifelines, y) { - - const maxLines = this.options.lifelines.header.maxLines; - const wrapWords = this.options.lifelines.header.wrapWords; - const wrapLines = this.options.lifelines.header.wrapLines; - - for (const lifeline of lifelines) { - const lines = Common.tokenize(lifeline.actor.name, wrapWords, wrapLines, maxLines); - const lifelineTxt = this.templates.lifeline({ - x: lifeline.x, - y0: 0, - y1: y, - lines, - rows: maxLines, - headerHeight: this.options.lifelines.header.height, - headerWidth: this.options.lifelines.header.width, - id: lifeline.actor.id, - }); - - const lifelineEl = Common.txt2dom(lifelineTxt); - Common.dom2svg(lifelineEl, gLifelines.append('g')); - } - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Initialize all mouse events. - * @param gLifelines lifelines container. - * @param gCanvas top-level canvas container. - * @private - */ - _initMouseEvents(gLifelines, gCanvas) { - - const self = this; - const source = 'asdcs'; - const origin = `${window.location.protocol}//${window.location.host}`; - - let timer; - gLifelines.selectAll('.asdcs-diagram-lifeline-selectable') - .on('mouseenter', function f() { - timer = setTimeout(() => { - self.application.selectLifeline(d3.select(this.parentNode).attr('data-id')); - }, 150); - }) - .on('mouseleave', () => { - clearTimeout(timer); - self.application.selectLifeline(); - }) - .on('click', function f() { - const id = d3.select(this.parentNode).attr('data-id'); - window.postMessage({ source, id, type: 'lifeline' }, origin); - }); - - gLifelines.selectAll('.asdcs-diagram-lifeline-heading-box') - .on('mouseenter', function f() { - timer = setTimeout(() => { - self.application.selectLifeline(d3.select(this.parentNode).attr('data-id')); - }, 150); - }) - .on('mouseleave', () => { - clearTimeout(timer); - self.application.selectLifeline(); - }) - .on('click', function f() { - const id = d3.select(this.parentNode).attr('data-id'); - window.postMessage({ source, id, type: 'lifelineHeader' }, origin); - }); - - gCanvas.selectAll('.asdcs-diagram-message-selectable') - .on('mouseenter', function f() { - self.events.message = { x: d3.event.pageX, y: d3.event.pageY }; - timer = setTimeout(() => { - self.application.selectMessage(d3.select(this.parentNode).attr('data-id')); - }, 200); - }) - .on('mouseleave', () => { - delete self.events.message; - clearTimeout(timer); - self.application.selectMessage(); - }) - .on('click', function f() { - const id = d3.select(this.parentNode).attr('data-id'); - window.postMessage({ source, id, type: 'message' }, origin); - }); - - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Get CSS classes to be applied to a message, according to whether request/response - * or synchronous/asynchronous. - * @param message message being rendered. - * @returns CSS class name(s). - * @private - */ - static _getMessageStyles(message) { - - let marker = 'asdcsDiagramArrowSolid'; - let dasharray = ''; - let css = 'asdcs-diagram-message'; - if (message.type === 'request') { - css = `${css} asdcs-diagram-message-request`; - } else { - css = `${css} asdcs-diagram-message-response`; - marker = 'asdcsDiagramArrowOpen'; - dasharray = '30, 10'; - } + const zoom = d3.zoom().on('zoom', zoomed); - if (message.asynchronous) { - css = `${css} asdcs-diagram-message-asynchronous`; - marker = 'asdcsDiagramArrowOpen'; - } else { - css = `${css} asdcs-diagram-message-synchronous`; - } + this.svg.call(zoom); + this.svg.call(zoom.scaleBy, scale); - return { css, marker, dasharray }; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Initialize or reinitialize zoom. This sets the initial zoom in the case of - * a re-rendering, and initializes the eventhandling in all cases. - * - * It does some fairly risky parsing of the 'transform' attribute, assuming that it - * can contain scale() and translate(). But only the zoom handler and us are writing - * the transform values, so that's probably OK. - * - * @param gContent container. - * @param width diagram width. - * @param height diagram height. - * @private - */ - _initZoom(gContent, width, height) { - - const zoomed = function zoomed() { - if (!this.initialTransformX && !this.initialTransformY) { - this.initialTransformX = d3.event.transform.x; - this.initialTransformY = d3.event.transform.y; - } - - gContent.attr('transform', - `translate(${d3.event.transform.x - this.initialTransformX}, ${d3.event.transform.y - - this.initialTransformY})scale(${d3.event.transform.k}, ${d3.event.transform.k})`); - }; - - const viewWidth = this.state.width || this.options.svg.width; - const viewHeight = this.state.height || this.options.svg.height; - const scaleMinimum = this.options.svg.scale.minimum; - const scaleWidth = viewWidth / width; - const scaleHeight = viewHeight / height; - - let scale = scaleMinimum; - if (this.options.svg.scale.width) { - scale = Math.max(scale, scaleWidth); - } - if (this.options.svg.scale.height) { - scale = Math.min(scale, scaleHeight); + gContent.attr( + 'transform', + `translate(${translate[0]}, ${translate[1]})` + ); + gContent.attr('transform', `scale(${scale})`); } - scale = Math.max(scale, scaleMinimum); - - let translate = [0, 0]; - if (this.savedTransform) { - const s = this.savedTransform; - const scaleStart = s.indexOf('scale('); - if (scaleStart !== -1) { - scale = parseFloat(s.substring(scaleStart + 6, s.length - 1)); - } - const translateStart = s.indexOf('translate('); - if (translateStart !== -1) { - const spec = s.substring(translateStart + 10, s.indexOf(')', translateStart)); - const tokens = spec.split(','); - translate = [parseFloat(tokens[0]), parseFloat(tokens[1])]; - } - - gContent.attr('transform', this.savedTransform); - } else { - gContent.attr('transform', `scale(${scale})`); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Hide from the linter the fact that we're modifying the lifeline. + * @param lifeline to be updated with X position. + * @param x X position. + * @private + */ + static _processLifeline(lifeline, x) { + const actor = lifeline; + actor.id = actor.id || actor.name; + actor.x = x; } - const zoom = d3.zoom() - .on('zoom', zoomed); - - this.svg.call(zoom); - this.svg.call(zoom.scaleBy, scale); - - gContent.attr('transform', `translate(${translate[0]}, ${translate[1]})`); - gContent.attr('transform', `scale(${scale})`); - - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Hide from the linter the fact that we're modifying the lifeline. - * @param lifeline to be updated with X position. - * @param x X position. - * @private - */ - static _processLifeline(lifeline, x) { - const actor = lifeline; - actor.id = actor.id || actor.name; - actor.x = x; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Derive active occurrences for lifeline. - * @param oData occurrences data. - * @param lifelineId lifeline to be analyzed. - * @returns {number} - * @private - */ - static _calcActive(oData, lifelineId) { - const o = oData[lifelineId]; - let active = 0; - if (o && o.active) { - active = o.active.length; + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Derive active occurrences for lifeline. + * @param oData occurrences data. + * @param lifelineId lifeline to be analyzed. + * @returns {number} + * @private + */ + static _calcActive(oData, lifelineId) { + const o = oData[lifelineId]; + let active = 0; + if (o && o.active) { + active = o.active.length; + } + return active; } - return active; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Derive the X position of an occurrence on a lifeline, taking into account how - * many occurrences are active. - * @param active active count. - * @param x lifeline X position; basis for offset. - * @param arrow whether this is the arrow (to) end. - * @param leftToRight whether this message goes left-to-right. - * @returns {*} calculated X position for occurrence left-hand side. - * @private - */ - _calcMessageX(active, x, arrow, leftToRight) { - const width = this.options.lifelines.occurrences.width; - const halfWidth = width / 2; - const active0 = Math.max(0, active - 1); - let calculated = x + (active0 * width); - if (arrow) { - // End (ARROW). - if (leftToRight) { - calculated -= halfWidth; - } else { - calculated += halfWidth; - } - } else { - // Start (NOT ARROW). - if (leftToRight) { - calculated += halfWidth; - } else { - calculated -= halfWidth; - } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Derive the X position of an occurrence on a lifeline, taking into account how + * many occurrences are active. + * @param active active count. + * @param x lifeline X position; basis for offset. + * @param arrow whether this is the arrow (to) end. + * @param leftToRight whether this message goes left-to-right. + * @returns {*} calculated X position for occurrence left-hand side. + * @private + */ + _calcMessageX(active, x, arrow, leftToRight) { + const width = this.options.lifelines.occurrences.width; + const halfWidth = width / 2; + const active0 = Math.max(0, active - 1); + let calculated = x + active0 * width; + if (arrow) { + // End (ARROW). + if (leftToRight) { + calculated -= halfWidth; + } else { + calculated += halfWidth; + } + } else { + // Start (NOT ARROW). + if (leftToRight) { + calculated += halfWidth; + } else { + calculated -= halfWidth; + } + } + + return calculated; } - return calculated; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Show popup upon hovering over a messages that has associated notes. - * @param id - * @private - */ - _showNotesPopup(id) { - if (this.popup) { - if (id) { - const message = this.application.getModel().getMessageById(id); - if (message && message.notes && message.notes.length > 0 && this.events.message) { - this.popup.setState({ - visible: true, - left: this.events.message.x - 50, - top: this.events.message.y + 20, - notes: message.notes[0], - }); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Show popup upon hovering over a messages that has associated notes. + * @param id + * @private + */ + _showNotesPopup(id) { + if (this.popup) { + if (id) { + const message = this.application.getModel().getMessageById(id); + if ( + message && + message.notes && + message.notes.length > 0 && + this.events.message + ) { + this.popup.setState({ + visible: true, + left: this.events.message.x - 50, + top: this.events.message.y + 20, + notes: message.notes[0] + }); + } + } else { + this.popup.setState({ visible: false, notes: '' }); + } } - } else { - this.popup.setState({ visible: false, notes: '' }); - } } - } } - Diagram.propTypes = { - application: PropTypes.object.isRequired, + application: PropTypes.object.isRequired }; export default Diagram; diff --git a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/diagram/components/popup/Popup.jsx b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/diagram/components/popup/Popup.jsx index 8f8f859aad..a2a6582ab0 100644 --- a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/diagram/components/popup/Popup.jsx +++ b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/diagram/components/popup/Popup.jsx @@ -25,85 +25,81 @@ import iconEdit from '../../../../../../../../res/ecomp/asdc/sequencer/sprites/i * @constructor */ class Popup extends React.Component { - - // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Construct react view. - * @param props element properties (of which there are none). - * @param context react context. - */ - constructor(props, context) { - super(props, context); - this.state = { - top: 0, - left: 0, - visible: false, - notes: '', - }; - } - - // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Render view. - * @returns {XML} - */ - render() { - - // Build CSS + styles to position and configure popup. - - let top = this.state.top; - let left = this.state.left; - - const popupHeight = 200; - const popupWidth = 320; - - let auxCssVertical = 'top'; - let auxCssHorizontal = 'left'; - - if (this.state.top > (window.innerHeight - popupHeight)) { - top -= (popupHeight + 50); - auxCssVertical = 'bottom'; - } - - if (this.state.left > (window.innerWidth - popupWidth)) { - left -= (popupWidth - 80); - auxCssHorizontal = 'right'; - } - - const auxCss = `asdcs-diagram-popup-${auxCssVertical}${auxCssHorizontal}`; - const styles = { - top, - left, - display: (this.state.visible ? 'block' : 'none'), - }; - - // Render element. - - let notes = this.state.notes || ''; - if (notes.length > 255) { - notes = notes.substring(0, 255); - notes = `${notes} ...`; + // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Construct react view. + * @param props element properties (of which there are none). + * @param context react context. + */ + constructor(props, context) { + super(props, context); + this.state = { + top: 0, + left: 0, + visible: false, + notes: '' + }; } - return ( -
-
Notes
-
-
- -
-
-
- {notes} + // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Render view. + * @returns {XML} + */ + render() { + // Build CSS + styles to position and configure popup. + + let top = this.state.top; + let left = this.state.left; + + const popupHeight = 200; + const popupWidth = 320; + + let auxCssVertical = 'top'; + let auxCssHorizontal = 'left'; + + if (this.state.top > window.innerHeight - popupHeight) { + top -= popupHeight + 50; + auxCssVertical = 'bottom'; + } + + if (this.state.left > window.innerWidth - popupWidth) { + left -= popupWidth - 80; + auxCssHorizontal = 'right'; + } + + const auxCss = `asdcs-diagram-popup-${auxCssVertical}${auxCssHorizontal}`; + const styles = { + top, + left, + display: this.state.visible ? 'block' : 'none' + }; + + // Render element. + + let notes = this.state.notes || ''; + if (notes.length > 255) { + notes = notes.substring(0, 255); + notes = `${notes} ...`; + } + + return ( +
+
Notes
+
+
+ +
+
+
{notes}
+
+
+
-
-
-
-
- ); - } + ); + } } export default Popup; diff --git a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/dialog/Dialog.jsx b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/dialog/Dialog.jsx index d48ef3bd88..96a709948c 100644 --- a/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/dialog/Dialog.jsx +++ b/dox-sequence-diagram-ui/src/main/webapp/lib/ecomp/asdc/sequencer/components/dialog/Dialog.jsx @@ -28,211 +28,216 @@ import iconClose from '../../../../../../res/ecomp/asdc/sequencer/sprites/icons/ * configured, shown and hidden as required. */ class Dialog extends React.Component { + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Construct view. + */ + constructor(props, context) { + super(props, context); + + this.MODE = { + INFO: { + icon: 'asdcs-icon-info', + heading: 'Information' + }, + ERROR: { + icon: 'asdcs-icon-exclaim', + heading: 'Error' + }, + EDIT: { + icon: 'asdcs-icon-edit', + heading: 'Edit', + edit: true, + confirm: true + }, + CONFIRM: { + icon: 'asdcs-icon-question', + heading: 'Confirm', + confirm: true + } + }; + + this.state = { + mode: this.MODE.INFO, + message: '', + text: '', + visible: false + }; + + // Bindings. + + this.onClickOK = this.onClickOK.bind(this); + this.onClickCancel = this.onClickCancel.bind(this); + this.onChangeText = this.onChangeText.bind(this); + this.showConfirmDialog = this.showConfirmDialog.bind(this); + this.showInfoDialog = this.showInfoDialog.bind(this); + this.showEditDialog = this.showEditDialog.bind(this); + this.showErrorDialog = this.showErrorDialog.bind(this); + this.showDialog = this.showDialog.bind(this); + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Show info dialog. + * @param message info message. + */ + showInfoDialog(message) { + this.showDialog(this.MODE.INFO, { message }); + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Show error dialog. + * @param message error message. + */ + showErrorDialog(message) { + this.showDialog(this.MODE.ERROR, { message }); + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Show edit dialog. + * @param message dialog message. + * @param text current edit text. + * @param callback callback function to be invoked on OK. + */ + showEditDialog(message, text, callback) { + this.showDialog(this.MODE.EDIT, { message, text, callback }); + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Show confirmation dialog. + * @param message dialog message. + * @param callback callback function to be invoked on OK. + */ + showConfirmDialog(message, callback) { + this.showDialog(this.MODE.CONFIRM, { message, callback }); + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Handle buttonclick. + */ + onClickOK() { + this.props.application.hideOverlay(); + this.setState({ visible: false }); + if (this.callback) { + // So far the only thing we can return is edit text, but send it back + // as properties to allow for future return values. + + this.callback({ text: this.state.text }); + } + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Handle buttonclick. + */ + onClickCancel() { + this.props.application.hideOverlay(); + this.setState({ visible: false }); + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Handle text changes. + * @param event update event. + */ + onChangeText(event) { + this.setState({ text: event.target.value }); + } + + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Show dialog in specified configuration. + * @param mode dialog mode. + * @param args dialog parameters, varying slightly by dialog type. + * @private + */ + showDialog(mode, args) { + this.props.application.showOverlay(); + this.callback = args.callback; + this.setState({ + mode, + visible: true, + message: args.message || '', + text: args.text || '' + }); + } - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Construct view. - */ - constructor(props, context) { - - super(props, context); - - this.MODE = { - INFO: { - icon: 'asdcs-icon-info', - heading: 'Information', - }, - ERROR: { - icon: 'asdcs-icon-exclaim', - heading: 'Error', - }, - EDIT: { - icon: 'asdcs-icon-edit', - heading: 'Edit', - edit: true, - confirm: true, - }, - CONFIRM: { - icon: 'asdcs-icon-question', - heading: 'Confirm', - confirm: true, - }, - }; - - this.state = { - mode: this.MODE.INFO, - message: '', - text: '', - visible: false, - }; - - // Bindings. - - this.onClickOK = this.onClickOK.bind(this); - this.onClickCancel = this.onClickCancel.bind(this); - this.onChangeText = this.onChangeText.bind(this); - this.showConfirmDialog = this.showConfirmDialog.bind(this); - this.showInfoDialog = this.showInfoDialog.bind(this); - this.showEditDialog = this.showEditDialog.bind(this); - this.showErrorDialog = this.showErrorDialog.bind(this); - this.showDialog = this.showDialog.bind(this); - - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Show info dialog. - * @param message info message. - */ - showInfoDialog(message) { - this.showDialog(this.MODE.INFO, { message }); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Show error dialog. - * @param message error message. - */ - showErrorDialog(message) { - this.showDialog(this.MODE.ERROR, { message }); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Show edit dialog. - * @param message dialog message. - * @param text current edit text. - * @param callback callback function to be invoked on OK. - */ - showEditDialog(message, text, callback) { - this.showDialog(this.MODE.EDIT, { message, text, callback }); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Show confirmation dialog. - * @param message dialog message. - * @param callback callback function to be invoked on OK. - */ - showConfirmDialog(message, callback) { - this.showDialog(this.MODE.CONFIRM, { message, callback }); - } - - // /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Handle buttonclick. - */ - onClickOK() { - this.props.application.hideOverlay(); - this.setState({ visible: false }); - if (this.callback) { - - // So far the only thing we can return is edit text, but send it back - // as properties to allow for future return values. - - this.callback({ text: this.state.text }); + // /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Render dialog into the page, initially hidden. + */ + render() { + const dialogClass = this.state.visible ? '' : 'asdcs-hidden'; + const cancelClass = this.callback ? '' : 'asdcs-hidden'; + const textClass = + this.state.mode === this.MODE.EDIT ? '' : 'asdcs-hidden'; + + return ( +
+
+ {this.state.mode.heading} +
+
+ +
+
+ + + + +
+
{this.state.message}
+
+ -
- ); - } + /** + * Render to DOM. + */ + render() { + return ( +
+