Giter Site home page Giter Site logo

margox / braft-editor Goto Github PK

View Code? Open in Web Editor NEW
4.6K 39.0 592.0 5.32 MB

美观易用的React富文本编辑器,基于draft-js开发

License: MIT License

HTML 0.53% JavaScript 85.10% SCSS 14.36%
draft-js rich-text-editor react wysiwyg wysiwyg-js-editor rich

braft-editor's Introduction

Braft Editor-EN

Thanks to Google Translate

A web rich text editor based on draft-js, suitable for React framework, compatible with mainstream modern browsers.

Note that the current version of the project is 2.x. If you are using 1.xx version, please refer to [Old Version Document](https://github.com/margox/braft-editor/blob/old-master/README. md)

Please understand before using

Braft Editor is an editor based on draft-js. Draft-js does not directly use HTML as the component state. It implements an EditorState type, which is essentially a JS object. In the traditional rich text editor, The piece of HTML content corresponding to EditorState is a block; this can be verified by looking at editorState.toRAW ().

The advantage of using EditorState instead of HTML strings is that a set of EditorState can be used on multiple ends, and the content produced by the editor is no longer limited to being displayed on the web platform (of course, each platform also needs to implement the corresponding EditorState to View conversion function) At the same time, it is more suitable for the component state of React.

However, in the above implementation, the biggest problem is that it cannot perfectly convert external HTML into EditorState, because its supported styles, tags, tag attributes, and so on are extremely limited, and there is no way to convert all the features in HTML to the state in EditorState. , When using third-party or historical HTML strings to initialize the editor content, and when pasting external HTML content, only a small number of styles and tag attributes supported by the editor can be retained, most of the content will be filtered or Ignore it.

Based on the above shortcomings, if your project strongly depends on the original HTML tags and attributes, etc., this editor is not recommended.

Editor-specific extension packs have been released, please see Braft Extensions

The form extension module has been released in a test version. Please upgrade craft-editor and craft-utils to the latest version and install the latest version of craft-extensions. For the usage, please see [form extension module]

Exchange feedback, please add QQ group: 725634541

Features

  • Perfect text content editing function
  • Many open editing interfaces, good scalability
  • Allows inserting multimedia content such as pictures, audio and video
  • Allows to customize the upload interface of multimedia content
  • Allow to set the image to float left and right (ie text wrapping function)
  • Allows setting the color list, font size, and fonts available to the editor
  • Allows customizing the control buttons and display order to be displayed
  • Allows adding additional custom buttons
  • Multi-language support (Simplified Chinese, Traditional Chinese, English, Polish, Japanese, Korean, Turkish)
  • ... More features under development

Thanks

Recent updates

  • 2019-08-06 v2.3.8
    • Fixed the issue that javascript statements in a tag href caused a warning
    • Merge PR # 560, # 593 , # 588, # 582
  • 2019-06-20 v2.3.7
    • Fix issues # 542, # 541 , # 467
    • Fix the problem # 512 and add the imageResizable attribute, which allows to turn off the drag and resize function of the image
  • 2019-06-18 v2.3.6
    • Supports inserting links without selecting text
    • Added allowInsertLinkText property, allowing link text to be entered when inserting a link directly, default false
  • 2019-06-14 v2.3.5
    • Perfect index.d.ts
  • 2019-06-11 v2.3.4
    • Support the retention of some more custom html attributes (need to upgrade craft-convert to v2.3.0)
    • Added Korean (kr), Japanese (jpn), Turkish (tr)
    • Add more hooks support
  • 2019-05-28 v2.3.2
    • Fixed the issue that incoming RAW strings could not be parsed normally
  • 2019-05-20 v2.3.1
    • Fixed fatal bug in v2.3.0
  • 2019-05-20 v2.3.0
  • 2019-04-29 v2.2.10
    • The picture supports dragging and resizing. Thanks to ArthasDragon for your contribution!
    • Optimized the use of pure numbers to initialize the editor's content. Thank you WzFFzW for your contribution!
    • Added fixPlaceholder attribute (Boolean), which is used to fix the problem that placeholder text is displayed abnormally in some cases. The default is false.
    • Optimize forceRender
  • 2019-03-06 v2.2.9
    • Modify index.d.ts
  • 2019-02-22 v2.2.7
    • Added boilerplate CSS files for beautifying output HTML(node_modules/braft-editor/dist/output.css)
  • 2019-02-22 v2.2.6
    • Optimize the blockRenerMap property and support passing in a function that returns a blockRenerMap object
    • Optimize the settings of subscript style
    • Optimize the display of text indentation and text alignment in the editor when colleagues are present
  • 2019-01-11 v2.2.4
    • Added the editorId property, which has the same effect as the id property, and is used to solve the problem that the id property will be overwritten in the Ant Design Form component and the extension module cannot be used normally
  • 2019-01-11 v2.2.2
    • Optimized the playback interaction between audio and video and embedded media, instead playing in the modal box
  • 2019-01-06 v2.2.1
  • 2018-12-29 v2.2.0

View history update record

installation

# Install using yarn
yarn add braft-editor
# Install using npm
npm install braft-editor --save

use

The editor supports value and onChange properties, which are similar to the native input components in React. In general, you can use this editor in the form of a typical controlled component:

import React from 'react'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'

export default class EditorDemo extends React.Component {

  state = {
      editorState: null
  }

  async componentDidMount () {
    // Assume here to get the editor content in html format from the server
    const htmlContent = await fetchEditorContent()
    // Use BraftEditor.createEditorState to convert html strings to editorState data needed by the editor
    this.setState({
      editorState: BraftEditor.createEditorState(htmlContent)
    })
  }

  submitContent = async () => {
    // Pressing ctrl + s when the editor has focus will execute this method
    // Before the editor content is submitted to the server, you can directly call editorState.toHTML () to get the HTML content
    const htmlContent = this.state.editorState.toHTML()
    const result = await saveEditorContent(htmlContent)
  }

  handleEditorChange = (editorState) => {
    this.setState({ editorState })
  }

  render () {

    const { editorState } = this.state

    return (
      <div className="my-component">
        <BraftEditor
          value={editorState}
          onChange={this.handleEditorChange}
          onSave={this.submitContent}
        />
      </div>
    )

  }

}

Of course, this editor also supports the defaultValue property, so you can also use this editor as a uncontrolled component.

For more introduction, please see Detailed Document

Buy me a beer

If you want to thank this editor for saving time for your project, or simply like this editor, you can scan the code and appreciate a few dollars to invite me for a beer!

  

    支付宝           WeChat

braft-editor's People

Contributors

1123612483 avatar arthasdragon avatar augustocunha avatar ayuka-bg avatar bertyhell avatar charanjit-singh avatar cnzsb avatar cpu220 avatar crper avatar dependabot[bot] avatar didibear avatar fameoflight avatar gencer avatar hughescuit avatar jas0ncn avatar kvkens avatar lili668668 avatar margox avatar matrixiao88 avatar maximusft avatar meowtec avatar pkrefta avatar pointline avatar rayronvictor avatar rockhentai avatar sayjeyhi avatar symind avatar wzffzw avatar xwuji avatar yyl1999 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

braft-editor's Issues

初始化问题

请问怎么设置初值,我看到content是个对象
{
blocks: [],
entityMap: {}
}

但是有没有提供一个吧html转换成这种content的方法用以初始化呢?

很好用而且很漂亮的一款富文本编辑器

我有一个需求是需要将所有的粘贴进来的内容都处理成纯文本(或者说移除原来所有的格式),想问下有哪个api能够处理类似的需求么(比如监听粘贴事件,或者onHtmlBeforeChange之类的)?

保存数据转换成html上传到服务器,再取回来转换成raw后图片消失了

保存成html上传,取回来时将其转换成raw后,赋值给editorProps的initialContent,但是里面的图片消失了;
这个是保存成功后取回的数据
image

// 转换成raw
initEditorState = () => {
    // content是html字符串
    const { content } = this.props;
    const blockHTML = convertFromHTML(content);
    const contentState = ContentState.createFromBlockArray(blockHTML.contentBlocks, blockHTML.entityMap);
    return convertToRaw(contentState);
  }

// 编辑器的配置
    const initialContent = this.initEditorState();
    const editorProps = {
      initialContent,
}

初始化后的编辑器,应该是要有图片的(取回的数据是有图片的):
image

还请帮忙看下,谢谢

chrome浏览器插入链接bug

  1. 插入链接必须选中文本才可以,否则即使输入连接也不会给出任何提示
  2. 插入链接完毕以后不是immutable状态,期望是一次性删除,而不是和删除普通文本一样
  3. 插入链接完毕后续录入不应该还是链接状态

@margox

视频功能

你好,能否增加视频上传功能, 像上传图片一样? 这样更加完美!!!

toggleSelectionBlockType的疑问??

尝试了很多次,toggleSelectionBlockType这个方法好像是改变光标所在区块的区块类型,而不是选中内容的区块类型。。。

有什么方法能做到让选中的内容独立一行么?

代码块内tab键的提议

在代码块内能否处理下tab键,现在一tab就跳出编辑器了,其实我只是想在代码块内加个tab

定义onHTMLChange钩子函数,输入文本时会报Uncaught Error: block is not a BlockNode

从在线demo拷贝的代码 http://margox.github.io/braft-editor/
本地运行时,在文本区域输入文本会报错:
Uncaught Error: block is not a BlockNode

image

不知道是不是我改什么东西导致的,有人遇到类似的情况吗

`import React from 'react'
import { connect } from 'dva'
import { routerRedux } from 'dva/router'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/braft.css'

class Editortest extends React.Component {

state = {
htmlContent: ''
}

render() {

const editorProps = {
  placeholder: 'Hello World!',
  initialContent: '',
  onHTMLChange: this.handleHTMLChange,
  viewWrapper: '.demo',
  // 增加自定义预览按钮
  extendControls: [
    {
      type: 'split',
    },
    {
      type: 'button',
      text: '预览',
      className: 'preview-button',
      onClick: () => {
        window.open().document.write(this.state.htmlContent)
      }
    }, {
      type: 'dropdown',
      text: <span>下拉菜单</span>,
      component: <h1 style={{width: 200, color: '#ffffff', padding: 10, margin: 0}}>Hello World!</h1>
    }, {
      type: 'modal',
      text: <span style={{paddingRight: 10,paddingLeft: 10}}>弹窗</span>,
      className: 'modal-button',
      modal: {
        title: '这是一个弹窗',
        showClose: true,
        showCancel: true,
        showConfirm: true,
        confirmable: true,
        onConfirm: () => console.log(1),
        onCancel: () => console.log(2),
        onClose: () => console.log(3),
        children: (
          <div style={{width: 480, height: 320, padding: 30}}>
            <span>Hello World!</span>
          </div>
        )
      }
    }
  ]
}

return (
  <div className="demo">
    <BraftEditor {...editorProps} />
  </div>
)

}

handleHTMLChange = (htmlContent) => {
this.setState({ htmlContent })
}

}

export default connect(({ editortest }) => ({ editortest }))(Editortest)`

文字无法居中

1.1.9版本,只是简单的引入了尝试后发现点击居中 居左都无效

每个按钮点击时,都会submit 整个form, 怎么办?

{getFieldDecorator('title', { rules: [{ required: true, message: '请输入标题', }], })( )}
            <FormItem
              {...formItemLayout}
              label="正文"
            >
              {getFieldDecorator('content', {
                rules: [{
                  required: true, message: '请输入正文',
                }],
              })(
                <BraftEditor {...editorProps} />
              )}
            </FormItem>

上传视频问题?

当我上传了一个视频,回到编辑器,鼠标点击刚上传的视频(意思是将光标移到刚上传的视频),然后再点击媒体选择一个视频,按下确定控制台报“Uncaught TypeError: Cannot read property 'getKey' of undefined at t.a.selectNextBlock ”错误。
音频和视频有这种问题。如果编辑器只有图片,就不会报错, 图片会自动向下插入一张图片。音频和视频需要将光标移到空白处才能插入, 麻烦帮看一下!

图片的toolbar是否可以开放api,用于自定义

1、图片的toolbar是否可以开放api,用于自定义(例如显示或隐藏某功能,自定义样式)
2、是否考虑图片拖拽功能
3、media: { image: true, // 开启图片插入功能 video: false, // 开启视频插入功能 audio: false, // 开启音频插入功能 uploadFn: this.uploadFn, validateFn: this.validateFn, },
在配置中已取消视频和音频的插入功能,但是 图片-添加网络资源 的弹窗仍会有视频和音频,这里是否也可以开放api,用于自定义?
image

用webpack对js压缩后,点击工具栏的多媒体图标时报错

先占个坑…

用webpack打包时不进行JS压缩可以正常使用。压缩后发布到线上想要传图片,点击工具栏时报了一个错: xx is not a function,怀疑是压缩后变量名重复?

import React from 'react'
import PropTypes from 'prop-types'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/braft.css'

const controls = [
  'bold',
  'italic',
  'underline',
  'strike-through',
  'text-color',
  'split',
  'text-align',
  'split',
  'list_ul',
  'list_ol',
  'split',
  'link',
  'media',
]

const colors = [
  '#000000',
  '#333333',
  '#999999',
  '#ffffff',
  '#1C89EA',
  '#13ce66',
  '#f7ba2a',
  '#ff4949',
]

const media = upload => ({
  image: true,
  video: true,
  audio: true,
  uploadFn: upload,
})

const RichTextEditor = ({ value, onChange, upload }) => (
  <BraftEditor
    contentFormat="html"
    initialContent={value}
    onHTMLChange={onChange}
    controls={controls}
    colors={colors}
    media={media(upload)}
  />
)

RichTextEditor.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func,
  upload: PropTypes.func,
}

export default RichTextEditor

组件卸载处理和多实例共存

使用过程中感觉这个编辑器还可以做得更加精细点,主要有下面几个点:

  1. 组件卸载时的销毁处理(添加到Body上的class移除、事件绑定的移除、数据清理等);
  2. 多个实例共存时是否能正常运行(使用中发现内容串扰的问题);
  3. 组件更新时的内容覆写问题(期望能覆写);

插入代码的问题

很喜欢这个编辑器,已经集成到我的博客了,希望作者能一直更下去

看到作者刚刚回家过年了,先把issue提了吧,Orz....

插入多行代码后,不会显示在一个代码块里,而是每行代码显示在一个单独的代码块,下面上图:
image
image

设置中文字体切换无效

const fontFamilies = [
{
name: '黑',
family: 'SimHei, Helvetica, sans-serif'
}, {
name: '宋',
family: 'SimSun, Helvetica, sans-serif'
}, {
name: '楷体',
family: 'KaiTi, Helvetica, sans-serif'
}, {
name: '微软雅黑',
family: 'Microsoft YaHei , Helvetica, sans-serif'
}, {
name: 'Araial',
family: 'Arial, Helvetica, sans-serif'
}, {
name: 'Georgia',
family: 'Georgia, serif'
}, {
name: 'Impact',
family: 'Impact, serif'
}, {
name: 'Monospace',
family: '"Courier New", Courier, monospace'
}, {
name: 'Tahoma',
family: "tahoma, arial, 'Hiragino Sans GB', 宋体, sans-serif"
}
]

初始值中如果有图片,使用图片排版会出错

在使用initialContent属性时
如果参数中有图片则使用图片排版功能会报错
DraftModifier.js:144 Uncaught TypeError: Cannot read property 'merge' of undefined at DraftModifier.js:144 at immutable.js:3004 at immutable.js:3376 at immutable.js:1365 at ArrayMapNode.iterate.HashCollisionNode.iterate (immutable.js:1714) at Map.__iterate (immutable.js:1363) at flatDeep (immutable.js:3373) at immutable.js:3375 at immutable.js:2822 at ArraySeq.__iterate (immutable.js:375)
image

不管是使用html 还是raw作为初始值都会出错,但是如果是新增的图片就不会有这个错误

图片排版是指这个:
image

我代码

import React from 'react';
import { upload } from '@hlj/ajax/src/ajax';
import Popup from '@hlj/widget/Popup';
import { convertFromHTML } from 'draft-js';
import { isString } from 'lodash';
import BraftEditor from 'braft-editor';

import 'braft-editor/dist/braft.css';
import './style.scss';

class Marked extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      content: this.props.source,
      editing: false
    };
  }

  componentDidMount() {
    const { source } = this.props;
    if (isString(source)) {
      const content = convertFromHTML(source);
      this.setState({ content })
    }
  }

  render() {
    const { title } = this.props;
    const { editing, content } = this.state;

    return (
      <div className="marked field">
        <label>{title}</label>
        <div>
          <button type="button" className="ui button"
              onClick={() => this.setState({ editing: true })}>
            <i className="edit icon"></i>
          </button>
        </div>
        {
          editing &&
            <Popup className="draft-editor">
              <div className="bg" onClick={::this.onClose}></div>
              <div className="wrapper">
                <BraftEditor
                  initialContent={content}
                  controls={[
                    'undo', 'redo', 'split', 'font-size', 'font-family', 'text-color',
                    'bold', 'italic', 'underline', 'strike-through', 'superscript',
                    'subscript', 'text-align', 'split', 'headings', 'list_ul', 'list_ol',
                    'split', 'link', 'split', 'media'
                  ]}
                  media={{
                    image: true, // 开启图片插入功能
                    video: false, // 开启视频插入功能
                    audio: false, // 开启音频插入功能
                    uploadFn: ::this.uploadImg // 指定上传函数
                  }}
                  onChange={::this.onChange}
                  onHTMLChange={::this.onHTMLChange}
                />
              </div>
            </Popup>
        }
      </div>
    );
  }

  onHTMLChange(html) {
    this.setState({ html });
  }

  onChange(raw) {
    this.setState({ content: raw });
  }

  onClose() {
    const { content, html } = this.state;
    const { update } = this.props;
    console.log(content);
    debugger
    update && update({ source: content, html });
    this.setState({ editing: false });
  }

  uploadImg(e) {
    if (!e || !e.file) {
      return Promise.reject();
    }

    return upload(e.file, '/images').then(({ url }) => (
      e.success({ url })
    )).catch(ex => {
      window.console.error(ex);
      e.error({ msg: 'unable to upload.' });
    });
  }
}

