constructor(props) {
   super(props);
   this.state = {
     editorState: props.editorState
       ? EditorState.createWithContent(convertFromRaw(props.editorState))
       : EditorState.createWithContent(ContentState.createFromText('Insert text ...'))
   };
 }
export default (text, plugins) => {
  const compositeDecorator = createCompositeDecorator(plugins);
  return EditorState.createWithContent(
    ContentState.createFromText(text),
    compositeDecorator,
  );
};
        const getCell = (i, j) => {
            const cellContentState = cells[i] && cells[i][j]
                ? convertFromRaw(cells[i][j])
                : ContentState.createFromText('');

            return new HTMLGenerator(cellContentState, ['table']).html();
        };
Example #4
0
 it('should get selected block key', () => {
   const contentState = ContentState.createFromText('we need to connect the bluetooth SSL capacitor!');
   const block = contentState.getFirstBlock();
   const blockKey = block.getKey();
   const editorState = EditorState.createWithContent(contentState);
   expect(getSelectedBlockKey(editorState)).toEqual(blockKey);
 });
Example #5
0
 componentWillMount () {
   this.props.dispatch(openFile(this.props.filename))
   this.setState({
     editorState: this.props.content ? EditorState.createWithContent(
       ContentState.createFromText(this.props.content)
     ) : EditorState.createEmpty()
   })
 }
Example #6
0
 componentWillReceiveProps (nextProps) {
   if (nextProps.filename !== this.props.filename) {
     this.props.dispatch(openFile(nextProps.filename))
   }
   this.setState({
     editorState: nextProps.content ? EditorState.createWithContent(
       ContentState.createFromText(nextProps.content)
     ) : EditorState.createEmpty()
   })
 }
Example #7
0
  constructor (props) {
    super(props)

    this.state = {
      editorState: EditorState.createWithContent(
        ContentState.createFromText(this.props.nodeId),
        createHighlightDecorator()
      ),
      suggestions: mentions
    }
  }
Example #8
0
 constructor(props) {
   super(props);
   this.state = {
     editorState: EditorState.createWithContent(ContentState.createFromText(props.content))
   };
   this.focus = () => this.refs.editor.focus();
   this.onChange = (editorState) => this.setState({ editorState });
   this.handleKeyCommand = (command) => this.onHandleKeyCommand(command);
   this.toggleBlockType = (type) => this.onToggleBlockType(type);
   this.toggleInlineStyle = (style) => this.onToggleInlineStyle(style);
   this.saveContent = () => this.onSaveContent();
 }
/**
 * @name getInitialContent
 * @param {Object} ctrl Controller hosting the editor
 * @returns {ContentState} DraftJS ContentState object.
 * @description Gets the initial content state of the editor based on available information.
 * If an editor state is available as saved in the DB, we use that, otherwise we attempt to
 * use available HTML. If none are available, an empty ContentState is created.
 */
function getInitialContent(ctrl) {
    // we have an editor state stored in the DB
    if (typeof ctrl.editorState === 'object') {
        return convertFromRaw(ctrl.editorState);
    }

    // we have only HTML (possibly legacy editor2 or ingested item)
    if (ctrl.value) {
        return fromHTML(ctrl.value);
    }

    return ContentState.createFromText('');
}
Example #10
0
 componentWillUpdate(nextProps) {
   const currentPostId = this.props.params && this.props.params.postId;
   const nextPostId = nextProps.params && nextProps.params.postId;
   if (nextPostId && nextPostId !== currentPostId) {
     this.props.fetchSinglePostAsync(nextPostId);
   }
   if (nextProps.editor.post._id && (nextProps.editor.post._id !== this.props.editor.post._id)) {
     if (nextProps.editor.post.content) {
       this.setState({
         editorState: EditorState.createWithContent(ContentState.createFromText(nextProps.editor.post.content)),
       });
     } else {
       this.setState({
         editorState: EditorState.createEmpty(),
       });
     }
   }
 }
