# react-start-editor

> 基于 React 和 antd 的编辑器（同时支持富文本和 markdown，基于 braft-editor 和 react-markdown-editor-lite 的在封装）

Latest version **1.1.7** (published 2021-08-02) · MIT license · 0 weekly downloads

## Install

```sh
npm install react-start-editor
pnpm add react-start-editor
yarn add react-start-editor
bun add react-start-editor
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.7 |
| Published | 2021-08-02 |
| First published | 2021-02-19 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 11 |
| Unpacked size | 147.3 KB |
| Known vulnerabilities | 0 (+26 in 3 direct dependencies) |
| Install scripts | no |
| Author | clairoll |
| Maintainers | qinchuan123, clairoll, dmhhh |
| Keywords | react, markdown, rich |

## Links

- npm: https://www.npmjs.com/package/react-start-editor
- npm.io page: https://npm.io/package/react-start-editor

## Dependencies (11)

- [xss](https://npm.io/package/xss.md) ^1.0.9
- [antd](https://npm.io/package/antd.md) ^4.9.4
- [axios](https://npm.io/package/axios.md) ^0.21.1
- [markdown-it](https://npm.io/package/markdown-it.md) ^11.0.0
- [braft-editor](https://npm.io/package/braft-editor.md) ^2.3.9
- [highlight.js](https://npm.io/package/highlight.js.md) ^10.5.0
- [markdown-it-toc](https://npm.io/package/markdown-it-toc.md) ^1.1.0
- [markdown-it-xss](https://npm.io/package/markdown-it-xss.md) ^1.0.2
- [braft-extensions](https://npm.io/package/braft-extensions.md) ^0.1.0
- [react-markdown-editor-lite](https://npm.io/package/react-markdown-editor-lite.md) ^1.2.2
- [@liradb2000/markdown-it-mermaid](https://npm.io/package/@liradb2000/markdown-it-mermaid.md) ^0.4.1

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 1.1.7 (latest) — 2021-08-02
- 1.1.6 — 2021-08-02
- 1.1.5 — 2021-05-10
- 1.1.4 — 2021-04-15
- 1.1.3 — 2021-04-14
- 1.1.2 — 2021-04-12
- 1.1.1 — 2021-03-25
- 1.1.0 — 2021-03-22
- 1.0.3 — 2021-03-11
- 1.0.2 — 2021-03-11
- 1.0.0 — 2021-02-19

## README

# react-ritch-markdown

基于 React 和 antd 的编辑器（同时支持富文本和 markdown，基于 braft-editor 和 react-markdown-editor-lite 的在封装）

## 基本使用

### 1. 编辑器的基本使用

下载

`npm i react-start-editor`

引入

`import Editors from "react-start-editor/lib"`

使用

```React
// 编辑器
<Editors.Editors />
```

#### 1.1支持参数

##### 1.1.1 公共参数

| 名称         | 描述             | 类型     | 默认            |                  备注                  |
| ------------ | ---------------- | -------- | --------------- | :------------------------------------: |
| onChange     | 获取编辑器的值   | function |                 |                  必传                  |
| isRich       | 是否显示富文本   | Boolean  | false           | true：显示富文本；false：显示 markdown |
| defaultValue | 默认值           | string   | null            |                                        |
| imgUrl       | 图片上传地址     | string   | /api/site/image |                                        |
| IUpName      | 图片上传名       | string   | file            |                                        |
| IUpData      | 图片上传额外参数 | object   | undefind        |                                        |
| fillUrl      | 文件上传地址     | string   | /api/site/annex |                                        |
| FUpName      | 文件上传名       | string   | file            |                                        |
| FUpData      | 文件上传额外参数 | object   | undefind        |                                        |

##### 1.1.2 markdown参数

| 名称         | 描述                     | 类型     | 默认             | 备注                    |
| ------------ | ------------------------ | -------- | ---------------- | ----------------------- |
| mdRender     | markdown 渲染规则        |          | markdown-it      | 需要传入整个markdown-it |
| mdStyle      | markdown样式             | object   | {height:'500px'} |                         |
| mdPasteImg   | markdown复制图片上传函数 | function | undefind         |                         |
| mdImgChange  | 图片上传回调函数         | function | undefind         |                         |
| mdFillChange | 文件上传回调函数         | function | undefind         |                         |

##### 1.1.3 富文本参数

| 名称           | 描述                   | 类型     | 默认     | 备注               |
| -------------- | ---------------------- | -------- | -------- | ------------------ |
| richPasetImg   | 富文本复制图片上传函数 | function | undefind |                    |
| richImgChange  | 图片上传回调函数       | function | undefind | 必须返回拼接后的值 |
| richFillChange | 文件上传回调函数       | function | undefind | 必须返回拼接后的值 |
| richXssOption  | 富文本xss配置对象      | object   | xssOption|                  |

```javascript
let xssOption = {
      whiteList: {
        a: ["href", "title", "target"],
        img: ["src", "alt", "target", "id", "title"],
        video: ["src", "control"],
        audio: ["src", "control"],
        span: ["style"],
        p: ["style"],
        div: ["style", "class", "id"],
        strong: [],
        em: [],
        u: [],
        hr: [],
        sup: [],
        sub: [],
        ul: [],
        ol: [],
        li: [],
        b: [],
        table: ["border", "style", "collapse"],
        tr: [],
        td: ["colspan", "rowspan"],
        blockquote: [],
        code: [],
        pre: [],
        br: [],
        font:["face"],
      },
    };