export default Marked;


initalContent初始值的时候 会报错

const editorProps = {
height: 500,
initialContent: '

hello world!

',
// onChange: this.handleChange,
onHTMLChange: this.handleChange,
}

报的错误:
Uncaught TypeError: Cannot convert undefined or null to object
at Function.keys ()
at convertFromRawToDraftState (convertFromRawToDraftState.js:40)
at t.N.setContent (braft.js:1)
at t.value (braft.js:1)
at eval (ReactCompositeComponent.js:262)
at measureLifeCyclePerf (ReactCompositeComponent.js:73)
at eval (ReactCompositeComponent.js:261)
at CallbackQueue.notifyAll (CallbackQueue.js:74)
at ReactReconcileTransaction.close (ReactReconcileTransaction.js:78)
at ReactReconcileTransaction.closeAll (Transaction.js:207)

initialContent为HTML内容时,并且存在img标签时会报错

initialContent为HTML内容时,并且存在img标签时会报错,如下

const editorProps = {
            height: 500,
            contentFormat: 'html',
            initialContent: '<div><img /></div><p></p>',
            onHTMLChange: this.handleHTMLChange,
            media: {
                image: true, // 开启图片插入功能
                video: false, // 开启视频插入功能
                audio: false, // 开启音频插入功能
                validateFn: null, // 指定本地校验函数,说明见下文
                uploadFn: this.uploadFn.bind(this) // 指定上传函数,说明见下文
            },
            controls: [
                'bold', 'italic', 'underline', 'strike-through', 'text-align', 'split',
                'headings', 'list_ul', 'list_ol', 'blockquote', 'split',
                'link', 'media'
            ]
        }

vendor.bundle.js:392 Uncaught Error: Unknown DraftEntity key: 1.
at invariant (vendor.bundle.js:392)
at Object.__get (app.bundle.js:7263)
at ContentState.getEntity (app.bundle.js:7933)
at app.bundle.js:51105
at findRangesImmutable (app.bundle.js:7004)
at ContentBlock.findEntityRanges (app.bundle.js:6281)
at r (app.bundle.js:51104)
at app.bundle.js:53940
at Array.forEach ()
at CompositeDraftDecorator.getDecorations (app.bundle.js:53928)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.