Example #11
0
  it('should return the list of attachments', () => {
    let contentState = ContentState.createFromText('');
    contentState = contentState.createEntity(ENTITY_TYPES.image, ENTITY_MUTABILITY.immutable, {
      mimeType: 'image/png',
      src: 'my-img.png',
      title: 'My image'
    });
    const imgEntityKey = contentState.getLastCreatedEntityKey();
    let editorState = EditorState.createWithContent(contentState);
    editorState = AtomicBlockUtils.insertAtomicBlock(editorState, imgEntityKey, ' ');

    // $FlowFixMe DraftEntityType is too restrictive in DraftJS (see https://github.com/facebook/draft-js/issues/868 )
    contentState = contentState.createEntity(ENTITY_TYPES.document, ENTITY_MUTABILITY.immutable, {
      mimeType: 'application/pdf',
      src: 'my-file.pdf',
      title: 'My pdf'
    });
    const docEntityKey = contentState.getLastCreatedEntityKey();
    editorState = AtomicBlockUtils.insertAtomicBlock(editorState, docEntityKey, ' ');
    contentState = editorState.getCurrentContent();
    const blocks = contentState.getBlocksAsArray();

    const actual = getAttachments(editorState);
    const expected = [
      {
        blockKey: blocks[1].getKey(),
        entityKey: imgEntityKey,
        entityType: 'IMAGE',
        mimeType: 'image/png',
        title: 'My image',
        src: 'my-img.png'
      },
      {
        blockKey: blocks[3].getKey(),
        entityKey: docEntityKey,
        entityType: 'DOCUMENT',
        mimeType: 'application/pdf',
        src: 'my-file.pdf',
        title: 'My pdf'
      }
    ];
    expect(actual).toEqual(expected);
  });
it('should not do anything on backspace if something is selected', () => {
  const initialText = 'hello';

  const currentContent = ContentState.createFromText(initialText);
  const selectInitialtext = SelectionState.createEmpty(
    currentContent
      .getBlockMap()
      .first()
      .getKey()
  );
  const editorState = EditorState.create({
    allowUndo: true,
    currentContent,
    // Focus the entire initial word
    selection: selectInitialtext.set('focusOffset', initialText.length)
  });

  expect(handleKeyCommand(editorState, 'backspace')).toEqual(undefined);
});
it('should not do anything if anything other than an indentation is deleted', () => {
  const initialText = 'hello';
  const currentContent = ContentState.createFromText(initialText + '    ');
  // "hello    "
  //       ^ cursor here
  const cursorAfterWord = SelectionState.createEmpty(
    currentContent
      .getBlockMap()
      .first()
      .getKey()
  )
    .set('anchorOffset', initialText.length)
    .set('focusOffset', initialText.length);
  const editorState = EditorState.create({
    allowUndo: true,
    currentContent,
    selection: cursorAfterWord
  });

  expect(handleKeyCommand(editorState, 'backspace')).toEqual(undefined);
});
Example #14
0
it('should replace selected content with the tab', () => {
  const evt = { preventDefault: jest.fn() };
  const initialText = 'hello';

  const currentContent = ContentState.createFromText(initialText);
  const selectInitialtext = SelectionState.createEmpty(
    currentContent
      .getBlockMap()
      .first()
      .getKey()
  );
  const before = EditorState.create({
    allowUndo: true,
    currentContent,
    // Focus the entire initial word
    selection: selectInitialtext.set('focusOffset', initialText.length)
  });

  const after = onTab(evt, before);
  expect(toPlainText(before)).toEqual(initialText);
  expect(toPlainText(after)).toEqual(tabs(1));
});
it('should delete indentation from the middle', () => {
  const initialText = 'hello            ';
  const currentContent = ContentState.createFromText(initialText);
  // "hello            "
  //              ^ cursor here
  const cursorAtEndOfLine = SelectionState.createEmpty(
    currentContent
      .getBlockMap()
      .first()
      .getKey()
  )
    .set('anchorOffset', initialText.length - 4)
    .set('focusOffset', initialText.length - 4);
  const editorState = EditorState.create({
    allowUndo: true,
    currentContent,
    selection: cursorAtEndOfLine
  });

  const result = handleKeyCommand(editorState, 'backspace');
  expect(toPlainText(result)).toEqual('hello        ');
});
Example #16
0
  it('should call the callback with start/end offsets for all link entities within a block', () => {
    const callbackSpy = jest.fn();

    let contentState = ContentState.createFromText('I will input the solid state PNG port');
    contentState = contentState.createEntity(ENTITY_TYPES.link, ENTITY_MUTABILITY.mutable, {
      target: '_blank',
      title: 'My link',
      url: 'https://en.wikipedia.org/wiki/Portable_Network_Graphics'
    });
    const contentBlock = contentState.getFirstBlock();
    const blockKey = contentBlock.getKey();
    let selection = createSelectionState(blockKey, 0, 4);
    const linkEntityKey = contentState.getLastCreatedEntityKey();
    contentState = Modifier.applyEntity(contentState, selection, linkEntityKey);
    contentState = contentState.createEntity(ENTITY_TYPES.image, ENTITY_MUTABILITY.mutable, {
      externalUrl: 'my-img.jpg'
    });
    selection = createSelectionState(blockKey, 8, 14);
    const mentionEntityKey = contentState.getLastCreatedEntityKey();
    contentState = Modifier.applyEntity(contentState, selection, mentionEntityKey);

    contentState = contentState.createEntity(ENTITY_TYPES.link, ENTITY_MUTABILITY.mutable, {
      target: '_blank',
      title: 'My link',
      url: 'https://en.wikipedia.org/wiki/Portable_Network_Graphics'
    });
    selection = createSelectionState(blockKey, 12, 16);
    const linkEntityKey2 = contentState.getLastCreatedEntityKey();
    contentState = Modifier.applyEntity(contentState, selection, linkEntityKey2);

    strategy(contentState.getFirstBlock(), callbackSpy, contentState);
    expect(callbackSpy.mock.calls.length).toBe(2);
    expect(callbackSpy.mock.calls[0][0]).toBe(0);
    expect(callbackSpy.mock.calls[0][1]).toBe(4);
    expect(callbackSpy.mock.calls[1][0]).toBe(12);
    expect(callbackSpy.mock.calls[1][1]).toBe(16);
  });