```

#### 1.2 方法实例

##### 1.2.1 onChange 实例

获取编辑器的值

```
onChange(value) {
	console.log(value)
}
```

##### 1.2.2 mdPasteImg实例

```jsx
// 粘贴图片上传
  myUploadFn = (file) => {
    const { IUpData, IUpName, imgUrl } = this.props;
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = () => {
        let obj = new FormData();
        if (IUpData) {
          for (let key in IUpData) {
            obj.append(key, IUpData[key]);
          }
        }
        obj.append(IUpName, file);
        Axios.post(imgUrl, obj).then((res) => {
          let { data } = res;
          resolve(data.url);
        });
      };
      reader.readAsDataURL(file);
    });
  };
```

##### 1.2.3 richPasetImg实例

```jsx
// 粘贴图片上传
  myUploadFn = (param) => {
    const { IUpData, IUpName, imgUrl } = this.props;
    let obj = new FormData();
    if (IUpData) {
      for (let key in IUpData) {
        obj.append(key, IUpData[key]);
      }
    }
    obj.append(IUpName, param.file);
    Axios.post(imgUrl, obj)
      .then((res) => {
        if (res.data && res.data.code === 0) {
          let data = res.data.data;
          param.success({
            url: data.url,
            meta: {
              id: data.id,
              title: data.name,
              alt: data.name,
            },
          });
        }
      })
      .catch((err) => {
        param.error({
          msg: "上传失败!",
        });
      });
  };
```

##### 1.2.4 mdImgChange实例

```jsx
const mdImgChange = (info, set) => {
    if (info.file.status === 'done') {
      set.setFieldsValue({
        url: info.file.response.data.url,
      });
    } else if (info.file.status === 'error') {
      message.error('图片上传失败');
    }
  };
```

##### 1.2.5 mdFillChange实例

```jsx
const mdImgChange = (info, set) => {
    if (info.file.status === 'done') {
       // 插入Markdown
        let str = `[${info.file.response.data.file_name}](${info.file.response.data.url})`;
       set.insertText(str);
    } else if (info.file.status === 'error') {
      message.error('图片上传失败');
    }
  };
```

##### 1.2.6 richImgChange 实例

```jsx
//图片上传回调
  const richImgChange = (info, value, set) => {
    if (info.file.status === 'done') {
      // 富文本图片上传成功，将图片地址加入富文本内容
      let data = set.insertMedias(value, [{ type: 'IMAGE', url: info.file.response.data.url }]);
      return data; // 必须返回拼接的值
    } else if (info.file.status === 'error') {
      message.error('图片上传失败');
    }
  };
