Added .onSetProperty method (issue #42)

This commit is contained in:
Rainer Simon 2021-01-17 14:01:22 +01:00
parent c1ebc07f00
commit 6d8e0bdb60
2 changed files with 23 additions and 5 deletions

View File

@ -26,8 +26,9 @@ const Editor = props => {
const element = useRef(); const element = useRef();
// Set derived annotation state // Set derived annotation state
useEffect(() => useEffect(() => {
setCurrentAnnotation(props.annotation), [ props.annotation ]); setCurrentAnnotation(props.annotation);
}, [ props.annotation ]);
// Change editor position if element has moved // Change editor position if element has moved
useEffect(() => { useEffect(() => {
@ -89,6 +90,22 @@ const Editor = props => {
}) })
); );
const onSetProperty = (property, value) => {
// A list of properties the user is NOT allowed to set
const isForbidden = [ '@context', 'id', 'type', 'body', 'target' ].includes(property);
if (isForbidden)
throw new Exception(`Cannot set ${property} - not allowed`);
if (value) {
setCurrentAnnotation(currentAnnotation.clone({ [property]: value }));
} else {
const updated = currentAnnotation.clone();
delete updated[property];
setCurrentAnnotation(updated);
}
};
const onCancel = () => const onCancel = () =>
props.onCancel(currentAnnotation); props.onCancel(currentAnnotation);
@ -130,6 +147,7 @@ const Editor = props => {
onAppendBody, onAppendBody,
onUpdateBody, onUpdateBody,
onRemoveBody, onRemoveBody,
onSetProperty,
onSaveAndClose: onOk onSaveAndClose: onOk
}) })
)} )}

View File

@ -19,9 +19,9 @@ export default class Selection {
/** Creates a copy of this selection **/ /** Creates a copy of this selection **/
clone = opt_props => { clone = opt_props => {
// Deep-clone target // Deep-clone
const clonedTarget = JSON.parse(JSON.stringify(this.underlying.target)); const cloned = new Selection();
const cloned = new Selection(clonedTarget); cloned.underlying = JSON.parse(JSON.stringify(this.underlying));
if (opt_props) if (opt_props)
cloned.underlying = { ...cloned.underlying, ...opt_props }; cloned.underlying = { ...cloned.underlying, ...opt_props };