Example #17
0
/**
 * Compiler
 */
function compiler(ast) {
  var config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

  /**
   * Create an empty ContentState object
   */
  var entityContentState = _draftJs.ContentState.createFromText('');

  /**
   * Called for each node in the abstract syntax tree (AST) that makes up the
   * state contained in the store. We identify the node by `type`
   *
   * @param  {Array} Array representing a single node from the AST
   * @param  {Boolean} first Is the first item in the AST?
   * @param  {Boolean} last Is the last item in the AST?
   *
   * @return {Array} Result of the visit/render
   */
  function visit(node, opts) {
    var type = node[0];
    var content = node[1];
    var visitMethod = 'visit' + (0, _camelCase2.default)(type, true);
    return destinations[visitMethod](content, opts);
  }

  /**
   * A reference object so we can call our dynamic functions in `visit`
   * @type {Object}
   */
  var destinations = {

    /**
     * Called for each node that identifies as a 'block'. Identifies the block
     * _type_ function from the `renderers`
     *
     * @param  {Array} Array representing a single block node from the AST
     * @param  {Boolean} first Is the first item in the AST?
     * @param  {Boolean} last Is the last item in the AST?
     *
     * @return {Function} Result of the relevant `renderers.block[type]`
     * function
     */

    visitBlock: function visitBlock(node, opts) {
      var childBlocks = [];
      var depth = opts.depth || 0;
      var type = node[_dataSchema2.default.block.type];
      var children = node[_dataSchema2.default.block.children];
      var data = (0, _immutable.Map)(node[_dataSchema2.default.block.data]);

      // Build up block content
      var text = '';
      var characterList = (0, _immutable.List)();

      children.forEach(function (child) {
        var type = child[0];
        var childData = visit(child, { depth: depth + 1 });
        // Nested blocks will be added to the `blocks` array
        // when visited
        if (type === 'block') {
          childBlocks.push(childData);
        } else {
          // Combine the text and the character list
          text = text + childData.text;
          characterList = characterList.concat(childData.characterList);
        }
      });

      var contentBlock = new _draftJs.ContentBlock({
        key: (0, _draftJs.genKey)(),
        text: text,
        type: type,
        characterList: characterList,
        depth: depth,
        data: data
      });

      return [contentBlock, childBlocks];
    },


    /**
     * Called for each node that identifies as a 'entity'. Identifies the
     * entity _type_ function from the `renderers`
     *
     * @param  {Array} Array representing a single entity node from the AST
     * @param  {Boolean} first Is the first item in the AST?
     * @param  {Boolean} last Is the last item in the AST?
     *
     * @return {Function} Result of the relevant `renderers.entity[type]`
     * function
     */
    visitEntity: function visitEntity(node) {
      var type = node[_dataSchema2.default.entity.type];
      var mutability = node[_dataSchema2.default.entity.mutability];
      var data = node[_dataSchema2.default.entity.data];
      var children = node[_dataSchema2.default.entity.children];

      // Create the entity and note its key
      // run over all the children and aggregate them into the
      // format we need for the final parent block
      entityContentState = entityContentState.createEntity(type, mutability, data);
      var entityKey = entityContentState.getLastCreatedEntityKey();
      var text = '';
      var characterList = (0, _immutable.List)();

      children.forEach(function (child) {
        var childData = visit(child, { entityKey: entityKey });
        // Combine the text and the character list
        text = text + childData.text;
        characterList = characterList.concat(childData.characterList);
      });

      return {
        text: text,
        characterList: characterList
      };
    },


    /**
     * Called for each node that identifies as a 'inline'. Identifies the
     * entity _type_ function from the `renderers`
     *
     * @param  {Array} Array representing a single inline node from the AST
     * @param  {Boolean} first Is the first item in the AST?
     * @param  {Boolean} last Is the last item in the AST?
     *
     * @return {Function} Result of the relevant `renderers.inline[type]`
     * function
     */
    visitInline: function visitInline(node) {
      var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

      var styles = node[_dataSchema2.default.inline.styles];
      var text = node[_dataSchema2.default.inline.text];

      // Convert the styles into an OrderedSet
      var style = (0, _immutable.OrderedSet)(styles.map(function (style) {
        return style;
      }));

      // Create a List that has the style values for each character
      var charMetadata = _draftJs.CharacterMetadata.create({
        style: style,
        entity: opts.entityKey || null
      });

      // We want the styles to apply to the entire range of `text`
      var characterMeta = (0, _immutable.Repeat)(charMetadata, text.length);

      var characterList = characterMeta.toList();

      return {
        text: text,
        characterList: characterList
      };
    }
  };

  if (ast.length > 0) {
    // Procedurally visit each node
    var blocks = (0, _flatten2.default)(ast.map(visit));
    // Build a valid ContentState that combines the blocks and the entity map
    // from the entityContentState
    return _draftJs.ContentState.createFromBlockArray(blocks, entityContentState.getEntityMap());
  } else {
    return _draftJs.ContentState.createFromText('');
  }
}
Example #18
0
    EditorCore.prototype.Reset = function Reset() {
        var defaultValue = this.props.defaultValue;

        this.setEditorState(_draftJs.EditorState.push(this.state.editorState, defaultValue ? defaultValue.getCurrentContent() : _draftJs.ContentState.createFromText(''), 'remove-range'));
    };