```

##### 1.2.7 richFillChange实例

```jsx
//文件上传回调
 const  uploadFileChange = (info, value，set) => {
      if (info.file.status === "done") {
        // 富文本文件上传成功，将图片地址加入富文本内容
        let data = set.insertHTML(
          value,
          `<a target="_blank" href="${info.file.response.data.url}">${info.file.response.data.file_name}</a>`
        )
        return data // 必须返回拼接的值
      } else if (info.file.status === "error") {
        message.error("文件上传失败");
      }
  };
```

#### 1.3 Muse 实例

挂载 markdown 插件

```React
Editors.Editors.Muse(插件, 配置)
```

#### 1.4 基本使用示例

```jsx

const mdParser = new MarkdownIt({
  breaks: true, // 转换段落里的 '\n' 到 <br>。
  linkify: true, // 将类似 URL 的文本自动转换为链接。
  typographer: true, // 启用一些语言中立的替换 + 引号美化
  html: true,
  highlight: function(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value;
      } catch (__) {}
    }
    return ""; // 使用额外的默认转义
  },
})
  .use(require("markdown-it-toc"))
  .use(require("markdown-it-xss"), {
    xss: {
      escapeHtml(html) {
        return html;
      },
    },
  })
  .use(require('@liradb2000/markdown-it-mermaid'));

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            defaultValue: '',
        }
    }

    // 获取编辑器的内容
    onChange = (value) => {
        console.log(value)
    }

    refadd = React.createRef();

	// 设置默认值
    componentDidMount() {
        this.setState({ defaultValue: '1236' })
    }

    handleClickLastValue = async () => {
        this.setState({ defaultValue: '7896' })
    }

    // 清空编辑器
    handleClear = () => {
        this.refadd.current.clearContent()
    }

    render() {
        const { defaultValue } = this.state
        return <div>
            <Button onClick={() => this.handleClickLastValue()}>
                恢复上一次内容
            </Button>
            <Button onClick={() => this.handleClear()}>
                清除内容
            </Button>
            <Editors.Editors
                ref={this.refadd}
                onChange={this.onChange}
                isRich={true}
                defaultValue={defaultValue}
                imgUrl= "/api/site/image",
                fillUrl= "/api/site/annex",
                mdStyle={{height:'500px'}}
                mdRender= {mdParser}
            />
        </div>
    }
}
```

### 2. 展示器的使用

#### 2.1 支持参数

| 名称     | 描述              | 类型    | 默认        |                  备注                  |
| -------- | ----------------- | ------- | ----------- | :------------------------------------: |
| isRich   | 是否显示富文本    | Boolean | false       | true：显示富文本；false：显示 markdown |
| value    | 内容              | string  | null        |                                        |
| mdRender | markdown 渲染规则 |         | markdown-it |        需要传入整个markdown-it         |

#### 2.2 基本使用实例

```jsx
const mdParser = new MarkdownIt({
  breaks: true, // 转换段落里的 '\n' 到 <br>。
  linkify: true, // 将类似 URL 的文本自动转换为链接。
  typographer: true, // 启用一些语言中立的替换 + 引号美化
  html: true,
  highlight: function(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value;
      } catch (__) {}
    }
    return ""; // 使用额外的默认转义
  },
})
  .use(require("markdown-it-toc"))
  .use(markdownItMermaid)
  .use(require("markdown-it-xss"), {
    xss: {
      whiteList: {
        a: ["href", "title", "target"],
        img: ["src"],
      },
    },
  });

class ShowEditors extends React.Component {
  constructor(props) {
    super(props);
  }
render() {
    return (
        <Editors.ShowEditors isRich={true}  value="hhhhhhhhh" mdRender={mdParser} />
    )
  }
}

```

---
_Source: https://npm.io/package/react-start-editor · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
