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 @@
+
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 @@
+
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 @@
+
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 @@
+
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 @@
+
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 @@
+
\ 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 @@
+
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}
+ />
+