const createStateFromText = defaultText => {
  if (!defaultText) {
    return {
      editorState: EditorState.createEmpty(syntaxDecorator),
      viewEditorState: EditorState.createEmpty(renderDecorator),
    };
  }

  let codeBlockMap = OrderedMap();
  let listMap = OrderedMap();
  let tableMap = OrderedMap();
  let blockQuoteMap = OrderedMap();

  const parsedText = defaultText
    .replace(regex.block.codeBlock, (match, p1, p2, p3, offset) => {
      codeBlockMap = codeBlockMap.set(offset.toString(), match.replace(/\n$/, ''));
      return `$$CODEBLOCK__${offset}$$`;
    })
    .replace(regex.block.list, (match, offset) => {
      listMap = listMap.set(offset.toString(), match.replace(/\n$/, ''));
      const lastChar = match.charAt(match.length - 1);
      return `$$LIST__${offset}$$${lastChar === '\n' && lastChar}`;
    })
    .replace(regex.block.table, (match, offset) => {
      tableMap = tableMap.set(offset.toString(), match.replace(/\n$/, ''));
      const lastChar = match.charAt(match.length - 1);
      return `$$TABLE__${offset}$$${lastChar === '\n' && lastChar}`;
    })
    .replace(regex.block.blockquote, (match, offset) => {
      blockQuoteMap = blockQuoteMap.set(offset.toString(), match.replace(/\n$/, ''));
      const lastChar = match.charAt(match.length - 1);
      return `$$BLOCKQUITE__${offset}$$${lastChar === '\n' && lastChar}`;
    })
    .replace(regex.block.indentCodeBlock, (match, p1, p2, offset) => {
      codeBlockMap = codeBlockMap.set(offset.toString(), match.replace(/\n+$/, ''));
      const trailingNewLine = /(\n+)$/.exec(match);
      return `$$CODEBLOCK__${offset}$$${trailingNewLine && trailingNewLine[1]}`;
    });

  const defaultContent = ContentState.createFromText(parsedText);

  const tokenHackRegexes = [
    {
      withoutGroup: /\$\$BLOCKQUITE__\d+\$\$/g,
      withGroup: /\$\$BLOCKQUITE__(\d+)\$\$/g,
      mapObject: blockQuoteMap
    },
    {
      withoutGroup: /\$\$LIST__\d+\$\$/g,
      withGroup: /\$\$LIST__(\d+)\$\$/g,
      mapObject: listMap
    },
    {
      withoutGroup: /\$\$CODEBLOCK__\d+\$\$/g,
      withGroup: /\$\$CODEBLOCK__(\d+)\$\$/g,
      mapObject: codeBlockMap
    },
    {
      withoutGroup: /\$\$TABLE__\d+\$\$/g,
      withGroup: /\$\$TABLE__(\d+)\$\$/g,
      mapObject: tableMap
    },
  ];

  let parsedContent = defaultContent;

  tokenHackRegexes
    .forEach(re => {
      defaultContent.getBlockMap()
        .filter(block => block.getText().match(new RegExp(re.withoutGroup)))
        .forEach(block => {
          const text = block.getText();
          const match = new RegExp(re.withGroup).exec(text);
          parsedContent = Modifier.replaceText(
            parsedContent,
            SelectionState.createEmpty(block.getKey()).set('focusOffset', text.length),
            re.mapObject.get(match[1])
          );
        });
    });

  return {
    editorState: EditorState.createWithContent(parsedContent, syntaxDecorator),
    viewEditorState: EditorState.createWithContent(parsedContent, renderDecorator),
  };
};
Example #20
0
 EditorCore.ToEditorState = function ToEditorState(text) {
     var createEmptyContentState = _draftJs.ContentState.createFromText((0, _exportText.decodeContent)(text) || '');
     var editorState = _draftJs.EditorState.createWithContent(createEmptyContentState);
     return _draftJs.EditorState.forceSelection(editorState, createEmptyContentState.getSelectionAfter());
 };
