From a7d6361d90f898bad9fd94bc21068e82d65d13bf Mon Sep 17 00:00:00 2001 From: Alexey Morozov Date: Sat, 1 Nov 2025 00:12:39 +0300 Subject: [PATCH] Support diagram-only annotation elements and links: * Add `AnnotationElement` and `AnnotationLink` diagram cell types representing diagram-only elements and links which exports and imports with the diagram but does not exists in the data graph: - Support annotation elements in `SelectionActionEstablishLink` and new `SelectionActionAnnotate` components; - Support annotation links in `LinkActionDelete`, `LinkActionMoveEndpoint` components. * Display and edit annotations with new built-in templates `NoteTemplate` and `NoteLinkTemplate` which use `NoteAnnotation`, `NoteEntity` and `NoteLink` template components: - Change `defaultElementTemplate` to `defaultElementResolver`, `defaultLinkTemplate` to `defaultLinkResolver` in `SharedCanvasState` to support new default fallbacks. * Add `AnnotationContent` and `ColorVariant` element template state properties to support editable annotations: - Support `ColorVariant` template state property as default fallback for non-entity elements in `typeStyleResolver`. * Support user-resizable element templates with `ElementSize` template state property: - Resizable elements display "box with handles" in the `Halo` to change the size; - Changed element sizes are captured and restored by `RestoreGeometry` command; - Add `setTemplateProperty()` utility function to easily set or unset template state property. * Add `ElementTemplate.supports` property to tell template capabilities such as ability to expand/collapse or resized by user. * Add `TemplateProps.onlySelected` flag to use in the element templates to track if the element is the only one selected without performance penalty. * Make `Halo` margin configurable via CSS property `--reactodia-selection-single-box-margin`. * Highlight link path in `HaloLink` with `--reactodia-selection-link-color` color by default. * Fix `DraggableHandle` to avoid using stale `onDragHandle` and `onEndDragHandle` prop values. * Refactor various places to support annotations: - Extract internal `DragLinkMover` as a utility component to use as base for `DragEditLayer` and `AnnotationLinkMover`; - Add internal `ContentEditablePlaintext` utility component; - Add internal `ResizableBox` utility component; * Use small subset of [carbon design icons](https://github.com/carbon-design-system/carbon-icons) for various buttons. --- CHANGELOG.md | 16 + THIRDPARTY.md | 179 +++++ eslint.config.mjs | 1 + examples/styleCustomization.tsx | 6 +- i18n/i18n.schema.json | 21 +- .../en.reactodia-translation.json | 17 +- images/carbon-design/text--align--center.svg | 1 + images/carbon-design/text--align--left.svg | 1 + images/carbon-design/text--align--right.svg | 1 + images/carbon-design/text--bold.svg | 1 + images/carbon-design/text--italic.svg | 1 + images/carbon-design/text--strikethrough.svg | 1 + images/carbon-design/text--underline.svg | 1 + src/data/schema.ts | 87 ++- src/diagram/commands.ts | 32 +- src/diagram/customization.ts | 30 + src/diagram/elementLayer.tsx | 26 +- src/diagram/elements.ts | 11 +- src/diagram/linkLayer.tsx | 2 +- src/diagram/renderingState.ts | 8 +- src/diagram/sharedCanvasState.ts | 44 +- src/editor/annotationCells.ts | 80 +++ src/editor/dataDiagramModel.ts | 9 +- src/editor/editorController.tsx | 10 +- src/editor/overlayController.tsx | 2 +- src/editor/serializedDiagram.ts | 23 +- src/templates/classicTemplate.tsx | 4 + src/templates/noteAnnotation.tsx | 389 +++++++++++ src/templates/standardTemplate.tsx | 3 + .../annotation/annotationLinkMover.tsx | 93 +++ src/widgets/annotation/annotationSupport.tsx | 98 +++ src/widgets/annotation/index.ts | 1 + src/widgets/canvas.tsx | 5 +- src/widgets/halo.tsx | 74 ++- src/widgets/linkAction.tsx | 145 ++++- src/widgets/linksToolbox.tsx | 4 + src/widgets/selection.tsx | 3 + src/widgets/selectionAction.tsx | 161 ++++- .../utility/contentEditablePlaintext.tsx | 60 ++ src/widgets/utility/dragLinkMover.tsx | 508 +++++++++++++++ src/widgets/utility/draggableHandle.tsx | 17 +- src/widgets/utility/resizableBox.tsx | 146 +++++ src/widgets/visualAuthoring/dragEditLayer.tsx | 616 +++++------------- src/workspace.ts | 10 +- src/workspace/commandBusTopic.ts | 4 + src/workspace/workspace.tsx | 44 +- styles/main.scss | 4 +- styles/mixin/_icons.scss | 17 + styles/templates/_noteAnnotation.scss | 117 ++++ styles/theme/_common.scss | 5 +- styles/theme/_theme.scss | 3 + .../_dragLinkMover.scss} | 2 +- styles/utility/_draggableHandle.scss | 30 +- styles/utility/_resizableBox.scss | 72 ++ styles/widgets/_halo.scss | 36 +- styles/widgets/_haloLink.scss | 8 +- styles/widgets/_selectionAction.scss | 4 + 57 files changed, 2681 insertions(+), 613 deletions(-) create mode 100644 images/carbon-design/text--align--center.svg create mode 100644 images/carbon-design/text--align--left.svg create mode 100644 images/carbon-design/text--align--right.svg create mode 100644 images/carbon-design/text--bold.svg create mode 100644 images/carbon-design/text--italic.svg create mode 100644 images/carbon-design/text--strikethrough.svg create mode 100644 images/carbon-design/text--underline.svg create mode 100644 src/editor/annotationCells.ts create mode 100644 src/templates/noteAnnotation.tsx create mode 100644 src/widgets/annotation/annotationLinkMover.tsx create mode 100644 src/widgets/annotation/annotationSupport.tsx create mode 100644 src/widgets/annotation/index.ts create mode 100644 src/widgets/utility/contentEditablePlaintext.tsx create mode 100644 src/widgets/utility/dragLinkMover.tsx create mode 100644 src/widgets/utility/resizableBox.tsx create mode 100644 styles/templates/_noteAnnotation.scss rename styles/{editor/_dragEditLayer.scss => utility/_dragLinkMover.scss} (95%) create mode 100644 styles/utility/_resizableBox.scss diff --git a/CHANGELOG.md b/CHANGELOG.md index b3adb41a..297c14a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,13 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p * Introduce an optional contract for `Element` or `Link`-derived cell types to be serializable: `SerializableElementCell` and `SerializableLinkCell`; * When implemented, the corresponding cell types can be exported and later imported with the diagram; * `DataDiagramModel.importLayout()` will accept known cell types via `elementCellTypes` and `linkCellTypes` to import. +- Add `AnnotationElement` and `AnnotationLink` diagram cell types representing diagram-only elements and links which exports and imports with the diagram but does not exists in the data graph: + * Rendered by default with new built-in templates `NoteTemplate` and `NoteLinkTemplate` which use `NoteAnnotation`, `NoteEntity` and `NoteLink` template components; + * Support annotation elements in `SelectionActionEstablishLink` and new `SelectionActionAnnotate` components; + * Support annotation links in `LinkActionDelete`, `LinkActionMoveEndpoint` components. +- Support user-resizable element templates with `ElementSize` template state property: + * Resizable elements display "box with handles" in the `Halo` to change the size; + * Changed element sizes are captured and restored by `RestoreGeometry` command. - Add `EditorController.applyAuthoringChanges()` method to apply current authoring changes to the diagram (i.e. change entity data, delete relations, etc) and reset the change state to be empty. #### ⏱ Performance @@ -21,11 +28,14 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p * Subscribe to canvas `changeTransform` event when using `CanvasApi.metrics` to convert between coordinates; * Subscribe to canvas `resize` event to track viewport size; * Subscribe to `changeCells` event from `DiagramModel` to track graph content changes. +- Add `TemplateProps.onlySelected` flag to use in the element templates to track if the element is the only one selected without performance penalty. #### 💅 Polish - Make dialogs fill the available viewport when the viewport width is small: * This is controlled by new CSS property `--reactodia-dialog-viewport-breakpoint-s` with default value `600px` which makes dialog fill the viewport if the available width is less or equal to that value. - Allow to override base z-index level for workspace components with a set z-index value via `--reactodia-z-index-base` CSS property; +- Make `Halo` margin configurable via CSS property `--reactodia-selection-single-box-margin`. +- Highlight link path in `HaloLink` with `--reactodia-selection-link-color` color by default. - Add `changeTransform` event to `CanvasApi.events` which triggers on `CanvasApi.metrics.getTransform()` changes, i.e. when coordinate mapping changes due to scale or canvas size is re-adjusted. - Add `DiagramModel.cellsVersion` property which updates on every element or link addition/removal/reordering to be able to subscribe to `changeCells` event with `useSyncStore()` hook. - Deprecate `canvasWidgets` prop on `DefaultWorkspace` and `ClassicWorkspace` in favor of passing widgets directly as children. @@ -33,12 +43,18 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p * All existing properties, methods and commands works as before but use element template state as storage for expanded state; * `changeExpanded` event is removed from element events, use `changeElementState` event instead; * When exporting the diagram the expanded state is serialized only with `elementState` while using `isExpanded` property when importing the diagram for backward compatibility. +- Introduce `ElementTemplate.supports` property for templates to tell its capabilities such as ability to expand/collapse or resized by user. - Move "expand/collapse on double click" global element behavior to `StandardEntity` and `ClassicEntity` implementation only. +- Add `setTemplateProperty()` utility function to easily set or unset template state property. #### 🐛 Fixed - Fix `HaloLink` and visual authoring link path highlight being rendered on top on elements by placing it onto `overLinkGeometry` widget layer instead. - Fix element template state not being restored when ungrouping entities. - Fix missing element decorations after re-importing the same diagram. +- Fix `DraggableHandle` to avoid using stale `onDragHandle` and `onEndDragHandle` prop values. + +#### 🔧 Maintenance +- Use small subset of [carbon design icons](https://github.com/carbon-design-system/carbon-icons) for various buttons. ## [0.30.1] - 2025-06-27 #### 🐛 Fixed diff --git a/THIRDPARTY.md b/THIRDPARTY.md index 7a7b27a8..6838a749 100644 --- a/THIRDPARTY.md +++ b/THIRDPARTY.md @@ -8,6 +8,9 @@ MIT License: CC-BY-4.0 - VSCode Codicons (unmodified SVG icons): https://github.com/microsoft/vscode-codicons/blob/main/LICENSE +Apache License (Version 2.0, January 2004) + - Carbon Design System Icons (unmodified SVG icons): https://github.com/carbon-design-system/carbon-icons + ### The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy @@ -27,3 +30,179 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +### Apache License (Version 2.0, January 2004) + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/eslint.config.mjs b/eslint.config.mjs index 623d47b4..0cde59f9 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -60,6 +60,7 @@ export default tseslint.config( '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-var-requires': 'off', '@typescript-eslint/prefer-promise-reject-errors': 'off', + '@typescript-eslint/require-await': 'off', '@typescript-eslint/unbound-method': ['warn', { ignoreStatic: true, }], diff --git a/examples/styleCustomization.tsx b/examples/styleCustomization.tsx index 965c7f71..b66e548c 100644 --- a/examples/styleCustomization.tsx +++ b/examples/styleCustomization.tsx @@ -59,7 +59,11 @@ function StyleCustomizationExample() { } return undefined; }, - linkTemplateResolver: type => DoubleArrowLinkTemplate, + linkTemplateResolver: type => { + if (!type.startsWith('urn:reactodia:')) { + return DoubleArrowLinkTemplate; + } + }, }} menu={}> diff --git a/i18n/i18n.schema.json b/i18n/i18n.schema.json index 7f34b752..af07e03f 100644 --- a/i18n/i18n.schema.json +++ b/i18n/i18n.schema.json @@ -57,7 +57,8 @@ "set_entity_group_items.title": { "$ref": "#/$defs/Value" }, "set_link_state.title": { "$ref": "#/$defs/Value" }, "set_relation_data.title": { "$ref": "#/$defs/Value" }, - "set_relation_group_items.title": { "$ref": "#/$defs/Value" } + "set_relation_group_items.title": { "$ref": "#/$defs/Value" }, + "transform_elements.title": { "$ref": "#/$defs/Value" } } }, "connections_menu": { @@ -186,6 +187,7 @@ "$ref": "#/$defs/Group", "additionalProperties": false, "properties": { + "delete_annotation.title": { "$ref": "#/$defs/Value" }, "delete_relation.title": { "$ref": "#/$defs/Value" }, "delete_relation.title_disabled": { "$ref": "#/$defs/Value" }, "edit_relation.title": { "$ref": "#/$defs/Value" }, @@ -203,6 +205,21 @@ "toggle_expand.title": { "$ref": "#/$defs/Value" } } }, + "note_annotation": { + "$ref": "#/$defs/Group", + "additionalProperties": false, + "properties": { + "change_text.command": { "$ref": "#/$defs/Value" }, + "style_align_center.title": { "$ref": "#/$defs/Value" }, + "style_align_left.title": { "$ref": "#/$defs/Value" }, + "style_align_right.title": { "$ref": "#/$defs/Value" }, + "style_bold.title": { "$ref": "#/$defs/Value" }, + "style_color_variant.title": { "$ref": "#/$defs/Value" }, + "style_italic.title": { "$ref": "#/$defs/Value" }, + "style_strikethrough.title": { "$ref": "#/$defs/Value" }, + "style_underline.title": { "$ref": "#/$defs/Value" } + } + }, "overlay_controller": { "$ref": "#/$defs/Group", "additionalProperties": false, @@ -274,6 +291,8 @@ "properties": { "add_to_filter.title": { "$ref": "#/$defs/Value" }, "anchor.title": { "$ref": "#/$defs/Value" }, + "annotate.defaultContent": { "$ref": "#/$defs/Value" }, + "annotate.title": { "$ref": "#/$defs/Value" }, "connections.title": { "$ref": "#/$defs/Value" }, "establish_relation.title": { "$ref": "#/$defs/Value" }, "establish_relation.title_disabled": { "$ref": "#/$defs/Value" }, diff --git a/i18n/translations/en.reactodia-translation.json b/i18n/translations/en.reactodia-translation.json index 2fa8b07f..f2825a62 100644 --- a/i18n/translations/en.reactodia-translation.json +++ b/i18n/translations/en.reactodia-translation.json @@ -38,7 +38,8 @@ "set_entity_group_items.title": "Set entity group items", "set_link_state.title": "Change link state", "set_relation_data.title": "Set relation link data", - "set_relation_group_items.title": "Set relation group items" + "set_relation_group_items.title": "Set relation group items", + "transform_elements.title": "Resize elements" }, "connections_menu": { "all_link.label": "All", @@ -127,6 +128,7 @@ "title_extra": "Types: {{entityTypes}}" }, "link_action": { + "delete_annotation.title": "Remove annotation link", "delete_relation.title": "Delete relation", "delete_relation.title_disabled": "Cannot delete the relation", "edit_relation.title": "Edit relation", @@ -139,6 +141,17 @@ "toggle_collapse.title": "Collapse navigator", "toggle_expand.title": "Expand navigator" }, + "note_annotation": { + "change_text.command": "Change annotation text", + "style_align_center.title": "Align center", + "style_align_left.title": "Align left", + "style_align_right.title": "Align right", + "style_bold.title": "Bold", + "style_color_variant.title": "Color variant: {{variant}}", + "style_italic.title": "Italic", + "style_strikethrough.title": "Strikethrough", + "style_underline.title": "Underline" + }, "overlay_controller": { "multiple_tasks_in_progress": "Multiple tasks are in progress", "unknown_error": "Unknown error occurred" @@ -187,6 +200,8 @@ "selection_action": { "add_to_filter.title": "Search for connected elements", "anchor.title": "Jump to resource", + "annotate.defaultContent": "Annotation", + "annotate.title": "Add annotation to this element", "connections.title": "Navigate to connected elements", "expand.collapse_command": "Collapse elements", "expand.expand_command": "Expand elements", diff --git a/images/carbon-design/text--align--center.svg b/images/carbon-design/text--align--center.svg new file mode 100644 index 00000000..5ae2fd50 --- /dev/null +++ b/images/carbon-design/text--align--center.svg @@ -0,0 +1 @@ +align--center diff --git a/images/carbon-design/text--align--left.svg b/images/carbon-design/text--align--left.svg new file mode 100644 index 00000000..077c5e8d --- /dev/null +++ b/images/carbon-design/text--align--left.svg @@ -0,0 +1 @@ +align--left diff --git a/images/carbon-design/text--align--right.svg b/images/carbon-design/text--align--right.svg new file mode 100644 index 00000000..0f284c9d --- /dev/null +++ b/images/carbon-design/text--align--right.svg @@ -0,0 +1 @@ +align--right diff --git a/images/carbon-design/text--bold.svg b/images/carbon-design/text--bold.svg new file mode 100644 index 00000000..baa6d622 --- /dev/null +++ b/images/carbon-design/text--bold.svg @@ -0,0 +1 @@ +text-bold diff --git a/images/carbon-design/text--italic.svg b/images/carbon-design/text--italic.svg new file mode 100644 index 00000000..68466f5b --- /dev/null +++ b/images/carbon-design/text--italic.svg @@ -0,0 +1 @@ +text-italic diff --git a/images/carbon-design/text--strikethrough.svg b/images/carbon-design/text--strikethrough.svg new file mode 100644 index 00000000..5835af52 --- /dev/null +++ b/images/carbon-design/text--strikethrough.svg @@ -0,0 +1 @@ +text--strikethrough \ No newline at end of file diff --git a/images/carbon-design/text--underline.svg b/images/carbon-design/text--underline.svg new file mode 100644 index 00000000..c286acde --- /dev/null +++ b/images/carbon-design/text--underline.svg @@ -0,0 +1 @@ +text-underline diff --git a/src/data/schema.ts b/src/data/schema.ts index ddf0d143..f80641d9 100644 --- a/src/data/schema.ts +++ b/src/data/schema.ts @@ -29,11 +29,16 @@ export const PlaceholderRelationType: LinkTypeIri = 'urn:reactodia:newLink'; export enum TemplateProperties { /** * Element state property to display the element as expanded - * (if supported by its element template). + * (if element template supports expanded state). * * @see {@link Element.isExpanded} */ Expanded = 'urn:reactodia:expanded', + /** + * Element state property for user-modifiable template size + * (if element template supports changing its size). + */ + ElementSize = 'urn:reactodia:elementSize', /** * Element state property to mark some element data properties as "pinned", * i.e. displayed even if element is collapsed. @@ -61,6 +66,19 @@ export enum TemplateProperties { * of multiple items displayed with pagination. */ GroupPageSize = 'urn:reactodia:groupPageSize', + /** + * Element state property for the annotation content. + * + * @see {@link AnnotationContent} + */ + AnnotationContent = 'urn:reactodia:annotationContent', + /** + * Element or link state property to select a color variant for its style + * from a predefined list. + * + * @see {@link ColorVariant} + */ + ColorVariant = 'urn:reactodia:colorVariant', } /** @@ -72,3 +90,70 @@ export enum TemplateProperties { export interface PinnedProperties { readonly [propertyId: string]: boolean; } + +/** + * Annotation content for the template state property + * {@link TemplateProperties.AnnotationContent}. + * + * @see {@link TemplateProperties.AnnotationContent} + */ +export interface AnnotationContent { + /** + * Content type: plain text with specified styles. + */ + readonly type: 'plaintext'; + /** + * Plain text content without any formatting. + */ + readonly text: string; + /** + * Styles for the whole text content. + */ + readonly style?: AnnotationTextStyle; +} + +/** + * Subset of supported styles for the {@link AnnotationContent annotation text content}. + */ +export type AnnotationTextStyle = Pick< + React.CSSProperties, + 'fontStyle' | 'fontWeight' | 'textDecorationLine' | 'textAlign' +>; + +/** + * Color variant from a predefined list of theme colors. + * + * @see {@link TemplateProperties.ColorVariant} + */ +export type ColorVariant = + 'default' | 'primary' | 'success' | 'info' | 'warning' | 'danger'; + +export const DefaultColorVariants: readonly ColorVariant[] = [ + 'default', + 'primary', + 'success', + 'info', + 'warning', + 'danger', +]; + +/** + * Utility function to set optional {@link TemplateProperties template property} value. + * + * If the `value` is `undefined`, the property will be removed from the `state`, + * otherwise the new value will be set. + */ +export function setTemplateProperty( + state: { readonly [propertyId: string]: unknown } | undefined, + propertyId: string, + value: T | undefined +): { readonly [propertyId: string]: unknown } | undefined { + if (value !== undefined) { + return state?.[propertyId] === value + ? state : {...state, [propertyId]: value}; + } else if (state?.[propertyId] !== undefined) { + const {[propertyId]: _, ...withoutProperty} = state; + return withoutProperty; + } + return state; +} diff --git a/src/diagram/commands.ts b/src/diagram/commands.ts index e77e58ba..4d524f50 100644 --- a/src/diagram/commands.ts +++ b/src/diagram/commands.ts @@ -1,20 +1,20 @@ import { TranslatedText } from '../coreUtils/i18n'; import type { LinkTypeIri } from '../data/model'; -import { TemplateProperties } from '../data/schema'; +import { TemplateProperties, setTemplateProperty } from '../data/schema'; import type { CanvasApi } from './canvasApi'; import type { Element, ElementTemplateState, Link, LinkTemplateState, LinkTypeVisibility, } from './elements'; import { - SizeProvider, Vector, boundsOf, isPolylineEqual, calculateAveragePosition, + Size, SizeProvider, Vector, boundsOf, isPolylineEqual, calculateAveragePosition, } from './geometry'; import { Command } from './history'; import type { DiagramModel, GraphStructure } from './model'; /** - * Command to restore element positions and link geometry (vertices) on a canvas. + * Command to restore element positions and sizes, link geometry (vertices) on a canvas. * * **Example**: * ```ts @@ -32,7 +32,11 @@ export class RestoreGeometry implements Command { private static _title = TranslatedText.text('commands.restore_geometry.title'); private constructor( - private elementState: ReadonlyArray<{ element: Element; position: Vector }>, + private elementState: ReadonlyArray<{ + element: Element; + position: Vector; + size: Size | undefined; + }>, private linkState: ReadonlyArray<{ link: Link; vertices: ReadonlyArray }>, ) {} @@ -52,7 +56,11 @@ export class RestoreGeometry implements Command { links: ReadonlyArray, ): RestoreGeometry { return new RestoreGeometry( - elements.map(element => ({element, position: element.position})), + elements.map(element => ({ + element, + position: element.position, + size: getElementSize(element), + })), links.map(link => ({link, vertices: link.vertices})), ); } @@ -79,7 +87,10 @@ export class RestoreGeometry implements Command { filterOutUnchanged(): RestoreGeometry { return new RestoreGeometry( this.elementState.filter( - ({element, position}) => !Vector.equals(element.position, position) + ({element, position, size}) => !( + Vector.equals(element.position, position) && + getElementSize(element) === size + ) ), this.linkState.filter( ({link, vertices}) => !isPolylineEqual(link.vertices, vertices) @@ -95,8 +106,11 @@ export class RestoreGeometry implements Command { // restore in reverse order to workaround position changed event // handling in EmbeddedLayer inside nested elements // (child's position change causes group to resize or move itself) - for (const {element, position} of [...this.elementState].reverse()) { + for (const {element, position, size} of [...this.elementState].reverse()) { element.setPosition(position); + element.setElementState( + setTemplateProperty(element.elementState, TemplateProperties.ElementSize, size) + ); } for (const {link, vertices} of this.linkState) { link.setVertices(vertices); @@ -105,6 +119,10 @@ export class RestoreGeometry implements Command { } } +function getElementSize(element: Element): Size | undefined { + return element.elementState?.[TemplateProperties.ElementSize] as Size | undefined; +} + /** * Command to restore single link geometry (vertices) on a canvas. * diff --git a/src/diagram/customization.ts b/src/diagram/customization.ts index 28d5773a..2a366239 100644 --- a/src/diagram/customization.ts +++ b/src/diagram/customization.ts @@ -64,6 +64,30 @@ export interface ElementTemplate { * **Note**: this should be a pure function, not a React component by itself. */ readonly renderElement: (props: TemplateProps) => React.ReactNode; + /** + * Describes a set of {@link TemplateProperties template state properties} + * supported by the template. + * + * These capabilities are used by other components (e.g. selection actions, etc) + * while the template itself, however, can read and change any template property + * as needed. + * + * **Example**: + * Element template which supports being expanded and resized + * by the user: + * ```ts + * const MyTemplate: Reactodia.ElementTemplate = { + * renderElement: props => { ... }, + * supports: { + * [Reactodia.TemplateProperties.Expanded]: true, + * [Reactodia.TemplateProperties.ElementSize]: true, + * } + * } + * ``` + * + * @default {} + */ + readonly supports?: Record; } /** @@ -102,6 +126,12 @@ export interface TemplateProps { * Same as {@link Element.elementState}. */ readonly elementState?: ElementTemplateState; + /** + * Whether the element is the only selected cell on the canvas. + * + * @see {@link DiagramModel.selection} + */ + readonly onlySelected: boolean; } /** diff --git a/src/diagram/elementLayer.tsx b/src/diagram/elementLayer.tsx index 377b70ae..2cd474ad 100644 --- a/src/diagram/elementLayer.tsx +++ b/src/diagram/elementLayer.tsx @@ -131,6 +131,22 @@ export class ElementLayer extends React.Component { this.listener.listen(model.events, 'changeCellOrder', () => { this.requestRedrawAll(RedrawFlags.None); }); + this.listener.listen(model.events, 'changeSelection', ({previous}) => { + const previousCell = previous.length === 1 ? previous[0] : undefined; + const nextSingle = model.selection.length === 1 ? model.selection[0] : undefined; + + const previousElement = previousCell instanceof Element ? previousCell : undefined; + const nextElement = nextSingle instanceof Element ? nextSingle : undefined; + + if (nextElement !== previousElement) { + if (previousElement) { + this.requestRedraw(previousElement, RedrawFlags.RecomputeTemplate); + } + if (nextElement) { + this.requestRedraw(nextElement, RedrawFlags.RecomputeTemplate); + } + } + }); this.listener.listen(model.events, 'elementEvent', ({data}) => { const invalidatesTemplate = data.changeElementState; if (invalidatesTemplate) { @@ -243,6 +259,8 @@ function applyRedrawRequests( if (batch.forAll === RedrawFlags.None && batch.requests.size === 0) { return previous; } + const selectedCell = model.selection.length === 1 ? model.selection[0] : undefined; + const selectedElement = selectedCell instanceof Element ? selectedCell : undefined; const computed = new Map(); for (const element of model.elements) { const elementId = element.id; @@ -255,7 +273,8 @@ function applyRedrawRequests( templateProps: // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison (request & RedrawFlags.RecomputeTemplate) === RedrawFlags.RecomputeTemplate - ? computeTemplateProps(state.element) : state.templateProps, + ? computeTemplateProps(state.element, selectedElement) + : state.templateProps, blurred: // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison (request & RedrawFlags.RecomputeBlurred) === RedrawFlags.RecomputeBlurred @@ -267,7 +286,7 @@ function applyRedrawRequests( } else { computed.set(element, { element, - templateProps: computeTemplateProps(element), + templateProps: computeTemplateProps(element, selectedElement), blurred: computeIsBlurred(element, view), }); } @@ -276,12 +295,13 @@ function applyRedrawRequests( return computed; } -function computeTemplateProps(element: Element): TemplateProps { +function computeTemplateProps(element: Element, selectedElement: Element | undefined): TemplateProps { return { elementId: element.id, element, isExpanded: element.isExpanded, elementState: element.elementState, + onlySelected: element === selectedElement, }; } diff --git a/src/diagram/elements.ts b/src/diagram/elements.ts index d2651e9b..efa197ce 100644 --- a/src/diagram/elements.ts +++ b/src/diagram/elements.ts @@ -1,7 +1,7 @@ import { EventSource, Events, PropertyChange } from '../coreUtils/events'; import { LinkTypeIri } from '../data/model'; -import { TemplateProperties } from '../data/schema'; +import { TemplateProperties, setTemplateProperty } from '../data/schema'; import { generate128BitID } from '../data/utils'; import { Vector, isPolylineEqual } from './geometry'; @@ -184,12 +184,9 @@ export abstract class Element { * not equal to the previous one. */ setExpanded(value: boolean): void { - if (value && !this._elementState?.[TemplateProperties.Expanded]) { - this.setElementState({...this._elementState, [TemplateProperties.Expanded]: true}); - } else if (!value && this._elementState?.[TemplateProperties.Expanded]) { - const {[TemplateProperties.Expanded]: _, ...withoutExpanded} = this._elementState; - this.setElementState(withoutExpanded); - } + this.setElementState( + setTemplateProperty(this._elementState, TemplateProperties.Expanded, value ? true : undefined) + ); } /** diff --git a/src/diagram/linkLayer.tsx b/src/diagram/linkLayer.tsx index 6129fd0b..d5dd4fbf 100644 --- a/src/diagram/linkLayer.tsx +++ b/src/diagram/linkLayer.tsx @@ -683,11 +683,11 @@ export class LinkMarkers extends React.Component { render() { const {renderingState} = this.props; - const defaultTemplate = renderingState.shared.defaultLinkTemplate; const markers: Array> = []; for (const [linkTypeId, template] of renderingState.getLinkTemplates()) { + const defaultTemplate = renderingState.shared.defaultLinkResolver(linkTypeId); const typeIndex = renderingState.ensureLinkTypeIndex(linkTypeId); if (template.markerSource) { diff --git a/src/diagram/renderingState.ts b/src/diagram/renderingState.ts index 5924c8e1..599923a9 100644 --- a/src/diagram/renderingState.ts +++ b/src/diagram/renderingState.ts @@ -115,8 +115,8 @@ export enum RenderingLayer { const FIRST_LAYER = RenderingLayer.Element; const LAST_LAYER = RenderingLayer.Overlay; -const DEFAULT_ELEMENT_TEMPLATE_RESOLVER: ElementTemplateResolver = types => undefined; -const DEFAULT_LINK_TEMPLATE_RESOLVER: LinkTemplateResolver = type => undefined; +const DEFAULT_ELEMENT_TEMPLATE_RESOLVER: ElementTemplateResolver = element => undefined; +const DEFAULT_LINK_TEMPLATE_RESOLVER: LinkTemplateResolver = linkTypeId => undefined; /** * Stores current rendering state for a single canvas. @@ -341,7 +341,7 @@ export class MutableRenderingState implements RenderingState { } resolved = mapped; } - return resolved ?? this.shared.defaultElementTemplate; + return resolved ?? this.shared.defaultElementResolver(element); } getElementShape(element: Element): ShapeGeometry { @@ -373,7 +373,7 @@ export class MutableRenderingState implements RenderingState { } const template = this.resolveLinkTemplate(linkTypeId) - ?? this.shared.defaultLinkTemplate; + ?? this.shared.defaultLinkResolver(linkTypeId); this.linkTemplates.set(linkTypeId, template); this.source.trigger('changeLinkTemplates', {source: this}); return template; diff --git a/src/diagram/sharedCanvasState.ts b/src/diagram/sharedCanvasState.ts index a3c7105d..01c61f1f 100644 --- a/src/diagram/sharedCanvasState.ts +++ b/src/diagram/sharedCanvasState.ts @@ -2,7 +2,8 @@ import * as React from 'react'; import { Events, EventSource, EventObserver, PropertyChange } from '../coreUtils/events'; -import { TemplateProperties } from '../data/schema'; +import type { LinkTypeIri } from '../data/model'; +import { TemplateProperties, setTemplateProperty } from '../data/schema'; import type { CanvasApi, CanvasDropEvent } from './canvasApi'; import type { ElementTemplate, LinkTemplate, RenameLinkProvider } from './customization'; @@ -56,8 +57,8 @@ export type CellHighlighter = (item: Element | Link) => boolean; /** @hidden */ export interface SharedCanvasStateOptions { - defaultElementTemplate: ElementTemplate; - defaultLinkTemplate: LinkTemplate; + defaultElementResolver: (element: Element) => ElementTemplate; + defaultLinkResolver: (linkType: LinkTypeIri) => LinkTemplate; defaultLayout: LayoutFunction; renameLinkProvider?: RenameLinkProvider; } @@ -81,13 +82,15 @@ export class SharedCanvasState { private _highlighter: CellHighlighter | undefined; /** - * Default element template to use as a fallback. + * Default element template resolver to use as a fallback + * (returns a default template for any element). */ - readonly defaultElementTemplate: ElementTemplate; + readonly defaultElementResolver: (element: Element) => ElementTemplate; /** - * Default link template to use as a fallback. + * Default link template resolver to use as a fallback + * (returns a default template for any link). */ - readonly defaultLinkTemplate: LinkTemplate; + readonly defaultLinkResolver: (linkTypeId: LinkTypeIri) => LinkTemplate; /** * Default layout algorithm function to use if it's not specified explicitly. */ @@ -100,10 +103,10 @@ export class SharedCanvasState { /** @hidden */ constructor(options: SharedCanvasStateOptions) { const { - defaultElementTemplate, defaultLinkTemplate, defaultLayout, renameLinkProvider, + defaultElementResolver, defaultLinkResolver, defaultLayout, renameLinkProvider, } = options; - this.defaultElementTemplate = defaultElementTemplate; - this.defaultLinkTemplate = defaultLinkTemplate; + this.defaultElementResolver = defaultElementResolver; + this.defaultLinkResolver = defaultLinkResolver; this.defaultLayout = defaultLayout; this.renameLinkProvider = renameLinkProvider; } @@ -193,22 +196,15 @@ export class RenameLinkToLinkStateProvider implements RenameLinkProvider { getLabel(link: Link): string | undefined { const {linkState} = link; - if ( - linkState && - Object.prototype.hasOwnProperty.call(linkState, TemplateProperties.CustomLabel) - ) { - const customLabel = linkState[TemplateProperties.CustomLabel]; - if (typeof customLabel === 'string') { - return customLabel; - } - } - return undefined; + const customLabel = linkState?.[TemplateProperties.CustomLabel]; + return typeof customLabel === 'string' ? customLabel : undefined; } setLabel(link: Link, label: string): void { - link.setLinkState({ - ...link.linkState, - [TemplateProperties.CustomLabel]: label.length === 0 ? undefined : label, - }); + link.setLinkState(setTemplateProperty( + link.linkState, + TemplateProperties.CustomLabel, + label.length === 0 ? undefined : label + )); } } diff --git a/src/editor/annotationCells.ts b/src/editor/annotationCells.ts new file mode 100644 index 00000000..6d493834 --- /dev/null +++ b/src/editor/annotationCells.ts @@ -0,0 +1,80 @@ +import type { LinkTypeIri } from '../data/model'; + +import { Element, Link } from '../diagram/elements'; + +import type { + SerializedElement, SerializableElementCell, ElementFromJsonOptions, + SerializedLink, SerializableLinkCell, LinkFromJsonOptions, +} from './serializedDiagram'; + +export class AnnotationElement extends Element { + static readonly fromJSONType = 'Annotation'; + + static fromJSON( + state: SerializedAnnotationElement, + options: ElementFromJsonOptions + ): AnnotationElement | undefined { + const {'@id': id, position, elementState} = state; + return new AnnotationElement({ + id, + position, + elementState: options.mapTemplateState(elementState), + }); + } + + toJSON(): SerializedAnnotationElement { + return { + '@type': 'Annotation', + '@id': this.id, + position: this.position, + elementState: this.elementState, + }; + } +} + +AnnotationElement satisfies SerializableElementCell; + +export interface SerializedAnnotationElement extends SerializedElement { + '@type': 'Annotation'; +} + +export class AnnotationLink extends Link { + static readonly typeId: LinkTypeIri = 'urn:reactodia:annotates'; + + protected getTypeId(): LinkTypeIri { + return AnnotationLink.typeId; + } + + static readonly fromJSONType = 'AnnotationLink'; + + static fromJSON( + state: SerializedAnnotationLink, + options: LinkFromJsonOptions + ): AnnotationLink | undefined { + const {'@id': id, vertices, linkState} = state; + return new AnnotationLink({ + id, + sourceId: options.source.id, + targetId: options.target.id, + vertices, + linkState: options.mapTemplateState(linkState), + }); + } + + toJSON(): SerializedAnnotationLink { + return { + '@type': 'AnnotationLink', + '@id': this.id, + source: {'@id': this.sourceId}, + target: {'@id': this.targetId}, + vertices: this.vertices, + linkState: this.linkState, + }; + } +} + +AnnotationLink satisfies SerializableLinkCell; + +export interface SerializedAnnotationLink extends SerializedLink { + '@type': 'AnnotationLink'; +} diff --git a/src/editor/dataDiagramModel.ts b/src/editor/dataDiagramModel.ts index af47bb47..fcabd602 100644 --- a/src/editor/dataDiagramModel.ts +++ b/src/editor/dataDiagramModel.ts @@ -20,6 +20,7 @@ import { DiagramModel, DiagramModelEvents, DiagramModelOptions, GraphStructure, } from '../diagram/model'; +import { AnnotationElement, AnnotationLink } from './annotationCells'; import { EntityElement, EntityGroup, EntityGroupItem, RelationLink, RelationGroup, RelationGroupItem, @@ -325,7 +326,7 @@ export class DataDiagramModel extends DiagramModel implements DataGraphStructure * * **Unstable**: this feature is likely to be changed in the future. * - * @default [EntityElement, EntityGroup] + * @default [EntityElement, EntityGroup, AnnotationElement] */ elementCellTypes?: readonly SerializableElementCell[]; /** @@ -335,7 +336,7 @@ export class DataDiagramModel extends DiagramModel implements DataGraphStructure * * **Unstable**: this feature is likely to be changed in the future. * - * @default [RelationLink, RelationGroup] + * @default [RelationLink, RelationGroup, AnnotationLink] */ linkCellTypes?: readonly SerializableLinkCell[]; /** @@ -371,8 +372,8 @@ export class DataDiagramModel extends DiagramModel implements DataGraphStructure dataProvider, locale, diagram = emptyDiagram(), - elementCellTypes = [EntityElement, EntityGroup], - linkCellTypes = [RelationLink, RelationGroup], + elementCellTypes = [EntityElement, EntityGroup, AnnotationElement], + linkCellTypes = [RelationLink, RelationGroup, AnnotationLink], preloadedElements, preloadedLinks, validateLinks = false, diff --git a/src/editor/editorController.tsx b/src/editor/editorController.tsx index 41319ae5..da51bb47 100644 --- a/src/editor/editorController.tsx +++ b/src/editor/editorController.tsx @@ -10,6 +10,7 @@ import { Element, Link } from '../diagram/elements'; import { Command } from '../diagram/history'; import { GraphStructure } from '../diagram/model'; +import { AnnotationLink } from './annotationCells'; import { AuthoringState, AuthoringEvent, TemporaryState, } from './authoringState'; @@ -247,8 +248,9 @@ export class EditorController { * Removes the specified diagram cells from the diagram * and discards any associated graph authoring state. * - * The links are only removed when its a new relation - * added by the graph authoring. + * If the link is a {@link RelationLink relation}, it will be removed + * only if it's marked as "added" in the graph + * {@link EditorController.authoringState authoring state}. * * The operation puts a command to the {@link DiagramModel.history command history}. */ @@ -271,6 +273,10 @@ export class EditorController { this.deleteRelation(relation); } } + + if (!(item instanceof RelationLink || item instanceof RelationGroup)) { + this.model.removeLink(item.id); + } } } diff --git a/src/editor/overlayController.tsx b/src/editor/overlayController.tsx index d47b1a8c..6083efe6 100644 --- a/src/editor/overlayController.tsx +++ b/src/editor/overlayController.tsx @@ -467,7 +467,7 @@ function readOverlayProperty( export function OverlaySupport(props: { overlay: OverlayController; }) { - const { overlay } = props; + const {overlay} = props; const {canvas} = useCanvas(); const internalApi = withInternalApi(overlay)[OverlayInternalApi]; diff --git a/src/editor/serializedDiagram.ts b/src/editor/serializedDiagram.ts index 62f605b1..e79a0562 100644 --- a/src/editor/serializedDiagram.ts +++ b/src/editor/serializedDiagram.ts @@ -1,7 +1,9 @@ import type { ReadonlyHashMap } from '@reactodia/hashmap'; import { ElementIri, ElementModel, LinkKey, LinkModel, LinkTypeIri } from '../data/model'; -import { DiagramContextV1, PlaceholderRelationType, TemplateProperties } from '../data/schema'; +import { + DiagramContextV1, PlaceholderRelationType, TemplateProperties, setTemplateProperty, +} from '../data/schema'; import { Element, ElementTemplateState, Link, LinkTemplateState, LinkTypeVisibility } from '../diagram/elements'; import { Vector } from '../diagram/geometry'; @@ -343,24 +345,7 @@ export function markLayoutOnly( linkState: LinkTemplateState | undefined, value: boolean ): LinkTemplateState | undefined { - const previous = ( - linkState && - Object.prototype.hasOwnProperty.call(linkState, TemplateProperties.LayoutOnly) && - Boolean(linkState[TemplateProperties.LayoutOnly]) - ); - if (previous && !value) { - const { - [TemplateProperties.LayoutOnly]: layoutOnly, - ...withoutLayoutOnly - } = linkState; - return withoutLayoutOnly; - } else if (!previous && value) { - return { - ...linkState, - [TemplateProperties.LayoutOnly]: true, - }; - } - return linkState; + return setTemplateProperty(linkState, TemplateProperties.LayoutOnly, value ? true : undefined); } function hasToJSON(instance: object): instance is { toJSON(): { ['@type']?: unknown } } { diff --git a/src/templates/classicTemplate.tsx b/src/templates/classicTemplate.tsx index 982320c1..cd14f267 100644 --- a/src/templates/classicTemplate.tsx +++ b/src/templates/classicTemplate.tsx @@ -4,6 +4,7 @@ import * as React from 'react'; import { useKeyedSyncStore } from '../coreUtils/keyedObserver'; import { ElementModel, PropertyTypeIri } from '../data/model'; +import { TemplateProperties } from '../data/schema'; import { setElementExpanded } from '../diagram/commands'; import { ElementTemplate, TemplateProps } from '../diagram/customization'; import { EntityElement } from '../editor/dataElements'; @@ -21,6 +22,9 @@ import { useWorkspace } from '../workspace/workspaceContext'; */ export const ClassicTemplate: ElementTemplate = { renderElement: props => , + supports: { + [TemplateProperties.Expanded]: true, + }, }; /** diff --git a/src/templates/noteAnnotation.tsx b/src/templates/noteAnnotation.tsx new file mode 100644 index 00000000..b258661c --- /dev/null +++ b/src/templates/noteAnnotation.tsx @@ -0,0 +1,389 @@ +import * as React from 'react'; +import cx from 'clsx'; + +import { TranslatedText, useTranslation } from '../coreUtils/i18n'; + +import type { PropertyTypeIri } from '../data/model'; +import { + TemplateProperties, type AnnotationContent, type AnnotationTextStyle, + type ColorVariant, DefaultColorVariants, setTemplateProperty, +} from '../data/schema'; + +import { useCanvas } from '../diagram/canvasApi'; +import { setElementState } from '../diagram/commands'; +import type { + ElementTemplate, LinkTemplate, LinkTemplateProps, TemplateProps, +} from '../diagram/customization'; +import { ElementDecoration } from '../diagram/elementLayer'; +import { Rect, Size, boundsOf } from '../diagram/geometry'; +import { Command } from '../diagram/history'; + +import { AnnotationElement, AnnotationLink } from '../editor/annotationCells'; +import { EntityElement } from '../editor/dataElements'; + +import { ContentEditablePlaintext } from '../widgets/utility/contentEditablePlaintext'; +import { useAuthoredEntity } from '../widgets/visualAuthoring/authoredEntity'; + +import { useWorkspace } from '../workspace/workspaceContext'; + +import { DefaultLink } from './defaultLinkTemplate'; + +/** + * Element template to display an {@link AnnotationElement} on a canvas. + * + * Uses {@link NoteAnnotation} component to render an annotation element. + * + * @category Constants + */ +export const NoteTemplate: ElementTemplate = { + renderElement: props => { + if (props.element instanceof AnnotationElement) { + return ; + } else if (props.element instanceof EntityElement) { + return ; + } + return null; + }, + supports: { + [TemplateProperties.ColorVariant]: true, + [TemplateProperties.ElementSize]: true, + }, +}; + +/** + * Props for {@link NoteAnnotation} component. + * + * @see {@link NoteAnnotation} + */ +export interface NoteAnnotationProps extends TemplateProps {} + +/** + * Displays an {@link AnnotationElement} in a form of a editable plaintext note. + * + * The template supports displaying any element but always store its content + * in the {@link Element.elementState element state}. + * + * The template supports the following template state: + * - {@link TemplateProperties.ElementSize} + * - {@link TemplateProperties.AnnotationText} + * + * @category Components + * @see {@link NoteTemplate} + */ +export function NoteAnnotation(props: NoteAnnotationProps) { + const {element, elementState} = props; + const {model} = useCanvas(); + const content = elementState?.[TemplateProperties.AnnotationContent] as AnnotationContent | undefined; + return ( + { + model.history.execute(Command.compound( + TranslatedText.text('note_annotation.change_text.command'), + [ + setElementState(element, setTemplateProperty( + element.elementState, + TemplateProperties.AnnotationContent, + changedContent + )) + ], + )); + }} + /> + ); +} + +/** + * Props for {@link NoteEntity} component. + * + * @see {@link NoteEntity} + */ +export interface NoteEntityProps extends TemplateProps { + /** + * @default "http://www.w3.org/ns/oa#bodyValue" + */ + textProperty?: PropertyTypeIri; +} + +/** + * Displays an {@link EntityElement} in a form of a editable plaintext note. + * + * The template supports displaying any element but will be empty + * for any element cell type other than {@link EntityElement}. + * + * The property IRI for note content can be configured with + * {@link NoteEntityProps.textProperty}; by default it uses + * `oa:bodyValue` from [Web Annotation Ontology](https://www.w3.org/ns/oa). + * + * The template supports the following template state: + * - {@link TemplateProperties.ElementSize} + * + * @category Components + * @see {@link NoteTemplate} + */ +export function NoteEntity(props: NoteEntityProps) { + const { + element, + textProperty = 'http://www.w3.org/ns/oa#bodyValue', + } = props; + + const {model, editor, translation: t} = useWorkspace(); + + const data = element instanceof EntityElement ? element.data : undefined; + const entityContext = useAuthoredEntity(data, true); + + const content = React.useMemo((): AnnotationContent | undefined => { + const values = data?.properties[textProperty]; + if (values && values.length > 0) { + const texts = t.selectValues(values, model.language); + const text = texts.filter(v => v.termType === 'Literal').map(v => v.value).join('\n'); + return {type: 'plaintext', text}; + } else { + return undefined; + } + }, [data]); + + return ( + { + if (data) { + editor.changeEntity(data.id, { + ...data, + properties: { + ...data.properties, + [textProperty]: [model.factory.literal(changedContent.text)], + } + }); + } + }} + /> + ); +} + +interface NoteAnnotationViewProps extends TemplateProps { + readOnly?: boolean; + content: AnnotationContent | undefined; + setContent: (changedContent: AnnotationContent) => void; +} + +const CLASS_NAME = 'reactodia-note-annotation'; + +function NoteAnnotationView(props: NoteAnnotationViewProps) { + const {element, elementState, onlySelected, readOnly, content, setContent} = props; + const {canvas, model} = useCanvas(); + + const [isEditing, setEditing] = React.useState(false); + + const size = elementState?.[TemplateProperties.ElementSize] as Size | undefined; + const colorVariant = + elementState?.[TemplateProperties.ColorVariant] as ColorVariant | undefined; + const plaintext = (content?.type === 'plaintext' ? content : undefined) ?? { + type: 'plaintext', + text: '', + }; + + return ( + <> +
{ + e.preventDefault(); + e.stopPropagation(); + if (readOnly) { + return; + } + if (canvas.getScale() < 1) { + await canvas.centerTo( + Rect.center(boundsOf(element, canvas.renderingState)), + {scale: 1, animate: true} + ); + } + setEditing(true); + }}> + { + // Delay executing command to change text to avoid putting it into + // "Move elements and links" batch from PaperArea due to click on canvas + requestAnimationFrame(() => setContent({...plaintext, text: changedText})); + }} + isEditing={isEditing} + setEditing={setEditing} + /> +
+ {onlySelected && ( + + { + setContent({...plaintext, style: changedStyle}); + }} + variant={colorVariant} + setVariant={changedVariant => { + model.history.execute(setElementState( + element, + setTemplateProperty( + element.elementState, + TemplateProperties.ColorVariant, + changedVariant + ) + )); + }} + /> + + )} + + ); +} + +function NoteStyleControls(props: { + style: AnnotationTextStyle | undefined; + setStyle: (changedStyle: AnnotationTextStyle) => void; + variant: ColorVariant | undefined; + setVariant: (changedVariant: ColorVariant | undefined) => void; +}) { + const {style, setStyle, variant: selectedVariant = 'default', setVariant} = props; + const t = useTranslation(); + const { + fontStyle, + fontWeight, + textDecorationLine, + textAlign = 'center', + } = style ?? {}; + const preventPropagation = (e: React.MouseEvent) => e.stopPropagation(); + const buttonProps = { + type: 'button', + onPointerDown: preventPropagation, + } as const satisfies React.HTMLProps; + return ( +
+
+
+
+
+
+ {DefaultColorVariants.map(variant => + + )} +
+
+ ); +} + +export const NoteLinkTemplate: LinkTemplate = { + markerTarget: { + fill: 'var(--reactodia-canvas-background-color)', + stroke: 'var(--reactodia-color-emphasis-500)', + strokeWidth: 2, + d: 'M 7 2 a 5 5 0 1 0 0.0001 0 Z', + width: 14, + height: 14, + }, + renderLink: props => { + if (props.link instanceof AnnotationLink) { + return ; + } + return null; + }, +}; + +const LINK_CLASS = 'reactodia-note-link'; + +export function NoteLink(props: LinkTemplateProps) { + return ( + + ); +} diff --git a/src/templates/standardTemplate.tsx b/src/templates/standardTemplate.tsx index 4a07c783..1fc6a7fb 100644 --- a/src/templates/standardTemplate.tsx +++ b/src/templates/standardTemplate.tsx @@ -43,6 +43,9 @@ export const StandardTemplate: ElementTemplate = { return null; } }, + supports: { + [TemplateProperties.Expanded]: true, + }, }; /** diff --git a/src/widgets/annotation/annotationLinkMover.tsx b/src/widgets/annotation/annotationLinkMover.tsx new file mode 100644 index 00000000..82b0d824 --- /dev/null +++ b/src/widgets/annotation/annotationLinkMover.tsx @@ -0,0 +1,93 @@ +import * as React from 'react'; + +import { useCanvas } from '../../diagram/canvasApi'; +import { Element, Link } from '../../diagram/elements'; +import { DiagramModel } from '../../diagram/model'; + +import { AnnotationElement, AnnotationLink } from '../../editor/annotationCells'; + +import { DragLinkMover, type DragLinkOperation, type DragLinkConnection } from '../utility/dragLinkMover'; + +export type AnnotationLinkOperation = DragLinkOperation; + +export function AnnotationLinkMover(props: { + operation: AnnotationLinkOperation; + onFinish: () => void; +}) { + const {operation, onFinish} = props; + const {model} = useCanvas(); + return ( + { + const link = new AnnotationLink({ + sourceId: source.id, + targetId: target.id, + vertices: original?.vertices, + linkState: original?.linkState, + }); + model.addLink(link); + return link; + }} + canConnect={async (source, link, target) => { + const allowed = ( + source instanceof AnnotationElement && + link instanceof AnnotationLink && + target !== undefined && + !model.getElementLinks(source).some(link => ( + link instanceof AnnotationLink && + link.sourceId === source.id && + link.targetId === target.id + )) + ); + return new AnnotationLinkConnection(allowed, model); + }} + onFinish={onFinish} + /> + ); +} + +class AnnotationLinkConnection implements DragLinkConnection { + constructor( + readonly allowed: boolean, + private readonly model: DiagramModel + ) {} + + async connect(source: Element, target: Element | undefined): Promise { + if (!target) { + return; + } + this.model.addLink(new AnnotationLink({sourceId: source.id, targetId: target.id})); + } + + async moveSource(link: Link, newSource: Element): Promise { + const batch = this.model.history.startBatch(); + this.model.removeLink(link.id); + const movedLink = new AnnotationLink({ + id: link.id, + sourceId: newSource.id, + targetId: link.targetId, + vertices: link.vertices, + linkState: link.linkState, + }); + this.model.addLink(movedLink); + batch.store(); + + this.model.setSelection([movedLink]); + } + + async moveTarget(link: Link, newTarget: Element): Promise { + const batch = this.model.history.startBatch(); + this.model.removeLink(link.id); + const movedLink = new AnnotationLink({ + id: link.id, + sourceId: link.sourceId, + targetId: newTarget.id, + vertices: link.vertices, + linkState: link.linkState, + }); + this.model.addLink(movedLink); + batch.store(); + + this.model.setSelection([movedLink]); + } +} diff --git a/src/widgets/annotation/annotationSupport.tsx b/src/widgets/annotation/annotationSupport.tsx new file mode 100644 index 00000000..1e39d32c --- /dev/null +++ b/src/widgets/annotation/annotationSupport.tsx @@ -0,0 +1,98 @@ +import * as React from 'react'; + +import { EventObserver } from '../../coreUtils/events'; + +import { TemplateProperties, type AnnotationContent } from '../../data/schema'; + +import { useCanvas } from '../../diagram/canvasApi'; +import { placeElementsAroundTarget } from '../../diagram/commands'; +import { Element } from '../../diagram/elements'; +import { Rect, type SizeProvider, Vector, boundsOf } from '../../diagram/geometry'; + +import { AnnotationElement, AnnotationLink } from '../../editor/annotationCells'; + +import { AnnotationTopic } from '../../workspace/commandBusTopic'; +import type { WorkspaceContext } from '../../workspace/workspaceContext'; + +import { AnnotationLinkMover, type AnnotationLinkOperation } from './annotationLinkMover'; + +export interface AnnotationCommands { + startDragOperation: { + readonly operation: AnnotationLinkOperation; + }; + createAnnotation: { + readonly targets: readonly Element[]; + readonly content?: AnnotationContent; + }; +} + +export function AnnotationSupport(props: Pick) { + const {getCommandBus} = props; + + const {canvas, model} = useCanvas(); + const [mover, setMover] = React.useState(null); + + React.useEffect(() => { + const commands = getCommandBus(AnnotationTopic); + const listener = new EventObserver(); + listener.listen(commands, 'startDragOperation', ({operation}) => { + setMover( + setMover(null)} + /> + ); + }); + listener.listen(commands, 'createAnnotation', ({targets, content}) => { + const outermost = getOutermostElement(targets, canvas.renderingState); + + const batch = model.history.startBatch(); + + const annotation = new AnnotationElement({ + elementState: content ? { + [TemplateProperties.AnnotationContent]: content, + } : undefined, + }); + model.addElement(annotation); + + if (outermost) { + annotation.setPosition(outermost.position); + canvas.renderingState.syncUpdate(); + batch.history.execute(placeElementsAroundTarget({ + elements: [annotation], + target: outermost, + graph: model, + sizeProvider: canvas.renderingState, + })); + } + + for (const element of targets) { + model.addLink(new AnnotationLink({ + sourceId: annotation.id, + targetId: element.id, + })); + } + + batch.store(); + }); + }, []); + + return ( + <> + {mover} + + ); +} + +function getOutermostElement(elements: readonly Element[], sizeProvider: SizeProvider): Element | undefined { + let maxDistance = 0; + let outermost: Element | undefined; + for (const element of elements) { + const bounds = boundsOf(element, sizeProvider); + const distance = Vector.length(Rect.center(bounds)); + if (distance >= maxDistance) { + maxDistance = distance; + outermost = element; + } + } + return outermost; +} diff --git a/src/widgets/annotation/index.ts b/src/widgets/annotation/index.ts new file mode 100644 index 00000000..cca81792 --- /dev/null +++ b/src/widgets/annotation/index.ts @@ -0,0 +1 @@ +export { type AnnotationCommands, AnnotationSupport } from './annotationSupport'; diff --git a/src/widgets/canvas.tsx b/src/widgets/canvas.tsx index 94c03d15..ac0e6d15 100644 --- a/src/widgets/canvas.tsx +++ b/src/widgets/canvas.tsx @@ -15,6 +15,8 @@ import { OverlaySupport } from '../editor/overlayController'; import { useWorkspace } from '../workspace/workspaceContext'; +import { AnnotationSupport } from './annotation'; + /** * Props for {@link Canvas} component. * @@ -88,7 +90,7 @@ const CLASS_NAME = 'reactodia-canvas'; * @category Components */ export function Canvas(props: CanvasProps) { - const {model, view, overlay} = useWorkspace(); + const {model, view, overlay, getCommandBus} = useWorkspace(); const { elementTemplateResolver, linkTemplateResolver, linkRouter, showScrollbars, zoomOptions, watermarkSvg, watermarkUrl, children, @@ -120,6 +122,7 @@ export function Canvas(props: CanvasProps) { watermarkUrl={watermarkUrl}> {children} + ); diff --git a/src/widgets/halo.tsx b/src/widgets/halo.tsx index fbc30fa1..ebd93ea5 100644 --- a/src/widgets/halo.tsx +++ b/src/widgets/halo.tsx @@ -1,17 +1,25 @@ import * as React from 'react'; +import cx from 'clsx'; import { AnyListener, EventObserver } from '../coreUtils/events'; import { useObservedProperty } from '../coreUtils/hooks'; +import { TranslatedText } from '../coreUtils/i18n'; + +import { TemplateProperties } from '../data/schema'; import { CanvasApi, useCanvas } from '../diagram/canvasApi'; +import { RestoreGeometry } from '../diagram/commands'; import { Element, ElementEvents } from '../diagram/elements'; -import { boundsOf } from '../diagram/geometry'; +import { Rect, boundsOf } from '../diagram/geometry'; +import { Command } from '../diagram/history'; +import type { DiagramModel } from '../diagram/model'; import { CanvasPlaceAt } from '../diagram/placeLayer'; +import { ResizableBox, type ResizableBoxOperation } from './utility/resizableBox'; import { SelectionActionRemove, SelectionActionExpand, SelectionActionAnchor, SelectionActionConnections, SelectionActionAddToFilter, SelectionActionGroup, - SelectionActionEstablishLink, + SelectionActionEstablishLink, SelectionActionAnnotate, } from './selectionAction'; /** @@ -23,7 +31,7 @@ export interface HaloProps { /** * Margin between the element and surrounding actions. * - * @default 5 + * **Default** is set by `--reactodia-selection-single-box-margin` CSS property. */ margin?: number; /** @@ -38,6 +46,7 @@ export interface HaloProps { * * * + * * * * ``` @@ -68,6 +77,7 @@ export function Halo(props: HaloProps) { ); @@ -78,6 +88,7 @@ export function Halo(props: HaloProps) { interface HaloInnerProps extends HaloProps { readonly target: Element; readonly canvas: CanvasApi; + readonly model: DiagramModel; } const CLASS_NAME = 'reactodia-halo'; @@ -131,25 +142,46 @@ class HaloInner extends React.Component { const { target, canvas, - margin = 5, + model, + margin, children, } = this.props; + const template = canvas.renderingState.getElementTemplate(target); + const resizable = Boolean(template.supports?.[TemplateProperties.ElementSize]); + const bbox = boundsOf(target, canvas.renderingState); const {x: x0, y: y0} = canvas.metrics.paperToScrollablePaneCoords(bbox.x, bbox.y); const {x: x1, y: y1} = canvas.metrics.paperToScrollablePaneCoords( bbox.x + bbox.width, bbox.y + bbox.height, ); - const style: React.CSSProperties = { - left: x0 - margin, - top: y0 - margin, - width: ((x1 - x0) + margin * 2), - height: ((y1 - y0) + margin * 2), - }; + const style = { + '--reactodia-selection-single-box-margin': margin, + '--reactodia-halo-left': `${x0}px`, + '--reactodia-halo-top': `${y0}px`, + '--reactodia-halo-width': `${x1 - x0}px`, + '--reactodia-halo-height': `${y1 - y0}px`, + } as React.CSSProperties; return ( -
+
+ {resizable && ( + canvas.metrics.pageToPaperCoords(x, y)} + startResize={() => { + model.history.registerToUndo(Command.compound( + TranslatedText.text('commands.transform_elements.title'), + [RestoreGeometry.capturePartial([target], [])] + )); + return new ElementResizeOperation(target, bbox); + }} + minWidth={40} + minHeight={40} + /> + )} {children ?? <> @@ -157,9 +189,29 @@ class HaloInner extends React.Component { + }
); } } + +class ElementResizeOperation implements ResizableBoxOperation { + constructor( + private readonly target: Element, + readonly initialBounds: Rect + ) {} + + onResize({x, y, width, height}: Rect): void { + this.target.setPosition({x, y}); + this.target.setElementState({ + ...this.target.elementState, + [TemplateProperties.ElementSize]: {width, height}, + }); + } + + end(): void { + /* nothing */ + } +} diff --git a/src/widgets/linkAction.tsx b/src/widgets/linkAction.tsx index 3c87bc9a..78b21592 100644 --- a/src/widgets/linkAction.tsx +++ b/src/widgets/linkAction.tsx @@ -13,11 +13,12 @@ import { Link } from '../diagram/elements'; import { GraphStructure } from '../diagram/model'; import { HtmlSpinner } from '../diagram/spinner'; +import { AnnotationLink } from '../editor/annotationCells'; import { AuthoringState } from '../editor/authoringState'; import { EntityElement, RelationLink } from '../editor/dataElements'; import { EditorController } from '../editor/editorController'; -import { VisualAuthoringTopic } from '../workspace/commandBusTopic'; +import { AnnotationTopic, VisualAuthoringTopic } from '../workspace/commandBusTopic'; import { useWorkspace } from '../workspace/workspaceContext'; /** @@ -234,8 +235,9 @@ export interface LinkActionDeleteProps extends LinkActionStyleProps {} /** * Link action component to delete the link. - * - * This action is visible only when {@link EditorController.inAuthoringMode graph authoring mode} + * + * This action is visible either if the link is an {@link AnnotationLink} or + * it is an {@link RelationLink} and {@link EditorController.inAuthoringMode graph authoring mode} * is active. * * Deleting a link adds a command to the command history. @@ -243,8 +245,19 @@ export interface LinkActionDeleteProps extends LinkActionStyleProps {} * @category Components */ export function LinkActionDelete(props: LinkActionDeleteProps) { - const {className, title, ...otherProps} = props; const {link} = useLinkActionContext(); + + if (link instanceof RelationLink) { + return ; + } else if (link instanceof AnnotationLink) { + return ; + } else { + return null; + } +} + +function LinkActionDeleteRelation(props: LinkActionDeleteProps & { link: RelationLink }) { + const {link, className, title, ...otherProps} = props; const {model, editor, translation: t} = useWorkspace(); const canModify = useCanModifyLink(link, model, editor); @@ -332,6 +345,22 @@ function isSourceOrTargetDeleted(state: AuthoringState, link: RelationLink): boo ); } +function LinkActionDeleteAnnotation(props: LinkActionDeleteProps & { link: AnnotationLink }) { + const {link, className, title, ...otherProps} = props; + const {editor, translation: t} = useWorkspace(); + return ( + editor.removeItems([link])} + /> + ); +} + /** * Props for {@link LinkActionMoveEndpoint} component. * @@ -340,12 +369,12 @@ function isSourceOrTargetDeleted(state: AuthoringState, link: RelationLink): boo export interface LinkActionMoveEndpointProps extends Omit {} /** - * Link action component to change the relation link by moving its endpoint - * to another entity element. + * Link action component to change the link by moving its endpoint to another element. * * The changed endpoint is specified via {@link LinkActionStyleProps.dockSide dockSide} prop. * - * This action is visible only when {@link EditorController.inAuthoringMode graph authoring mode} + * This action is visible either if the link is an {@link AnnotationLink} or + * it is an {@link RelationLink} and {@link EditorController.inAuthoringMode graph authoring mode} * is active. * * Changing a link adds a command to the command history. @@ -353,8 +382,22 @@ export interface LinkActionMoveEndpointProps extends Omit; + } else if (link instanceof AnnotationLink) { + return ; + } else { + return null; + } +} + +function LinkActionMoveRelationEndpoint( + props: LinkActionMoveEndpointProps & { link: RelationLink } +) { + const {link, dockSide, className, title, ...otherProps} = props; + const {buttonSize, getAngleInDegrees} = useLinkActionContext(); const {canvas} = useCanvas(); const {editor, translation: t, getCommandBus} = useWorkspace(); @@ -364,25 +407,18 @@ export function LinkActionMoveEndpoint(props: LinkActionMoveEndpointProps) { const linkIsDeleted = useObservedProperty( editor.events, 'changeAuthoringState', - () => ( - link instanceof RelationLink && - AuthoringState.isDeletedRelation(editor.authoringState, link.data) - ) + () => AuthoringState.isDeletedRelation(editor.authoringState, link.data) ); - if (!(inAuthoringMode && link instanceof RelationLink)) { + if (!inAuthoringMode) { return null; } - const angle = getAngleInDegrees(dockSide); return ( - - - {dockSide === 'source' ? ( - - ) : ( - - )} - - + ); } +function LinkActionMoveAnnotationEndpoint( + props: LinkActionMoveEndpointProps & { link: AnnotationLink } +) { + const {link, dockSide, className, title, ...otherProps} = props; + const {buttonSize, getAngleInDegrees} = useLinkActionContext(); + const {canvas} = useCanvas(); + const {translation: t, getCommandBus} = useWorkspace(); + + return ( + { + const point = canvas.metrics.pageToPaperCoords(e.pageX, e.pageY); + getCommandBus(AnnotationTopic) + .trigger('startDragOperation', { + operation: { + mode: dockSide === 'source' ? 'moveSource' : 'moveTarget', + link, + point, + }, + }); + }}> + + + ); +} + +function LinkEndpointHandle(props: { + dockSide: LinkActionStyleProps['dockSide']; + buttonSize: number; + angle: number; +}) { + const {dockSide, buttonSize, angle} = props; + return ( + + + {dockSide === 'source' ? ( + + ) : ( + + )} + + + ); +} + /** * Props for {@link LinkActionRename} component. * diff --git a/src/widgets/linksToolbox.tsx b/src/widgets/linksToolbox.tsx index 8e898024..afd4d110 100644 --- a/src/widgets/linksToolbox.tsx +++ b/src/widgets/linksToolbox.tsx @@ -356,6 +356,10 @@ function applyFilter(state: State, term: string, props: LinkTypesToolboxInnerPro const allLinkTypeIris = new Set(); for (const link of model.links) { + if (link.typeId.startsWith('urn:reactodia:')) { + // Skip built-in link types + continue; + } allLinkTypeIris.add(link.typeId); } diff --git a/src/widgets/selection.tsx b/src/widgets/selection.tsx index 878f9754..b633c3b0 100644 --- a/src/widgets/selection.tsx +++ b/src/widgets/selection.tsx @@ -20,6 +20,7 @@ import { CanvasPlaceAt } from '../diagram/placeLayer'; import { SelectionActionRemove, SelectionActionZoomToFit, SelectionActionLayout, SelectionActionExpand, SelectionActionConnections, SelectionActionGroup, + SelectionActionAnnotate, } from './selectionAction'; /** @@ -60,6 +61,7 @@ export interface SelectionProps { * * * + * * * ``` */ @@ -285,6 +287,7 @@ function SelectionBox(props: SelectionBoxProps) { + }
{/* Render box on top of item overlays for correct pointer event handling */} diff --git a/src/widgets/selectionAction.tsx b/src/widgets/selectionAction.tsx index 0dfdc18c..74f3f4c5 100644 --- a/src/widgets/selectionAction.tsx +++ b/src/widgets/selectionAction.tsx @@ -10,7 +10,7 @@ import type { HotkeyString } from '../coreUtils/hotkey'; import { TranslatedText, useTranslation } from '../coreUtils/i18n'; import { LinkTypeIri } from '../data/model'; -import { TemplateProperties } from '../data/schema'; +import { AnnotationContent, TemplateProperties } from '../data/schema'; import { useCanvas } from '../diagram/canvasApi'; import { useCanvasHotkey } from '../diagram/canvasHotkey'; @@ -20,6 +20,7 @@ import { getContentFittingBox } from '../diagram/geometry'; import type { DiagramModel } from '../diagram/model'; import { HtmlSpinner } from '../diagram/spinner'; +import { AnnotationElement } from '../editor/annotationCells'; import { AuthoringState } from '../editor/authoringState'; import { BuiltinDialogType } from '../editor/builtinDialogType'; import { EntityElement, EntityGroup, iterateEntitiesOf } from '../editor/dataElements'; @@ -27,7 +28,7 @@ import type { EditorController } from '../editor/editorController'; import { groupEntitiesAnimated, ungroupAllEntitiesAnimated } from '../editor/elementGrouping'; import { - ConnectionsMenuTopic, InstancesSearchTopic, VisualAuthoringTopic, + AnnotationTopic, ConnectionsMenuTopic, InstancesSearchTopic, VisualAuthoringTopic, } from '../workspace/commandBusTopic'; import { useWorkspace } from '../workspace/workspaceContext'; @@ -323,23 +324,32 @@ export interface SelectionActionExpandProps extends SelectionActionStyleProps {} * Elements are collapsed if all of them are expanded, otherwise only collapsed * ones are expanded instead. * + * This action is visible only when at least one of the selected elements + * have {@link TemplateProperties.Expanded} property in {@link ElementTemplate.supports}. + * * Expanding or collapsing the elements adds a command to the command history. * * @category Components */ export function SelectionActionExpand(props: SelectionActionExpandProps) { const {className, title, ...otherProps} = props; + const {canvas} = useCanvas(); const {model, translation: t} = useWorkspace(); const elements = model.selection.filter((cell): cell is Element => cell instanceof Element); const elementExpandedStore = useElementExpandedStore(model, elements); const debouncedExpandedStore = useFrameDebouncedStore(elementExpandedStore); + + const canExpand = (element: Element) => { + const template = canvas.renderingState.getElementTemplate(element); + return Boolean(template.supports?.[TemplateProperties.Expanded]); + }; const allExpanded = useSyncStore( debouncedExpandedStore, - () => elements.every(element => element.isExpanded) + () => elements.every(element => !canExpand(element) || element.isExpanded) ); - if (elements.every(element => element instanceof EntityGroup)) { + if (!elements.some(canExpand)) { return null; } @@ -365,7 +375,9 @@ export function SelectionActionExpand(props: SelectionActionExpandProps) { : TranslatedText.text('selection_action.expand.expand_command') ); for (const element of elements) { - batch.history.execute(setElementExpanded(element, !allExpanded)); + if (canExpand(element)) { + batch.history.execute(setElementExpanded(element, !allExpanded)); + } } batch.store(); } @@ -424,6 +436,8 @@ export interface SelectionActionAnchorProps extends SelectionActionStyleProps { /** * Selection action component to display a link to the entity IRI. * + * This action is visible only if the selected element is an {@link EntityElement}. + * * @category Components */ export function SelectionActionAnchor(props: SelectionActionAnchorProps) { @@ -471,6 +485,9 @@ export interface SelectionActionConnectionsProps extends SelectionActionStylePro /** * Selection action component to open a {@link ConnectionsMenu} for the selected entities. * + * This action is visible if at least one {@link EntityElement} or {@link EntityGroup} + * is selected. + * * @category Components */ export function SelectionActionConnections(props: SelectionActionConnectionsProps) { @@ -530,6 +547,8 @@ export interface SelectionActionAddToFilterProps extends SelectionActionStylePro /** * Selection action component to add the selected entity to the {@link InstancesSearch} filter. * + * This action is visible only if the selected element is an {@link EntityElement}. + * * @category Components */ export function SelectionActionAddToFilter(props: SelectionActionAddToFilterProps) { @@ -576,8 +595,9 @@ export interface SelectionActionGroupProps extends SelectionActionStyleProps { /** * Selection action component to group or ungroup selected elements. * - * Selected elements can be grouped if only entity elements are selected, - * the elements can be ungrouped if only entity groups are selected. + * Selected elements can be grouped if only {@link EntityElement entity elements} + * are selected, the elements can be ungrouped if only {@link EntityGroup entity groups} + * are selected. * * Grouping or ungrouping the elements adds a command to the command history. * @@ -606,7 +626,11 @@ export function SelectionActionGroup(props: SelectionActionGroupProps) { } }; - if (elements.length === 0 || elements.length === 1 && canGroup) { + if ( + elements.length === 0 || + elements.length === 1 && canGroup || + elements.every(element => element instanceof AnnotationElement) + ) { return null; } @@ -641,33 +665,49 @@ export interface SelectionActionEstablishLinkProps extends SelectionActionStyleP } /** - * Selection action component to start creating a relation link to an existing - * or a new entity. + * Selection action component to start creating a link to an existing or a new element. * - * This action is visible only when graph authoring mode is active. + * This action is visible either if selected element is an {@link AnnotationElement} + * it is an {@link EntityElement} and {@link EditorController.inAuthoringMode graph authoring mode} + * is active. * * Creating a link adds a command to the command history. * * @category Components */ export function SelectionActionEstablishLink(props: SelectionActionEstablishLinkProps) { - const {className, title, linkType, ...otherProps} = props; + const {model} = useCanvas(); + + const elements = model.selection.filter((cell): cell is Element => cell instanceof Element); + const target = elements.length === 1 ? elements[0] : undefined; + + if (target instanceof EntityElement) { + return ; + } else if (target instanceof AnnotationElement) { + return ; + } else { + return null; + } +} + +function SelectionActionEstablishRelation( + props: SelectionActionEstablishLinkProps & { target: EntityElement } +) { + const {target, className, title, linkType, ...otherProps} = props; const {canvas} = useCanvas(); - const {model, editor, translation: t, getCommandBus} = useWorkspace(); + const {editor, translation: t, getCommandBus} = useWorkspace(); const inAuthoringMode = useObservedProperty( editor.events, 'changeMode', () => editor.inAuthoringMode ); - - const elements = model.selection.filter((cell): cell is Element => cell instanceof Element); - const target = elements.length === 1 ? elements[0] : undefined; + const canLink = useCanEstablishLink( editor, inAuthoringMode ? target : undefined, linkType ); - if (!(target instanceof EntityElement && inAuthoringMode)) { + if (!inAuthoringMode) { return null; } else if (canLink === undefined) { const {dock, dockRow, dockColumn} = props; @@ -678,6 +718,7 @@ export function SelectionActionEstablishLink(props: SelectionActionEstablishLink /> ); } + return ( { + const point = canvas.metrics.pageToPaperCoords(e.pageX, e.pageY); + getCommandBus(AnnotationTopic) + .trigger('startDragOperation', { + operation: {mode: 'connect', source: target, point}, + }); + }} + /> + ); +} + +/** + * Props for {@link SelectionActionAnnotate} component. + * + * @see {@link SelectionActionAnnotate} + */ +export interface SelectionActionAnnotateProps extends SelectionActionStyleProps { + /** + * Initial annotation content. + * + * @default Translation.text('selection_action.annotate.defaultContent') + */ + initialContent?: AnnotationContent | GetInitialAnnotationContent | null; +} + +type GetInitialAnnotationContent = (elements: readonly Element[]) => AnnotationContent | undefined; + +/** + * Selection action component to create a new annotaion element + * connected to the selected elements. + * + * @category Components + */ +export function SelectionActionAnnotate(props: SelectionActionAnnotateProps) { + const {className, title, initialContent, ...otherProps} = props; + const {model, translation: t, getCommandBus} = useWorkspace(); + + const elements = model.selection.filter((cell): cell is Element => cell instanceof Element); + if (elements.length === 0) { + return null; + } + + return ( + { + let content: AnnotationContent | undefined; + if (typeof initialContent === 'function') { + content = initialContent(elements); + } else if (initialContent === undefined) { + content = { + type: 'plaintext', + text: t.text('selection_action.annotate.defaultContent'), + }; + } else if (initialContent !== null) { + content = initialContent; + } + + getCommandBus(AnnotationTopic) + .trigger('createAnnotation', { + targets: elements, + content, + }); + }} + /> + ); +} diff --git a/src/widgets/utility/contentEditablePlaintext.tsx b/src/widgets/utility/contentEditablePlaintext.tsx new file mode 100644 index 00000000..fc8d367b --- /dev/null +++ b/src/widgets/utility/contentEditablePlaintext.tsx @@ -0,0 +1,60 @@ +import * as React from 'react'; + +export function ContentEditablePlaintext(props: { + className?: string; + style?: React.CSSProperties; + text: string; + setText: (value: string) => void; + isEditing: boolean; + setEditing: (value: boolean) => void; +}) { + const {className, style, text, setText, isEditing, setEditing} = props; + const editorRef = React.useRef(null); + + React.useLayoutEffect(() => { + const editor = editorRef.current; + if (isEditing && editor) { + editor.focus(); + window.getSelection()?.selectAllChildren(editor); + } + }, [isEditing]); + + React.useLayoutEffect(() => { + const editor = editorRef.current; + if (editor) { + editor.innerText = text || '\n'; + } + }, [text]); + + return ( +

{ + if (isEditing) { + e.stopPropagation(); + } + }} + onKeyDown={e => { + if (isEditing) { + e.stopPropagation(); + } + }} + onKeyUp={e => { + if (isEditing) { + e.stopPropagation(); + if (e.key === 'Escape') { + document.getSelection()?.removeAllRanges(); + editorRef.current?.blur(); + } + } + }} + onBlur={e => { + const changedText = (editorRef.current?.innerText ?? '').trim(); + setEditing(false); + setText(changedText); + }}> +

+ ); +} diff --git a/src/widgets/utility/dragLinkMover.tsx b/src/widgets/utility/dragLinkMover.tsx new file mode 100644 index 00000000..6763867a --- /dev/null +++ b/src/widgets/utility/dragLinkMover.tsx @@ -0,0 +1,508 @@ +import * as React from 'react'; + +import { mapAbortedToNull } from '../../coreUtils/async'; +import { EventObserver } from '../../coreUtils/events'; + +import { CanvasApi, useCanvas } from '../../diagram/canvasApi'; +import { Element, Link, VoidElement } from '../../diagram/elements'; +import { Vector, boundsOf, findElementAtPoint } from '../../diagram/geometry'; +import { LinkLayer, LinkMarkers } from '../../diagram/linkLayer'; +import { DiagramModel } from '../../diagram/model'; +import { SvgPaperLayer } from '../../diagram/paper'; +import { CanvasPlaceAt } from '../../diagram/placeLayer'; +import type { MutableRenderingState } from '../../diagram/renderingState'; +import { Spinner } from '../../diagram/spinner'; + +export interface DragLinkMoverProps { + operation: DragLinkOperation; + + createLink: ( + source: Element, + target: Element, + original: Link | undefined + ) => Link; + + canConnect: ( + source: Element, + link: Link, + target: Element | undefined, + signal: AbortSignal + ) => Promise; + + cleanupLink?: (link: Link) => void; + + onFinish?: () => void; +} + +export type DragLinkOperation = DragLinkOperationConnect | DragLinkOperationMove; + +export interface DragLinkOperationConnect { + /** + * Drag link operation type. + */ + readonly mode: 'connect'; + /** + * Target element to drag a link from. + */ + readonly source: Element; + /** + * Initial position for the dragged link endpoint on paper. + */ + readonly point: Vector; + +} + +export interface DragLinkOperationMove { + /** + * Drag link operation type. + */ + readonly mode: 'moveSource' | 'moveTarget'; + /** + * Target relation link to drag an endpoint of. + */ + readonly link: Link; + /** + * Initial position for the dragged link endpoint on paper. + */ + readonly point: Vector; +} + +export interface DragLinkConnection { + readonly allowed: boolean; + + connect( + source: Element, + target: Element | undefined, + targetPosition: Vector, + canvas: CanvasApi, + signal: AbortSignal + ): Promise; + + moveSource( + link: Link, + newSource: Element, + canvas: CanvasApi, + signal: AbortSignal + ): Promise; + + moveTarget( + link: Link, + newTarget: Element, + canvas: CanvasApi, + signal: AbortSignal + ): Promise; +} + +export function DragLinkMover(props: DragLinkMoverProps) { + const {canvas, model} = useCanvas(); + return ( + + + + ); +} + +interface DragLinkMoverInnerProps extends DragLinkMoverProps { + model: DiagramModel; + canvas: CanvasApi; +} + +interface State { + targetElement?: Element; + anyConnection?: DragLinkConnection; + targetConnection?: DragLinkConnection; + waitingForMetadata?: boolean; +} + +const CLASS_NAME = 'reactodia-drag-link-mover'; + +const NO_CONNECTION: DragLinkConnection = { + allowed: false, + connect: () => Promise.resolve(), + moveSource: () => Promise.resolve(), + moveTarget: () => Promise.resolve(), +}; + +class DragLinkMoverInner extends React.Component { + private readonly listener = new EventObserver(); + private cancellation = new AbortController(); + private canDropOnElementCancellation = new AbortController(); + + private temporaryLink: Link | undefined; + private temporaryElement: VoidElement | undefined; + private oldLink: Link | undefined; + + constructor(props: DragLinkMoverInnerProps) { + super(props); + this.state = {}; + } + + componentDidMount() { + const {canvas, operation} = this.props; + + this.cancellation = new AbortController(); + + switch (operation.mode) { + case 'connect': { + this.beginCreatingLink(operation); + break; + } + case 'moveSource': + case 'moveTarget': { + this.beginMovingLink(operation); + break; + } + default: { + throw new Error(`Unknown edit mode: "${(operation as DragLinkOperation).mode}"`); + } + } + + this.forceUpdate(); + this.queryCanConnectToAny(); + + this.listener.listen(canvas.events, 'changeTransform', () => this.forceUpdate()); + document.addEventListener('mousemove', this.onMouseMove); + document.addEventListener('mouseup', this.onMouseUp); + } + + componentWillUnmount() { + this.listener.stopListening(); + this.cancellation.abort(); + this.canDropOnElementCancellation.abort(); + document.removeEventListener('mousemove', this.onMouseMove); + document.removeEventListener('mouseup', this.onMouseUp); + this.cleanup(); + } + + private beginCreatingLink(operation: DragLinkOperationConnect) { + const {createLink, model} = this.props; + const {source, point} = operation; + + const batch = model.history.startBatch(); + + const temporaryElement = this.createTemporaryElement(point); + const temporaryLink = createLink(source, temporaryElement, undefined); + + batch.discard(); + + this.temporaryElement = temporaryElement; + this.temporaryLink = temporaryLink; + } + + private beginMovingLink(operation: DragLinkOperationMove) { + const {createLink, model} = this.props; + const {link, point} = operation; + + const batch = model.history.startBatch(); + + this.oldLink = link; + model.removeLink(link.id); + + const temporaryElement = this.createTemporaryElement(point); + const temporaryLink = operation.mode === 'moveSource' + ? createLink(temporaryElement, model.targetOf(link)!, link) + : createLink(model.sourceOf(link)!, temporaryElement, link); + + batch.discard(); + + this.temporaryElement = temporaryElement; + this.temporaryLink = temporaryLink; + } + + private createTemporaryElement(point: Vector) { + const {model} = this.props; + const temporaryElement = new VoidElement({}); + temporaryElement.setPosition(point); + model.addElement(temporaryElement); + return temporaryElement; + } + + private onMouseMove = (e: MouseEvent) => { + const {model, canvas} = this.props; + const {targetElement, waitingForMetadata} = this.state; + + e.preventDefault(); + e.stopPropagation(); + + if (waitingForMetadata) { return; } + + const point = canvas.metrics.pageToPaperCoords(e.pageX, e.pageY); + this.temporaryElement!.setPosition(point); + + const newTargetElement = findElementAtPoint(model.elements, point, canvas.renderingState); + + if (newTargetElement !== targetElement) { + this.queryCanDropOnElement(newTargetElement); + } + this.setState({targetElement: newTargetElement}); + }; + + private queryCanConnectToAny() { + const {canConnect, model} = this.props; + + this.setState({anyConnection: undefined}); + + const link = this.temporaryLink!; + const source = model.getElement(link.sourceId)!; + mapAbortedToNull( + canConnect( + source, + link, + undefined, + this.cancellation.signal + ), + this.cancellation.signal + ).then( + connection => { + if (connection === null) { return; } + this.setState({anyConnection: connection}); + }, + error => { + console.error('Error calling canConnect() without target', error); + this.setState({anyConnection: NO_CONNECTION}); + } + ); + } + + private queryCanDropOnElement(targetElement: Element | undefined) { + const {operation, canConnect, model} = this.props; + + this.canDropOnElementCancellation.abort(); + this.canDropOnElementCancellation = new AbortController(); + + if (!targetElement) { + this.setState({targetConnection: NO_CONNECTION}); + return; + } + + this.setState({targetConnection: undefined}); + + const link = this.temporaryLink; + let source: Element | undefined; + let target: Element | undefined; + switch (operation.mode) { + case 'connect': + case 'moveTarget': { + source = link ? model.getElement(link.sourceId) : undefined; + target = targetElement; + break; + } + case 'moveSource': { + source = targetElement; + target = link ? model.getElement(link.targetId) : undefined; + break; + } + } + + if (!(source && target && link)) { + this.setState({targetConnection: NO_CONNECTION}); + return; + } + + const signal = this.canDropOnElementCancellation.signal; + mapAbortedToNull( + canConnect(source, link, target, signal), + signal + ).then( + connection => { + if (connection === null) { return; } + this.setState({targetConnection: connection}); + }, + error => { + console.error('Error calling canConnect() with target', error); + this.setState({targetConnection: NO_CONNECTION}); + } + ); + } + + private onMouseUp = (e: MouseEvent) => { + const {canvas} = this.props; + if (this.state.waitingForMetadata) { return; } + // show spinner while waiting for additional MetadataApi queries + this.setState({waitingForMetadata: true}); + const selectedPosition = canvas.metrics.pageToPaperCoords(e.pageX, e.pageY); + void this.executeEditOperation(selectedPosition); + }; + + private async executeEditOperation(selectedPosition: Vector): Promise { + const {operation, canvas, model} = this.props; + + try { + const {targetElement, anyConnection, targetConnection} = this.state; + + const batch = model.history.startBatch(); + const restoredLink = this.restoreOldLink(); + batch.discard(); + + const connection = targetElement ? targetConnection : anyConnection; + if (connection?.allowed) { + switch (operation.mode) { + case 'connect': { + await connection.connect( + operation.source, + targetElement, + selectedPosition, + canvas, + this.cancellation.signal + ); + break; + } + case 'moveSource': { + await connection.moveSource( + restoredLink!, + targetElement!, + canvas, + this.cancellation.signal + ); + break; + } + case 'moveTarget': { + await connection.moveTarget( + restoredLink!, + targetElement!, + canvas, + this.cancellation.signal + ); + break; + } + } + } + } finally { + this.cleanupAndFinish(); + } + } + + private cleanupAndFinish() { + const {onFinish} = this.props; + this.cleanup(); + onFinish?.(); + } + + private cleanup() { + const {cleanupLink, model} = this.props; + + const batch = model.history.startBatch(); + model.removeElement(this.temporaryElement!.id); + model.removeLink(this.temporaryLink!.id); + cleanupLink?.(this.temporaryLink!); + this.restoreOldLink(); + batch.discard(); + + this.setState({waitingForMetadata: false}); + } + + private restoreOldLink(): Link | undefined { + const {model} = this.props; + const restoredLink = this.oldLink; + this.oldLink = undefined; + if (restoredLink) { + model.addLink(restoredLink); + } + return restoredLink; + } + + render() { + const {model, canvas} = this.props; + const {waitingForMetadata} = this.state; + + if (!this.temporaryLink) { + return null; + } + + const transform = canvas.metrics.getTransform(); + const renderingState = canvas.renderingState as MutableRenderingState; + return ( + + + {this.renderHighlight()} + {this.renderCanDropIndicator()} + {waitingForMetadata ? null : ( + link === this.temporaryLink} + /> + )} + + ); + } + + private renderHighlight() { + const {canvas} = this.props; + const {targetElement, targetConnection, waitingForMetadata} = this.state; + + if (!targetElement) { return null; } + + const {x, y, width, height} = boundsOf(targetElement, canvas.renderingState); + + if (targetConnection === undefined || waitingForMetadata) { + return ( + + + + + ); + } + + return ( + + ); + } + + private renderCanDropIndicator() { + const {targetElement, anyConnection, waitingForMetadata} = this.state; + + if (targetElement) { return null; } + + const {x, y} = this.temporaryElement!.position; + + let indicator: React.ReactElement; + if (anyConnection === undefined) { + indicator = ; + } else if (anyConnection?.allowed) { + indicator = ( + + ); + } else { + indicator = ( + + + + + ); + } + + return ( + + + {waitingForMetadata + ? + : {indicator}} + + ); + } +} diff --git a/src/widgets/utility/draggableHandle.tsx b/src/widgets/utility/draggableHandle.tsx index de9b40bf..1ea009ec 100644 --- a/src/widgets/utility/draggableHandle.tsx +++ b/src/widgets/utility/draggableHandle.tsx @@ -73,9 +73,12 @@ export function DraggableHandle(props: DraggableHandleProps) { } = props; const holdState = React.useRef(undefined); + const latestOnBegin = useLatest(onBeginDragHandle); + const latestOnDrag = useLatest(onDragHandle); + const latestOnEnd = useLatest(onEndDragHandle); const onPointerDown = (e: React.PointerEvent) => { - if (holdState.current || e.target !== e.currentTarget) { + if (holdState.current) { return; } @@ -93,7 +96,7 @@ export function DraggableHandle(props: DraggableHandleProps) { onPointerMove: e => { e.preventDefault(); const {origin} = state; - onDragHandle( + latestOnDrag.current( e, axis === 'y' ? 0 : e.pageX - origin.pageX, axis === 'x' ? 0 : e.pageY - origin.pageY @@ -106,7 +109,7 @@ export function DraggableHandle(props: DraggableHandleProps) { target.removeEventListener('pointermove', state.onPointerMove); target.removeEventListener('pointerup', state.onPointerUp); target.removeEventListener('pointercancel', state.onPointerUp); - onEndDragHandle?.(e); + latestOnEnd.current?.(e); }, }; currentTarget.addEventListener('pointermove', state.onPointerMove); @@ -114,7 +117,7 @@ export function DraggableHandle(props: DraggableHandleProps) { currentTarget.addEventListener('pointercancel', state.onPointerUp); currentTarget.setPointerCapture(pointerId); - onBeginDragHandle(e); + latestOnBegin.current(e); }; return ( @@ -129,3 +132,9 @@ export function DraggableHandle(props: DraggableHandleProps) { ); } + +function useLatest(value: T): { readonly current: T } { + const ref = React.useRef(value); + ref.current = value; + return ref; +} diff --git a/src/widgets/utility/resizableBox.tsx b/src/widgets/utility/resizableBox.tsx new file mode 100644 index 00000000..807149f5 --- /dev/null +++ b/src/widgets/utility/resizableBox.tsx @@ -0,0 +1,146 @@ +import * as React from 'react'; +import cx from 'clsx'; + +import { Rect, Vector } from '../../diagram/geometry'; + +import { DraggableHandle } from './draggableHandle'; + +const CLASS_NAME = 'reactodia-resizable-box'; + +export function ResizableBox(props: { + className?: string; + mapCoordsFromPage: (x: number, y: number) => Vector; + startResize: () => ResizableBoxOperation; + minWidth?: number; + minHeight?: number; +}) { + const { + className, mapCoordsFromPage, startResize, minWidth = 0, minHeight = 0, + } = props; + const [operation, setOperation] = React.useState(); + + const onBeginDragHandle = (e: React.MouseEvent) => { + e.stopPropagation(); + setOperation(startResize()); + }; + + const onEndDragHandle = () => { + operation?.end(); + setOperation(undefined); + }; + + const resize = (dx: number, dy: number, dw: number, dh: number) => { + if (!operation) { + return; + } + const {initialBounds} = operation; + const origin = mapCoordsFromPage(0, 0); + const {x: mappedDx, y: mappedDy} = Vector.subtract(mapCoordsFromPage(dx, dy), origin); + const {x: mappedDw, y: mappedDh} = Vector.subtract(mapCoordsFromPage(dw, dh), origin); + const nextBounds: Rect = { + x: Math.min(initialBounds.x + mappedDx, initialBounds.x + initialBounds.width - minWidth), + y: Math.min(initialBounds.y + mappedDy, initialBounds.y + initialBounds.height - minHeight), + width: Math.max(initialBounds.width + mappedDw, minWidth), + height: Math.max(initialBounds.height + mappedDh, minHeight), + }; + operation.onResize(nextBounds); + }; + + React.useEffect(() => { + return () => operation?.end(); + }, []); + + const handleCorner = ( + + + + ); + + const handleVertical = ( + + + + ); + + const handleHorizontal = ( + + + + ); + + const HANDLE_CLASS = `${CLASS_NAME}__handle`; + return ( +
+ resize(0, dy, 0, -dy)}> + {handleVertical} + + resize(0, 0, 0, dy)}> + {handleVertical} + + resize(dx, 0, -dx, 0)}> + {handleHorizontal} + + resize(0, 0, dx, 0)}> + {handleHorizontal} + + resize(dx, dy, -dx, -dy)}> + {handleCorner} + + resize(0, dy, dx, -dy)}> + {handleCorner} + + resize(dx, 0, -dx, dy)}> + {handleCorner} + + resize(0, 0, dx, dy)}> + {handleCorner} + +
+ ); +} + +export interface ResizableBoxOperation { + readonly initialBounds: Rect; + onResize(bounds: Rect): void; + end(): void; +} diff --git a/src/widgets/visualAuthoring/dragEditLayer.tsx b/src/widgets/visualAuthoring/dragEditLayer.tsx index 2e975512..a55c081a 100644 --- a/src/widgets/visualAuthoring/dragEditLayer.tsx +++ b/src/widgets/visualAuthoring/dragEditLayer.tsx @@ -1,24 +1,18 @@ import * as React from 'react'; -import { mapAbortedToNull } from '../../coreUtils/async'; -import { EventObserver } from '../../coreUtils/events'; - import { MetadataCanConnect } from '../../data/metadataProvider'; -import { ElementModel, ElementTypeIri, LinkTypeIri } from '../../data/model'; +import { ElementTypeIri, LinkTypeIri } from '../../data/model'; import { PlaceholderEntityType, PlaceholderRelationType } from '../../data/schema'; -import { CanvasApi, useCanvas } from '../../diagram/canvasApi'; -import { Element, VoidElement } from '../../diagram/elements'; -import { SizeProvider, Vector, boundsOf, findElementAtPoint } from '../../diagram/geometry'; -import { LinkLayer, LinkMarkers } from '../../diagram/linkLayer'; -import { SvgPaperLayer } from '../../diagram/paper'; -import { CanvasPlaceAt } from '../../diagram/placeLayer'; -import type { MutableRenderingState } from '../../diagram/renderingState'; -import { Spinner } from '../../diagram/spinner'; +import { CanvasApi } from '../../diagram/canvasApi'; +import { Element, Link } from '../../diagram/elements'; +import { SizeProvider, Vector } from '../../diagram/geometry'; import { TemporaryState } from '../../editor/authoringState'; import { EntityElement, RelationLink } from '../../editor/dataElements'; +import { DragLinkMover, DragLinkMoverProps, DragLinkConnection } from '../utility/dragLinkMover'; + import { VisualAuthoringTopic } from '../../workspace/commandBusTopic'; import { type WorkspaceContext, useWorkspace } from '../../workspace/workspaceContext'; @@ -73,344 +67,165 @@ export interface DragEditMoveEndpoint { } export function DragEditLayer(props: DragEditLayerProps) { + const {operation, onFinishEditing} = props; const workspace = useWorkspace(); - const {canvas} = useCanvas(); - return ( - - - - ); -} - -interface DragEditLayerInnerProps extends DragEditLayerProps { - workspace: WorkspaceContext; - canvas: CanvasApi; -} - -interface State { - targetElement?: Element; - connectionsToAny?: ReadonlyArray; - connectionsToTarget?: ReadonlyArray; - waitingForMetadata?: boolean; -} - -const CLASS_NAME = 'reactodia-drag-edit-layer'; - -class DragEditLayerInner extends React.Component { - private readonly listener = new EventObserver(); - private cancellation = new AbortController(); - private canDropOnElementCancellation = new AbortController(); - - private temporaryLink: RelationLink | undefined; - private temporaryElement: VoidElement | undefined; - private oldLink: RelationLink | undefined; - - constructor(props: DragEditLayerInnerProps) { - super(props); - this.state = {}; - } - - componentDidMount() { - const {canvas, operation} = this.props; + const {model, editor} = workspace; + const {metadataProvider} = editor; - this.cancellation = new AbortController(); - - switch (operation.mode) { - case 'connect': { - this.beginCreatingLink(operation); - break; + const createLink = React.useCallback( + (source, target, original) => { + if (original && !(original instanceof RelationLink)) { + throw new Error('DragEditLayer: cannot clone a non-relation link'); } - case 'moveSource': - case 'moveTarget': { - this.beginMovingLink(operation); - break; + const linkTemplate = new RelationLink({ + sourceId: source.id, + targetId: target.id, + data: { + sourceId: source instanceof EntityElement ? source.iri : '', + targetId: target instanceof EntityElement ? target.iri : '', + linkTypeId: original?.data.linkTypeId ?? PlaceholderRelationType, + properties: original?.data.properties ?? {}, + }, + vertices: original?.vertices, + linkState: original?.linkState, + }); + const link = editor.createRelation(linkTemplate, {temporary: true}); + if (!original) { + model.setLinkVisibility(PlaceholderRelationType, 'withoutLabel'); } - default: { - throw new Error(`Unknown edit mode: "${(operation as DragEditOperation).mode}"`); + return link; + }, + [operation] + ); + + const canConnect = React.useCallback( + async (source, link, target, signal) => { + const targetEvent = target instanceof EntityElement + ? editor.authoringState.elements.get(target.iri) : undefined; + + if (!( + metadataProvider && + link instanceof RelationLink && + source instanceof EntityElement && + (!target || target instanceof EntityElement) && + (!targetEvent || targetEvent.type !== 'entityDelete') + )) { + return new EnitityDragConnection([], workspace); } - } - - this.forceUpdate(); - this.queryCanConnectToAny(); - - this.listener.listen(canvas.events, 'changeTransform', () => this.forceUpdate()); - document.addEventListener('mousemove', this.onMouseMove); - document.addEventListener('mouseup', this.onMouseUp); - } - - componentWillUnmount() { - this.listener.stopListening(); - this.cancellation.abort(); - this.canDropOnElementCancellation.abort(); - document.removeEventListener('mousemove', this.onMouseMove); - document.removeEventListener('mouseup', this.onMouseUp); - this.cleanup(); - } - - private beginCreatingLink(operation: DragEditConnect) { - const {workspace: {model, editor}} = this.props; - const {source, linkType, point} = operation; - - const batch = model.history.startBatch(); - - const temporaryElement = this.createTemporaryElement(point); - const linkTemplate = new RelationLink({ - sourceId: source.id, - targetId: temporaryElement.id, - data: { - linkTypeId: linkType ?? PlaceholderRelationType, - sourceId: source.iri, - targetId: '', - properties: {}, - }, - }); - const temporaryLink = editor.createRelation(linkTemplate, {temporary: true}); - model.setLinkVisibility(PlaceholderRelationType, 'withoutLabel'); - - batch.discard(); - - this.temporaryElement = temporaryElement; - this.temporaryLink = temporaryLink; - } - private beginMovingLink(operation: DragEditMoveEndpoint) { - const {workspace: {model, editor}} = this.props; - const {mode, link, point} = operation; - - const batch = model.history.startBatch(); - - this.oldLink = link; - model.removeLink(link.id); - const {sourceId, targetId, data, vertices, linkState} = link; - - const temporaryElement = this.createTemporaryElement(point); - const linkTemplate = new RelationLink({ - sourceId: mode === 'moveSource' ? temporaryElement.id : sourceId, - targetId: mode === 'moveTarget' ? temporaryElement.id : targetId, - data: { - ...data, - sourceId: mode === 'moveSource' ? '' : data.sourceId, - targetId: mode === 'moveTarget' ? '' : data.targetId, - }, - vertices, - linkState, - }); - const temporaryLink = editor.createRelation(linkTemplate, {temporary: true}); - - batch.discard(); - - this.temporaryElement = temporaryElement; - this.temporaryLink = temporaryLink; - } - - private createTemporaryElement(point: Vector) { - const {workspace: {model}} = this.props; - const temporaryElement = new VoidElement({}); - temporaryElement.setPosition(point); - model.addElement(temporaryElement); - return temporaryElement; - } - - private onMouseMove = (e: MouseEvent) => { - const {workspace: {model}, canvas} = this.props; - const {targetElement, waitingForMetadata} = this.state; - - e.preventDefault(); - e.stopPropagation(); - - if (waitingForMetadata) { return; } - - const point = canvas.metrics.pageToPaperCoords(e.pageX, e.pageY); - this.temporaryElement!.setPosition(point); - - const newTargetElement = findElementAtPoint(model.elements, point, canvas.renderingState); - - if (newTargetElement !== targetElement) { - this.queryCanDropOnElement(newTargetElement); - } - this.setState({targetElement: newTargetElement}); - }; - - private queryCanConnectToAny() { - const {workspace: {model, editor}} = this.props; - - if (!editor.metadataProvider) { - this.setState({connectionsToAny: []}); - return; - } - - this.setState({connectionsToAny: undefined}); - - const link = this.temporaryLink!; - const source = model.getElement(link.sourceId) as EntityElement; - mapAbortedToNull( - editor.metadataProvider.canConnect( + const canConnect = await metadataProvider.canConnect( source.data, undefined, link.data.linkTypeId === PlaceholderRelationType ? undefined : link.data.linkTypeId, - {signal: this.cancellation.signal} - ), - this.cancellation.signal - ).then( - connections => { - if (connections === null) { return; } - this.setState({connectionsToAny: connections}); - }, - error => { - console.error('Error calling MetadataProvider.canConnect() without target', error); - this.setState({connectionsToAny: []}); + {signal} + ); + return new EnitityDragConnection(canConnect, workspace); + }, + [metadataProvider] + ); + + const cleanupLink = React.useCallback>( + (link) => { + if (link instanceof RelationLink) { + editor.setTemporaryState( + TemporaryState.removeRelation(editor.temporaryState, link.data) + ); } - ); - } + }, + [] + ); - private queryCanDropOnElement(targetElement: Element | undefined) { - const {operation, workspace: {model, editor}} = this.props; + return ( + + ); +} - this.canDropOnElementCancellation.abort(); - this.canDropOnElementCancellation = new AbortController(); +class EnitityDragConnection implements DragLinkConnection { + constructor( + private readonly connections: ReadonlyArray, + private readonly workspace: WorkspaceContext + ) {} - if (!(editor.metadataProvider && targetElement instanceof EntityElement)) { - this.setState({connectionsToTarget: []}); - return; - } + get allowed(): boolean { + return this.connections.length > 0; + } - const targetEvent = editor.authoringState.elements.get(targetElement.iri); - if (targetEvent && targetEvent.type === 'entityDelete') { - this.setState({connectionsToTarget: []}); + async connect( + source: Element, + target: Element | undefined, + targetPosition: Vector, + canvas: CanvasApi, + signal: AbortSignal + ): Promise { + if (!( + source instanceof EntityElement && + (!target || target instanceof EntityElement) + )) { return; } - this.setState({connectionsToTarget: undefined}); - - const link = this.temporaryLink!; - let source: ElementModel; - let target: ElementModel; - switch (operation.mode) { - case 'connect': - case 'moveTarget': { - source = (model.getElement(link.sourceId) as EntityElement).data; - target = targetElement.data; - break; - } - case 'moveSource': { - source = targetElement.data; - target = (model.getElement(link.targetId) as EntityElement).data; - break; - } + let createdTarget = target; + if (!createdTarget) { + createdTarget = await this.createNewElement(signal); + createdTarget.setPosition(targetPosition); + canvas.renderingState.syncUpdate(); + setElementCenterAtPoint(createdTarget, targetPosition, canvas.renderingState); } - const signal = this.canDropOnElementCancellation.signal; - mapAbortedToNull( - editor.metadataProvider.canConnect( - source, - target, - link.data.linkTypeId === PlaceholderRelationType - ? undefined : link.data.linkTypeId, - {signal} - ), - signal - ).then( - connections => { - if (connections === null) { return; } - this.setState({connectionsToTarget: connections}); - }, - error => { - console.error('Error calling MetadataProvider.canConnect() with target', error); - this.setState({connectionsToAny: []}); - } - ); + const modifiedLink = await this.createNewLink(source, createdTarget, signal); + this.afterCommit(target, createdTarget, modifiedLink); } - private onMouseUp = (e: MouseEvent) => { - const {canvas} = this.props; - if (this.state.waitingForMetadata) { return; } - // show spinner while waiting for additional MetadataApi queries - this.setState({waitingForMetadata: true}); - const selectedPosition = canvas.metrics.pageToPaperCoords(e.pageX, e.pageY); - void this.executeEditOperation(selectedPosition); - }; - - private async executeEditOperation(selectedPosition: Vector): Promise { - const {operation, canvas, workspace: {model, editor, getCommandBus}} = this.props; - - try { - const {targetElement, connectionsToAny, connectionsToTarget} = this.state; - - const batch = model.history.startBatch(); - const restoredLink = this.restoreOldLink(); - batch.discard(); - - const allowedConnections = targetElement ? connectionsToTarget : connectionsToAny; - if (allowedConnections && allowedConnections.length > 0) { - let modifiedLink: RelationLink | undefined; - let createdTarget = targetElement as EntityElement | undefined; - - switch (operation.mode) { - case 'connect': { - if (!createdTarget) { - createdTarget = await this.createNewElement(allowedConnections); - createdTarget.setPosition(selectedPosition); - canvas.renderingState.syncUpdate(); - setElementCenterAtPoint(createdTarget, selectedPosition, canvas.renderingState); - } - const sourceElement = model.getElement(this.temporaryLink!.sourceId) as EntityElement; - modifiedLink = await this.createNewLink(sourceElement, createdTarget, allowedConnections); - break; - } - case 'moveSource': { - modifiedLink = editor.moveRelationSource({ - link: restoredLink!, - newSource: targetElement as EntityElement, - }); - break; - } - case 'moveTarget': { - modifiedLink = editor.moveRelationTarget({ - link: restoredLink!, - newTarget: targetElement as EntityElement, - }); - break; - } - default: { - throw new Error('Unknown edit mode'); - } - } + async moveSource( + link: Link, + newSource: Element, + canvas: CanvasApi, + signal: AbortSignal + ): Promise { + const {editor} = this.workspace; + if (!( + link instanceof RelationLink && + newSource instanceof EntityElement + )) { + return; + } + const modifiedLink = editor.moveRelationSource({link, newSource}); + this.afterCommit(newSource, undefined, modifiedLink); + } - if (targetElement) { - const focusedLink = modifiedLink || restoredLink; - model.setSelection([focusedLink!]); - getCommandBus(VisualAuthoringTopic) - .trigger('editRelation', {target: focusedLink!}); - } else if (createdTarget && modifiedLink) { - model.setSelection([createdTarget]); - const source = model.getElement(modifiedLink.sourceId) as EntityElement; - getCommandBus(VisualAuthoringTopic) - .trigger('findOrCreateEntity', { - link: modifiedLink, - source, - target: createdTarget, - targetIsNew: true, - }); - } - } - } finally { - this.cleanupAndFinish(); + async moveTarget( + link: Link, + newTarget: Element, + canvas: CanvasApi, + signal: AbortSignal + ): Promise { + const {editor} = this.workspace; + if (!( + link instanceof RelationLink && + newTarget instanceof EntityElement + )) { + return; } + const modifiedLink = editor.moveRelationTarget({link, newTarget}); + this.afterCommit(newTarget, undefined, modifiedLink); } private async createNewElement( - connections: readonly MetadataCanConnect[] + signal: AbortSignal ): Promise { - const {workspace: {editor}} = this.props; + const {editor} = this.workspace; if (!editor.metadataProvider) { - throw new Error('Cannot create new element without metadata provider'); + throw new Error('Cannot create new entity without metadata provider'); } const elementTypes = new Set(); - for (const {targetTypes} of connections) { + for (const {targetTypes} of this.connections) { for (const typeIri of targetTypes) { elementTypes.add(typeIri); } @@ -418,7 +233,7 @@ class DragEditLayerInner extends React.Component const selectedType = elementTypes.size === 1 ? Array.from(elementTypes)[0] : PlaceholderEntityType; const elementModel = await editor.metadataProvider.createEntity( selectedType, - {signal: this.cancellation.signal} + {signal} ); return editor.createEntity(elementModel, {temporary: true}); } @@ -426,16 +241,16 @@ class DragEditLayerInner extends React.Component private async createNewLink( source: EntityElement, target: EntityElement, - connections: readonly MetadataCanConnect[] - ): Promise { - const {workspace: {model, editor}} = this.props; + signal: AbortSignal + ): Promise { + const {model, editor} = this.workspace; if (!editor.metadataProvider) { - return undefined; + throw new Error('Cannot create new relation without metadata provider'); } const inLinkSet = new Set(); const outLinkSet = new Set(); - for (const {targetTypes, inLinks, outLinks} of connections) { + for (const {targetTypes, inLinks, outLinks} of this.connections) { if (target.data.types.some(type => targetTypes.has(type))) { for (const linkType of inLinks) { inLinkSet.add(linkType); @@ -474,7 +289,7 @@ class DragEditLayerInner extends React.Component effectiveSource.data, effectiveTarget.data, linkTypeIri, - {signal: this.cancellation.signal} + {signal} ); const link = new RelationLink({ sourceId: effectiveSource.id, @@ -486,136 +301,27 @@ class DragEditLayerInner extends React.Component ? existingLink : editor.createRelation(link, {temporary: true}); } - private cleanupAndFinish() { - const {onFinishEditing} = this.props; - this.cleanup(); - onFinishEditing(); - } - - private cleanup() { - const {workspace: {model, editor}} = this.props; - - const batch = model.history.startBatch(); - model.removeElement(this.temporaryElement!.id); - model.removeLink(this.temporaryLink!.id); - editor.setTemporaryState( - TemporaryState.removeRelation(editor.temporaryState, this.temporaryLink!.data) - ); - this.restoreOldLink(); - batch.discard(); - } - - private restoreOldLink(): RelationLink | undefined { - const {workspace: {model}} = this.props; - const restoredLink = this.oldLink; - this.oldLink = undefined; - if (restoredLink) { - model.addLink(restoredLink); - } - return restoredLink; - } - - render() { - const {workspace: {model}, canvas} = this.props; - const {waitingForMetadata} = this.state; - - if (!this.temporaryLink) { - return null; - } - - const transform = canvas.metrics.getTransform(); - const renderingState = canvas.renderingState as MutableRenderingState; - return ( - - - {this.renderHighlight()} - {this.renderCanDropIndicator()} - {waitingForMetadata ? null : ( - link === this.temporaryLink} - /> - )} - - ); - } - - private renderHighlight() { - const {canvas} = this.props; - const {targetElement, connectionsToTarget, waitingForMetadata} = this.state; - - if (!targetElement) { return null; } - - const {x, y, width, height} = boundsOf(targetElement, canvas.renderingState); - - if (connectionsToTarget === undefined || waitingForMetadata) { - return ( - - - - - ); + private afterCommit( + selectedTarget: EntityElement | undefined, + createdTarget: EntityElement | undefined, + modifiedLink: RelationLink + ): void { + const {model, getCommandBus} = this.workspace; + if (selectedTarget) { + model.setSelection([modifiedLink]); + getCommandBus(VisualAuthoringTopic) + .trigger('editRelation', {target: modifiedLink}); + } else if (createdTarget && modifiedLink) { + model.setSelection([createdTarget]); + const source = model.getElement(modifiedLink.sourceId) as EntityElement; + getCommandBus(VisualAuthoringTopic) + .trigger('findOrCreateEntity', { + link: modifiedLink, + source, + target: createdTarget, + targetIsNew: true, + }); } - - const allowToConnect = connectionsToTarget && connectionsToTarget.length > 0; - return ( - - ); - } - - private renderCanDropIndicator() { - const {targetElement, connectionsToAny, waitingForMetadata} = this.state; - - if (targetElement) { return null; } - - const {x, y} = this.temporaryElement!.position; - - let indicator: React.ReactElement; - if (connectionsToAny === undefined) { - indicator = ; - } else if (connectionsToAny.length > 0) { - indicator = ( - - ); - } else { - indicator = ( - - - - - ); - } - - return ( - - - {waitingForMetadata - ? - : {indicator}} - - ); } } diff --git a/src/workspace.ts b/src/workspace.ts index f50f5124..316fc7df 100644 --- a/src/workspace.ts +++ b/src/workspace.ts @@ -31,7 +31,8 @@ export { } from './data/validationProvider'; export { DiagramContextV1, PlaceholderEntityType, PlaceholderRelationType, - TemplateProperties, PinnedProperties, + TemplateProperties, PinnedProperties, AnnotationContent, AnnotationTextStyle, + ColorVariant, setTemplateProperty, } from './data/schema'; export * from './data/composite/composite'; export { @@ -100,6 +101,10 @@ export { } from './diagram/sharedCanvasState'; export { Spinner, SpinnerProps, HtmlSpinner } from './diagram/spinner'; +export { + AnnotationElement, AnnotationLink, + SerializedAnnotationElement, SerializedAnnotationLink, +} from './editor/annotationCells'; export { AuthoringState, AuthoringEvent, AuthoredEntity, AuthoredEntityAdd, AuthoredEntityChange, AuthoredEntityDelete, @@ -158,6 +163,9 @@ export { DefaultLinkTemplate, DefaultLink, DefaultLinkProps, } from './templates/defaultLinkTemplate'; export { GroupPaginator, GroupPaginatorProps } from './templates/groupPaginator'; +export { + NoteTemplate, NoteAnnotation, NoteEntity, NoteLinkTemplate, NoteLink, +} from './templates/noteAnnotation'; export { RoundTemplate, RoundEntity, RoundEntityProps } from './templates/roundTemplate'; export { StandardTemplate, StandardEntity, StandardEntityProps, diff --git a/src/workspace/commandBusTopic.ts b/src/workspace/commandBusTopic.ts index 75707f3c..3f82edf3 100644 --- a/src/workspace/commandBusTopic.ts +++ b/src/workspace/commandBusTopic.ts @@ -1,5 +1,6 @@ import type { Events } from '../coreUtils/events'; +import type { AnnotationCommands } from '../widgets/annotation'; import type { ConnectionsMenuCommands } from '../widgets/connectionsMenu'; import type { InstancesSearchCommands } from '../widgets/instancesSearch'; import type { UnifiedSearchCommands } from '../widgets/unifiedSearch'; @@ -48,3 +49,6 @@ export const UnifiedSearchTopic = CommandBusTopic.define( * @category Constants */ export const VisualAuthoringTopic = CommandBusTopic.define(); + +// Internal topic +export const AnnotationTopic = CommandBusTopic.define(); diff --git a/src/workspace/workspace.tsx b/src/workspace/workspace.tsx index 61c000c9..ec7d4392 100644 --- a/src/workspace/workspace.tsx +++ b/src/workspace/workspace.tsx @@ -8,10 +8,12 @@ import { LabelLanguageSelector, TranslationBundle, TranslatedText } from '../cor import { ElementTypeIri } from '../data/model'; import { MetadataProvider } from '../data/metadataProvider'; +import { TemplateProperties, ColorVariant } from '../data/schema'; import { ValidationProvider } from '../data/validationProvider'; import { RestoreGeometry, restoreViewport } from '../diagram/commands'; import { TypeStyleResolver, RenameLinkProvider } from '../diagram/customization'; +import { Element } from '../diagram/elements'; import { CommandHistory, InMemoryHistory } from '../diagram/history'; import { CalculatedLayout, LayoutFunction, LayoutTypeProvider, calculateLayout, applyLayout, @@ -21,6 +23,7 @@ import { } from '../diagram/locale'; import { SharedCanvasState } from '../diagram/sharedCanvasState'; +import { AnnotationElement, AnnotationLink } from '../editor/annotationCells'; import { DataDiagramModel } from '../editor/dataDiagramModel'; import { EntityElement, EntityGroup, EntityGroupItem } from '../editor/dataElements'; import { EditorController } from '../editor/editorController'; @@ -29,6 +32,7 @@ import { } from '../editor/elementGrouping'; import { OverlayController } from '../editor/overlayController'; +import { NoteTemplate, NoteLinkTemplate } from '../templates/noteAnnotation'; import { DefaultLinkTemplate } from '../templates/defaultLinkTemplate'; import { StandardTemplate } from '../templates/standardTemplate'; @@ -55,6 +59,10 @@ export interface WorkspaceProps { * * By default, the colors are assigned deterministically based on total * hash of type strings. + * + * For non-{@link EntityElement entity} elements, the {@link Element.elementState} + * is checked for {@link TemplateProperties.ColorVariant} template state property + * instead. */ typeStyleResolver?: TypeStyleResolver; /** @@ -133,6 +141,15 @@ export class Workspace extends React.Component { private readonly resolveTypeStyle: TypeStyleResolver; private readonly cachedTypeStyles: WeakMap, ProcessedTypeStyle>; private readonly cachedGroupStyles: WeakMap, ProcessedTypeStyle>; + // TODO: use colors from theme directly + private readonly annotationStyles = new Map([ + ['default', {color: '#bec3c9'}], + ['primary', {color: '#337ab7'}], + ['success', {color: '#5cb85c'}], + ['info', {color: '#54c7ec'}], + ['warning', {color: '#ffba00'}], + ['danger', {color: '#c9302c'}], + ]); private readonly layoutTypeProvider: LayoutTypeProvider; @@ -171,8 +188,18 @@ export class Workspace extends React.Component { model.setLanguage(defaultLanguage); const view = new SharedCanvasState({ - defaultElementTemplate: StandardTemplate, - defaultLinkTemplate: DefaultLinkTemplate, + defaultElementResolver: element => { + if (element instanceof AnnotationElement) { + return NoteTemplate; + } + return StandardTemplate; + }, + defaultLinkResolver: linkTypeId => { + if (linkTypeId === AnnotationLink.typeId) { + return NoteLinkTemplate; + } + return DefaultLinkTemplate; + }, defaultLayout, renameLinkProvider, }); @@ -281,7 +308,8 @@ export class Workspace extends React.Component { } else if (element instanceof EntityGroup) { return this.getGroupTypeStyle(element); } else { - return this.getElementTypeStyle([]); + const style = this.tryGetColorVariantStyle(element); + return style ??this.getElementTypeStyle([]); } }; @@ -330,6 +358,16 @@ export class Workspace extends React.Component { return processedStyle; } + private tryGetColorVariantStyle(element: Element): ProcessedTypeStyle | undefined { + const {elementState} = element; + const colorVariant = + elementState?.[TemplateProperties.ColorVariant] as ColorVariant | undefined; + if (colorVariant || element instanceof AnnotationElement) { + return this.annotationStyles.get(colorVariant ?? 'default'); + } + return undefined; + } + private onPerformLayout: WorkspaceContext['performLayout'] = async params => { const { canvas: targetCanvas, layoutFunction, selectedElements, animate, signal, diff --git a/styles/main.scss b/styles/main.scss index 9ba27e47..c11cdf62 100644 --- a/styles/main.scss +++ b/styles/main.scss @@ -10,7 +10,6 @@ @forward "diagram/spinner"; @forward "editor/authoringState"; -@forward "editor/dragEditLayer"; @forward "editor/editEntityForm"; @forward "editor/editRelationForm"; @forward "editor/elementSelector"; @@ -22,11 +21,13 @@ @forward "theme/themeLight"; @forward "utility/draggableHandle"; +@forward "utility/dragLinkMover"; @forward "utility/dropdown"; @forward "utility/inlineEntity"; @forward "utility/listElementView"; @forward "utility/noSearchResults"; @forward "utility/progressBar"; +@forward "utility/resizableBox"; @forward "utility/searchInput"; @forward "utility/searchResults"; @forward "utility/viewportDock"; @@ -54,5 +55,6 @@ @forward "templates/classic"; @forward "templates/defaultLink"; @forward "templates/groupPaginator"; +@forward "templates/noteAnnotation"; @forward "templates/round"; @forward "templates/standard"; diff --git a/styles/mixin/_icons.scss b/styles/mixin/_icons.scss index e946092f..e893d870 100644 --- a/styles/mixin/_icons.scss +++ b/styles/mixin/_icons.scss @@ -26,3 +26,20 @@ margin-right: 3px; } } + +@mixin carbon-icon($name) { + @include icon("@images/carbon-design/" + $name + ".svg") +} + +@mixin carbon-icon-button($name) { + display: flex; + align-items: center; + + &::before { + @include carbon-icon($name); + } + + &:not(:empty)::before { + margin-right: 3px; + } +} diff --git a/styles/templates/_noteAnnotation.scss b/styles/templates/_noteAnnotation.scss new file mode 100644 index 00000000..e37093be --- /dev/null +++ b/styles/templates/_noteAnnotation.scss @@ -0,0 +1,117 @@ +@use "../mixin/icons" as *; +@use "../theme/theme"; + +.reactodia-note-annotation { + width: 200px; + height: 120px; + display: grid; + align-content: center; + + border: 2px solid theme.$color-gray-500; + border-radius: theme.$border-radius-s; + + &--variant-default { + color: theme.$font-color-base; + background-color: theme.$element-background-color; + border-color: theme.$color-gray-500; + } + &--variant-primary { + color: theme.$color-primary-contrast-foreground; + background-color: theme.$color-primary-contrast-background; + border-color: theme.$color-primary; + } + &--variant-success { + color: theme.$color-success-contrast-foreground; + background-color: theme.$color-success-contrast-background; + border-color: theme.$color-success; + } + &--variant-info { + color: theme.$color-info-contrast-foreground; + background-color: theme.$color-info-contrast-background; + border-color: theme.$color-info; + } + &--variant-warning { + color: theme.$color-warning-contrast-foreground; + background-color: theme.$color-warning-contrast-background; + border-color: theme.$color-warning; + } + &--variant-danger { + color: theme.$color-danger-contrast-foreground; + background-color: theme.$color-danger-contrast-background; + border-color: theme.$color-danger; + } + + &--editing { + align-content: unset; + } + + &__editor { + margin: 0; + padding: 10px; + font-size: 18px; + outline: none; + word-break: break-all; + pointer-events: none; + + text-align: center; + } + + &--editing &__editor { + cursor: text; + pointer-events: all; + } + + &__controls { + position: absolute; + top: 10px; + right: -10px; + transform: translate(100%, 0%); + width: max-content; + + display: flex; + flex-direction: column; + gap: theme.$spacing-base; + } + + &__style-bold { + @include carbon-icon-button("text--bold"); + } + &__style-italic { + @include carbon-icon-button("text--italic"); + } + &__style-underline { + @include carbon-icon-button("text--underline"); + } + &__style-strikethrough { + @include carbon-icon-button("text--strikethrough"); + } + + &__align-left { + @include carbon-icon-button("text--align--left"); + } + &__align-center { + @include carbon-icon-button("text--align--center"); + } + &__align-right { + @include carbon-icon-button("text--align--right"); + } + + &__variant { + width: 16px; + height: 16px; + border-radius: theme.$border-radius-s; + border-top-style: solid; + border-top-width: 16px; + } +} + +.reactodia-note-link { + &__path { + --reactodia-link-stroke-color: #{theme.$color-gray-500}; + stroke-width: 2; + } + + &__label { + display: none; + } +} diff --git a/styles/theme/_common.scss b/styles/theme/_common.scss index 3d8e8a28..d2d02a27 100644 --- a/styles/theme/_common.scss +++ b/styles/theme/_common.scss @@ -107,7 +107,10 @@ --reactodia-canvas-background-color: var(--reactodia-background-color); --reactodia-viewport-dock-margin: 10px; - --reactodia-selection-single-box-shadow: 0 0 5px 0 #d8956d inset; + --reactodia-selection-link-color: #d8956d; + --reactodia-selection-single-box-margin: 5px; + --reactodia-selection-single-box-color: #d8956d; + --reactodia-selection-single-box-shadow: 0 0 5px 0 var(--reactodia-selection-single-box-color) inset; --reactodia-navigator-scrollable-pane-fill: var(--reactodia-navigator-background-fill); --reactodia-navigator-viewport-fill: var(--reactodia-canvas-background-color); diff --git a/styles/theme/_theme.scss b/styles/theme/_theme.scss index 478edc57..a49f2bf4 100644 --- a/styles/theme/_theme.scss +++ b/styles/theme/_theme.scss @@ -167,7 +167,10 @@ $viewport-dock-margin: var(--reactodia-viewport-dock-margin); /* Halo and Selection */ $selection-icon-filter: var(--reactodia-selection-icon-filter); +$selection-link-color: var(--reactodia-selection-link-color); $selection-multiple-box-shadow: var(--reactodia-selection-multiple-box-shadow); +$selection-single-box-color: var(--reactodia-selection-single-box-color); +$selection-single-box-margin: var(--reactodia-selection-single-box-margin); $selection-single-box-shadow: var(--reactodia-selection-single-box-shadow); /* Navigator */ diff --git a/styles/editor/_dragEditLayer.scss b/styles/utility/_dragLinkMover.scss similarity index 95% rename from styles/editor/_dragEditLayer.scss rename to styles/utility/_dragLinkMover.scss index bfeb13b3..0692ecdd 100644 --- a/styles/editor/_dragEditLayer.scss +++ b/styles/utility/_dragLinkMover.scss @@ -1,6 +1,6 @@ @use "../theme/theme"; -.reactodia-drag-edit-layer { +.reactodia-drag-link-mover { overflow: visible; &__highlight-overlay { diff --git a/styles/utility/_draggableHandle.scss b/styles/utility/_draggableHandle.scss index a8b33d14..1c4ae1d4 100644 --- a/styles/utility/_draggableHandle.scss +++ b/styles/utility/_draggableHandle.scss @@ -5,10 +5,13 @@ $corner-inner: calc(theme.$draggable-handle-corner-width / 2); @mixin _draggable-handle-side { position: absolute; - opacity: 0; background-color: theme.$draggable-handle-side-color; - &:hover { + &:empty { + opacity: 0; + } + + &:empty:hover { opacity: 0.1; } } @@ -17,10 +20,13 @@ $corner-inner: calc(theme.$draggable-handle-corner-width / 2); position: absolute; width: 0; height: 0; - border-style: solid; - border-radius: theme.$border-radius-base; - &::before { + &:empty { + border-style: solid; + border-radius: theme.$border-radius-base; + } + + &:empty::before { content: ""; position: absolute; width: 0; @@ -36,8 +42,11 @@ $corner-inner: calc(theme.$draggable-handle-corner-width / 2); @include _draggable-handle-side; width: 100%; - height: theme.$draggable-handle-side-width; cursor: ns-resize; + + &:empty { + height: theme.$draggable-handle-side-width; + } } &--dock-n { top: 0; } @@ -48,9 +57,12 @@ $corner-inner: calc(theme.$draggable-handle-corner-width / 2); @include _draggable-handle-side; top: 0; - width: theme.$draggable-handle-side-width; height: 100%; cursor: ew-resize; + + &:empty { + width: theme.$draggable-handle-side-width; + } } &--dock-w { left: 0; } @@ -68,7 +80,7 @@ $corner-inner: calc(theme.$draggable-handle-corner-width / 2); border-color: theme.$draggable-handle-corner-color transparent transparent transparent; &::before { - top: -10px; + top: calc(-1 * $corner-size); border-color: theme.$draggable-handle-corner-color transparent transparent transparent; } @@ -106,7 +118,7 @@ $corner-inner: calc(theme.$draggable-handle-corner-width / 2); border-color: transparent transparent theme.$draggable-handle-corner-color transparent; &::before { - bottom: -10px; + bottom: calc(-1 * $corner-size); border-color: transparent transparent theme.$draggable-handle-corner-color transparent; } diff --git a/styles/utility/_resizableBox.scss b/styles/utility/_resizableBox.scss new file mode 100644 index 00000000..740c6656 --- /dev/null +++ b/styles/utility/_resizableBox.scss @@ -0,0 +1,72 @@ +@use "../theme/theme"; + +$resizable-box-bar-size: 10px; +$resizable-box-border-width: var(--reactodia-resizable-box-border-width); +$resizable-box-color: var(--reactodia-resizable-box-color); + +.reactodia-resizable-box { + border: $resizable-box-border-width solid $resizable-box-color; + + &__handle { + background-color: unset; + + &.reactodia-draggable-handle--dock-n, + &.reactodia-draggable-handle--dock-s, + &.reactodia-draggable-handle--dock-w, + &.reactodia-draggable-handle--dock-e { + display: flex; + justify-content: center; + align-items: center; + } + + &.reactodia-draggable-handle--dock-n { + margin-top: calc(-0.5 * $resizable-box-border-width); + } + &.reactodia-draggable-handle--dock-s { + margin-bottom: calc(-0.5 * $resizable-box-border-width); + } + &.reactodia-draggable-handle--dock-w { + margin-left: calc(-0.5 * $resizable-box-border-width); + } + &.reactodia-draggable-handle--dock-e { + margin-right: calc(-0.5 * $resizable-box-border-width); + } + + rect { + stroke-width: 2; + } + + circle, + rect { + stroke: $resizable-box-color; + fill: theme.$canvas-background-color; + } + + &:hover { + circle, + rect { + fill: $resizable-box-color; + } + } + } + + &__corner { + position: absolute; + left: -10px; + top: -10px; + width: 20px; + height: 20px; + } + + &__vertical { + position: absolute; + width: 30px; + height: $resizable-box-bar-size; + } + + &__horizontal { + position: absolute; + width: $resizable-box-bar-size; + height: 30px; + } +} diff --git a/styles/widgets/_halo.scss b/styles/widgets/_halo.scss index cb11eb4c..c647fcad 100644 --- a/styles/widgets/_halo.scss +++ b/styles/widgets/_halo.scss @@ -2,9 +2,41 @@ .reactodia-halo { position: absolute; - pointer-events: none; + left: calc( + var(--reactodia-halo-left) - var(--reactodia-selection-single-box-margin) + ); + top: calc( + var(--reactodia-halo-top) - var(--reactodia-selection-single-box-margin) + ); + width: calc( + var(--reactodia-halo-width) + 2 * var(--reactodia-selection-single-box-margin) + ); + height: calc( + var(--reactodia-halo-height) + 2 * var(--reactodia-selection-single-box-margin) + ); - border: 1.5px dashed #d8956d; + pointer-events: none; + border: 1.5px dashed theme.$selection-single-box-color; border-radius: theme.$border-radius-s; box-shadow: theme.$selection-single-box-shadow; + + &--resizable { + border: unset; + box-shadow: unset; + } + + &__resizer { + --reactodia-resizable-box-border-width: 3px; + --reactodia-resizable-box-color: #{theme.$color-primary-lighter}; + + position: absolute; + left: var(--reactodia-selection-single-box-margin); + top: var(--reactodia-selection-single-box-margin); + right: var(--reactodia-selection-single-box-margin); + bottom: var(--reactodia-selection-single-box-margin); + } + + &__resizer > * { + pointer-events: all; + } } diff --git a/styles/widgets/_haloLink.scss b/styles/widgets/_haloLink.scss index d2d9bd2a..6596a83b 100644 --- a/styles/widgets/_haloLink.scss +++ b/styles/widgets/_haloLink.scss @@ -1,12 +1,16 @@ +@use "../theme/theme"; + .reactodia-halo-link { &__label-highlight { position: absolute; pointer-events: none; - border-bottom: 2px solid #d8956d; + border-bottom: 2px solid theme.$selection-link-color; } &__path-highlight { fill: none; - /* Invisible by default but allows to be customized externally */ + stroke: theme.$selection-link-color; + stroke-width: 4; + opacity: 0.3; } } diff --git a/styles/widgets/_selectionAction.scss b/styles/widgets/_selectionAction.scss index 01fb4b4a..dc69d6d4 100644 --- a/styles/widgets/_selectionAction.scss +++ b/styles/widgets/_selectionAction.scss @@ -142,4 +142,8 @@ &__establish-link { background-image: url("@codicons/plug.svg"); } + + &__annotate { + background-image: url("@codicons/note.svg"); + } }