More work towards flexible widget API

This commit is contained in:
Rainer Simon 2020-09-12 10:06:29 +02:00
parent b1db6e90e0
commit 7874622ad4
5 changed files with 35 additions and 19 deletions

View File

@ -1,7 +1,7 @@
import React from 'preact/compat';
import { useState, useRef, useEffect } from 'preact/hooks';
import Environment from '../Environment';
import DOMWidget from './widgets/DOMWidget';
import { getWidget, DEFAULT_WIDGETS } from './widgets';
import setPosition from './setPosition';
import i18n from '../i18n';
@ -139,7 +139,9 @@ const Editor = props => {
}
};
const widgets = props.widgets ? props.widgets.map(fn => <DOMWidget widget={fn} />) : [];
// Use default comment + tag widget unless host app overrides
const widgets = props.config.widgets ?
props.widgets.map(getWidget) : DEFAULT_WIDGETS;
return (
<div ref={element} className="r6o-editor">

View File

@ -1,15 +0,0 @@
import Editor from './Editor';
import CommentWidget from './widgets/comment/CommentWidget';
import TagWidget from './widgets/tag/TagWidget';
/** Standard widgets included by default **/
const DEFAULT_WIDGETS = {
COMMENT: CommentWidget,
TAG: TagWidget
};
Editor.CommentWidget = CommentWidget;
Editor.TagWidget = TagWidget;
export { Editor };

View File

@ -1,15 +1,17 @@
import React, { Component } from 'preact/compat';
export default class DOMWidget extends Component {
export default class WrappedWidget extends Component {
constructor(props) {
super(props);
this.element = React.createRef();
}
componentWillReceiveProps(next) {
if (this.element.current) {
if (this.props.annotation !== next.annotation) {
const widgetEl = this.props.widget({
annotation: next.annotation,
readOnly: next.readOnly,

View File

@ -0,0 +1,27 @@
import React from 'react';
import CommentWidget from './comment/CommentWidget'
import TagWidget from './tag/TagWidget';
import WrappedWidget from './WrappedWidget';
/** Standard widgets included by default **/
const BUILTIN_WIDGETS = {
COMMENT: <CommentWidget />,
TAG: <TagWidget />
};
/** Defaults to use if there's no overrides from the host app **/
export const DEFAULT_WIDGETS = [
<CommentWidget />, <TagWidget />
]
export const getWidget = arg => {
if (typeof arg === 'string' || arg instanceof String) {
return BUILTIN_WIDGETS[arg];
} else if (typeof arg === 'function' || arg instanceof Function) {
return <WrappedWidget widget={arg} />
} else if (React.isValidElement(arg)) {
return arg;
} else {
throw `${arg} is not a valid plugin`
}
}

View File

@ -1,9 +1,9 @@
export { default as Editor } from './editor/Editor';
export { default as Environment } from './Environment';
export { default as I18n } from './i18n';
export { default as TextAnnotator } from './TextAnnotator';
export { default as WebAnnotation } from './WebAnnotation';
export * from './editor';
export * from './highlighter';
export * from './relations';
export * from './selection';