Example #21
0
  Mention.prototype.render = function render() {
    var _classnames,
        _this2 = this;

    var _props = this.props,
        prefixCls = _props.prefixCls,
        style = _props.style,
        tag = _props.tag,
        multiLines = _props.multiLines,
        editorKey = _props.editorKey,
        suggestionStyle = _props.suggestionStyle,
        placeholder = _props.placeholder,
        defaultValue = _props.defaultValue,
        className = _props.className,
        notFoundContent = _props.notFoundContent,
        getSuggestionContainer = _props.getSuggestionContainer,
        readOnly = _props.readOnly,
        disabled = _props.disabled,
        placement = _props.placement,
        mode = _props.mode;
    var suggestions = this.state.suggestions;
    var Suggestions = this.Suggestions;

    var editorClass = (0, _classnames3['default'])(className, (_classnames = {}, _classnames[prefixCls + '-wrapper'] = true, _classnames.readonly = readOnly, _classnames.disabled = disabled, _classnames.multilines = multiLines, _classnames));
    var editorProps = this.controlledMode ? { value: this.state.value } : {};
    var defaultValueState = defaultValue && _draftJs.EditorState.createWithContent(typeof defaultValue === 'string' ? _draftJs.ContentState.createFromText(defaultValue) : defaultValue, this._decorator);
    return _react2['default'].createElement(
      'div',
      { className: editorClass, style: style, ref: function ref(wrapper) {
          return _this2._wrapper = wrapper;
        } },
      _react2['default'].createElement(
        _rcEditorCore.EditorCore,
        (0, _extends3['default'])({
          ref: function ref(editor) {
            return _this2._editor = editor;
          },
          prefixCls: prefixCls,
          style: style,
          multiLines: multiLines,
          editorKey: editorKey,
          plugins: this.plugins,
          defaultValue: defaultValueState,
          placeholder: placeholder,
          onFocus: this.onFocus,
          onBlur: this.onBlur,
          onChange: this.onEditorChange
        }, editorProps, {
          readOnly: readOnly || disabled
        }),
        _react2['default'].createElement(Suggestions, {
          mode: tag ? 'immutable' : mode,
          prefix: this.getPrefix(),
          prefixCls: prefixCls,
          style: suggestionStyle,
          placement: placement,
          notFoundContent: notFoundContent,
          suggestions: suggestions,
          getSuggestionContainer: getSuggestionContainer ? function () {
            return getSuggestionContainer(_this2._wrapper);
          } : null,
          onSearchChange: this.props.onSearchChange,
          onSelect: this.props.onSelect,
          noRedup: this.props.noRedup
        })
      )
    );
  };
 beforeEach(() => {
   editorState = EditorState.createWithContent(
     ContentState.createFromText(sourceText)
   );
   contentState = editorState.getCurrentContent();
 });
 const createEditorState = text =>
   EditorState.createWithContent(ContentState.createFromText(text));
