All files / annotationEditor annotationEditor.tsx

48.48% Statements 16/33
37.5% Branches 3/8
40% Functions 4/10
48.28% Lines 14/29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 901x 1x 1x   1x                                                                   1x   1x   1x             1x 1x                   1x 2x 1x           1x                                       1x  
import { lazy } from '@fuselab/ui-shared/lib';
import { ContentBlock, ContentState, Editor, EditorState } from 'draft-js';
import * as React from 'react';
import { AnnotatedText, Annotation } from '../models';
import classNames from './annotationEditor.classNames';
 
export interface AnnotationEditorAttributes {
  document: AnnotatedText[];
}
 
export interface AnnotationEditorActions {
  insert(text: AnnotatedText);
  remove(text: AnnotatedText);
  update(text: AnnotatedText, newText: string);
  tag(text: AnnotatedText, tag: Annotation);
  unTag(text: AnnotatedText, tag: Annotation);
}
 
export type AnnotationEditorProps = AnnotationEditorAttributes & AnnotationEditorActions;
 
export interface AnnotationEditorState {
  editorState: EditorState;
}
 
function initContent(props: AnnotationEditorProps): ContentState {
  return ContentState.createFromBlockArray(props.document.map((t) => {
    return new ContentBlock({
      type: 'paragraph',
      key: t.key,
      text: t.text,
      data: t
    });
  }));
}
 
/**
 * document editor for annotation
 */
export class AnnotationEditor extends React.Component<AnnotationEditorProps, AnnotationEditorState> {
  constructor(props: AnnotationEditorProps) {
    super(props);
 
    this.state = {
      editorState: props.document.length
        ? EditorState.createWithContent(initContent(props))
        : EditorState.createEmpty()
    };
  }
 
  public render(): JSX.Element {
    return (
      <div className={classNames().root}>
        <Editor
          editorState={this.state.editorState}
          onChange={this.onEditorStateChange}
        />
      </div>
    );
  }
 
  @lazy()
  private get onEditorStateChange(): (s: EditorState) => void {
    return editorState => {
      this.findNewTexts(editorState);
      this.setState({ editorState });
    };
  }
 
  private findNewTexts(s: EditorState) {
    if (!s) {
      return;
    }
    const content = s.getCurrentContent();
    const blocks = content.getBlocksAsArray();
    const existingKeys = this.props.document.reduce(
      (h, x) => {
        let t = {};
        t[x.key] = true;
 
        return { ...t, ...h };
      },
      {});
 
    const newBlocks = blocks.filter(b => b.getText() && !existingKeys[b.getKey()]);
    for (let b of newBlocks) {
      this.props.insert({ key: b.getKey(), text: b.getText(), annotations: [] });
    }
  }
}