Example #24
0
const createNewEditorState = (text) => {
   var editorState;
   if (text) {
      // editorState = EditorState.createWithContent(ContentState.createFromText(text),
      //    new CompositeDecorator([
      //       {
      //          strategy: hashtagStrategy,
      //          component: HashtagSpan,
      //       }
      //    ])
      // );
      editorState = EditorState.push(EditorState.createEmpty(compositeDecorator), ContentState.createFromText(text), 'insert-characters');
   }
   else {
      editorState = EditorState.createEmpty(compositeDecorator);
   }

   return EditorState.moveFocusToEnd(editorState);
}
Example #25
0
    EditorCore.prototype.Reset = function Reset() {
        var defaultValue = this.props.defaultValue;

        var contentState = defaultValue ? defaultValue.getCurrentContent() : _draftJs.ContentState.createFromText('');
        var updatedEditorState = _draftJs.EditorState.push(this.state.editorState, contentState, 'remove-range');
        this.setEditorState(_draftJs.EditorState.forceSelection(updatedEditorState, contentState.getSelectionBefore()));
    };
Example #26
0
 const createEditorStateFromText = (text) => {
   const contentState = ContentState.createFromText(text);
   return EditorState.createWithContent(contentState);
 };
Example #27
0
function reducer(state: Immutable<AppState>, action: Action): Immutable<AppState> {
  switch (action.type) {
  case 'ACTIVATE_TAB': {
    return state.set('activeTab', action.key);
  }
  case 'CLOSE_PATIENT_SETTINGS': {
    return state.set('patientSettingsOpen', false);
  }
  case 'COMMIT_TAB': {
    const currentState = state.editors[state.activeTab].state;
    const currentContent = currentState.getCurrentContent();

    // Strip inactive toggles.
    const noToggles = stripInactiveToggles(currentContent);

    // Strip inactive toggle groups.
    const noGroups = stripToggleGroups(noToggles);

    // Strip all entity metadata.
    const currentText = noGroups.getPlainText();
    const nextContent = ContentState.createFromText(currentText);

    return state.setIn(
      ['editors', state.activeTab, 'state'],
      EditorState.push(currentState, nextContent, 'change-block-data')
    );
  }
  case 'EDIT': {
    return state.setIn(
      ['editors', state.activeTab, 'state'],
      action.next
    );
  }
  case 'INIT_TAB': {
    return state
      .set(
        'editors',
        state.editors.concat({
          patient: {
            firstName: '',
            lastName: '',
            dob: '',
            gender: '',
            address: '',
          },
          state: null,
        })
      )
      .set('activeTab', state.editors.length);
  }
  case 'MACROS_EDIT': {
    return state.set(
      'macroSettingsEditorState',
      action.next
    );
  }
  case 'MACROS_EXPAND': {
    return state.setIn(
      ['editors', state.activeTab, 'state'],
      expandMacro(
        state.editors[state.activeTab].state,
        state.macros,
        state.editors[state.activeTab].patient
      )
    );
  }
  case 'MACROS_NEW_LINE': {
    return state.set(
      'macroSettingsEditorState',
      RichUtils.insertSoftNewline(
        state.macroSettingsEditorState
      )
    );
  }
  case 'MACROS_OPEN': {
    return state
      .set('macroSettingsOpen', true)
      .set(
        'macroSettingsEditorState',
        EditorState.createWithContent(
          ContentState.createFromText(jsonPretty(state.macros))
        )
      );
  }
  case 'MACROS_SAVE': {
    return state
      .set('macroSettingsOpen', false)
      .set(
        'macroSettingsEditorState',
        EditorState.createEmpty()
      )
      .set(
        'macros',
        JSON.parse(state.macroSettingsEditorState.getCurrentContent().getPlainText())
      );
  }
  case 'NEW_LINE': {
    return state.setIn(
      ['editors', state.activeTab, 'state'],
      RichUtils.insertSoftNewline(
        state.editors[state.activeTab].state
      )
    );
  }
  case 'FINALIZE_TEMPLATE': {
    return state.setIn(
      ['editors', state.activeTab, 'state'],
      createFromTemplate(action.template, state.editors[state.activeTab].patient)
    );
  }
  case 'OPEN_PATIENT_SETTINGS': {
    return state.set('patientSettingsOpen', true);
  }
  case 'REMOVE_TAB': {
    return state.set(
      'editors',
      state.editors.filter(
        (value: Immutable<TabState>, i: number): bool => (i !== action.key)
      )
    );
  }
  case 'TOGGLE': {
    const toggle = Entity.get(action.key);
    const updated = Entity.replaceData(
      action.key,
      {
        active: !toggle.getIn(['data']).active,
      }
    );
    const newKey = Entity.add(updated);
    return state.setIn(
      ['editors', state.activeTab, 'state'],
      replaceEntity(state.editors[state.activeTab].state, action.key, newKey)
    );
  }
  case 'UPDATE_PATIENT': {
    return state.setIn(
      ['editors', state.activeTab, 'patient'],
      action.patient
    );
  }
  default: {
    return state;
  }
  }
}
Example #28
0
 EditorCore.prototype.SetText = function SetText(text) {
     var createTextContentState = _draftJs.ContentState.createFromText(text || '');
     var editorState = _draftJs.EditorState.push(this.state.editorState, createTextContentState, 'change-block-data');
     this.setEditorState(_draftJs.EditorState.moveFocusToEnd(editorState), true);
 };
Example #29
0
function editorStateFromText(text) {
    var content = Draft.ContentState.createFromText(text);
    return Draft.EditorState.createWithContent(content);
}
Example #30
0
 componentWillMount() {
   var content = this.props.node && this.props.node.props && this.props.node.props.content;
   this.setState({editorState: content !== undefined ? EditorState.createWithContent(convertFromRaw(content)) : EditorState.createWithContent(ContentState.createFromText('Type your content'))});
 }