عَلى قَدْرِ أهْلِ العَزْم تأتي العَزائِمُ
وَتأتي علَى قَدْرِ الكِرامِ المَكارمُ
وَتَعْظُمُ في عَينِ الصّغيرِ صغارُها
وَتَصْغُرُ في عَين العَظيمِ العَظائِمُ
يُكَلّفُ سيفُ الدّوْلَةِ الجيشَ هَمّهُ
وَقد عَجِزَتْ عنهُ الجيوشُ الخضارمُ
A Typescript & React project that creates a WYSIWYG Rich text/ HTML editor using Slate js.
A Typescript & React project that creates a WYSIWYG Rich text/ HTML editor using Slate js.
- 1. Getting Started
- 1.1. Installation
- 1.1.1. Using CDN
- 1.1.2. Using NPM
- 1.2. Documentation
- 1.2.1. Component Library API
- 1.2.2. Component Library API Explanation
- 1.2.3. Static API Interface
- 1.2.4. Static API Explanation
- 1.3. Editor Output Samples
- 1.4. Example Using The API
- 1.4.1. Using the Static API
- 1.4.2. Using the Component Library API
- 2. Forking Guide
- 2.1. Prerequisites
- 2.2. Installing
- 3. Built With
- 4. Main Features
- 5. Git Style
- 5.1. Message Structure
- 5.1.1. The Type
- 5.1.2. The Subject
- 5.1.3. The Body
- React + TypeScript + Vite
- Expanding the ESLint configuration
These instructions will guide you to consume the API provided by the app.
#### 1.1.1. Using CDN
Following these instructions will integrate the app into your website and will provide a globally defined API to be used.
1. Download the latest version of the app.
2. Link the app's CSS file the head of your HTML File. Example:
``HTML`
3. Link the app's Javascript file in the body of your HTML File. Example:
`HTML`
#### 1.1.2. Using NPM
Following these instructions will integrate the app into your website and will provide a react component library that provides the editor react component to be rendered.
`CLI`
npm i nagwa-html-editor
and then in your React app import the editor as follows:
`Typescript`
import NagwaHTMLEditor from "nagwa-html-editor"
Here will explain the API provided by our app that can be found under the globally defined namespace NagwaHTMLEditor.
#### 1.2.1. Component Library API
A react component is exposed and exported as default that renders the Editor component.
`ts
type Locale = "ar/eg" | "en/eg"
type UploadType = "image" | "audio" | "attachment"
type UploadFunction = (file: File) => Promise
type UploadProps = { storeUrl?: string; uploadFn?: UploadFunction; limit?: number; accept?: string[] }
type UploadConfig = string | UploadFunction | UploadProps
type Feature =
| "marks" // bold, italic, underlined, and strikethrough marks
| "color" // text color
| "scriptEffects" // sub script and super script
| "alignment"
| "directions"
| "undo-redo"
| PickLiteral
| "math-view"
| "attach" // Attach files
type MediaType = "image" | "audio" | "attachment"
interface MediaObj {
url: string
}
interface ImageObj extends MediaObj {
alt: string
}
interface AudioObj extends MediaObj {}
interface AttachmentObj extends MediaObj {
name: string
}
interface HTMLEditorProps {
uniqueKey?: string
locale?: Locale
oldValue?: string | Descendant[]
uploadImage?: UploadConfig
uploadAudio?: UploadConfig
uploadAttachment?: UploadFunction | Omit
hideToolbarOnBlur?: boolean
include?: Feature[]
exclude?: Feature[]
onInit?: ((editorAPI: EditorAPI) => void) | (() => void)
onChange?: ((value: string) => void) | (() => void)
onAttachmentClick?: (attachment: AttachmentObj, index: number) => void | ((attachment: AttachmentObj) => void) | (() => void) | null
autoFocus?: boolean
toolbarStyles?: CSSProperties
textareaStyles?: CSSProperties
}
export const NagwaHTMLEditor: React.VFC
export default NagwaHTMLEditor
`
#### 1.2.2. Component Library API Explanation
- NagwaHTMLEditor: This is the main component to be used to render an instance of the Editor and keep its state in memory. This component is exported namely and as default so that you can use the NagwaHTMLEditor name when importing or use any other name needed in your case. This is a void react component that accepts some props as follows:
- uniqueKey: This key is required and has to be unique because it stores the different editors states in an object with this uniqueKey. If it was not provided (not recommended) it will fallback to a randomly generated key so that you won't need to add a uniqueKey when you need to render only one Editor, if there's more than one please provide a uniqueKey.locale
- : The locale of the provided oldValue to set the direction of the element according to it. This property is optional and falls back to "en/eg" if not provided.oldValue
- : The old HTML value to initiate the app with. This is an optional property, if not provided the app will start with an empty state.uploadImage
- : Can be a function that handles uploading the image inputted by the user, a string url that represents a file storage or hosting service that contains images to be called by ID, or an object containing both properties, and extra. This property is optional, if not provided the feature of inserting images will not be available.uploadAudio
- : Can be a function that handles uploading the audio inputted or recorded by the user, a string url that represents a file storage or hosting service that contains audios to be called by ID, or an object containing both properties, and extra. This property is optional, if not provided the feature of inserting audios will not be available.uploadAttachment
- : Can be a function that handles uploading the file attached by the user or an object containing the function, and extra. This property is optional, if not provided the feature of attaching files will not be available.hideToolbarOnBlur
- : If this property was passed as true the toolbar will be hidden until the editor is focused. The default value is false which will make the toolbar visible at all times.include
- : An array of feature string to include these features in the editor. By default, all features are included.exclude
- : An array of feature string to exclude from the editor. By default, no feature is excluded. If both include and exclude arrays are present, the exclude array will me omitted, and only the features in the include array will be included.onInit
- : A callback function that will fire once the editor is initialized. An optional editorAPI can be expected as an argument to the function.onChange
- :A callback function that will fire with every update of the editor's value. An optional string value (the new editor's value) can be expected as an argument to the function.onAttachmentClick
- : A callback function that will fire when an attachment row is clicked. An optional attachment object and an optional index can be expected as arguments to the function. This property defaults to a function that will download the attachment when clicked. If set to null, Nothing will happen when clicking the attachment.autoFocus
- : A boolean that indicates whether or not to focus the editor if it is initialized. Defaults to false.toolbarStyles
- : A CSSProperties (styles) object that can be passed to apply styles to the toolbar.textareaStyles
- : A CSSProperties (styles) object that can be passed to apply styles to the editor's textarea.
Aside from the exported component the API extraction and deletion is implementing the following functions that are namely exported.
`ts
interface EditorAPI {
editor: CustomEditor // The slate Editor API
getValue: (includeAttachments = true) => string
getDeserializedValueWithoutAttachments: () => Descendant[]
getAttachmentsValue: () => string
getDeserializedAttachments: () => AttachmentObj
setValue: (oldValue: string, { locale?: "ar/eg" | "en/eg"; includeAttachments: boolean } = { includeAttachments: true }) => void
setDeserializedValue: (oldValue: Descendant[], shouldDeleteAttachments = true) => void
setAttachments: (oldValue: string | AttachmentObj[]) => void
clear: (shouldDeleteAttachments = true) => void
readonly isEmpty: boolean
}
function getEditorAPI(uniqueKey: string): EditorAPI // The same Static API interface (See the below section)
function deleteEditorAPI(uniqueKey: string): boolean
`
- EditorAPI:editor
- : The slate editor itselfgetValue
- : This method serializes the current editor value state into the desired HTML output. It takes an optional parameter includeAttachments. If set to true, the attachments value will be serialized also. It defaults to true.getDeserializedValueWithoutAttachments
- : This method returns the current state of the corresponding editor, without the attachments part. The state matches the structure mentioned in the @types folder.getAttachmentsValue
- : This method serializes the attachments and returns its string value.getDeserializedAttachments
- : This method returns the current state of attachment array. The state matches the structure mentioned in the @types folder.setValue
- : This method deserializes the HTML string inputted and sets the editor's state to the deserialized value. It takes an optional options object with the following properties:includeAttachments
- : If set to true, the attachments value will be set also, else, the textarea value will be set only, and the attachments will remain the same. It defaults to true.locale
- : "ar/eg" or "en/eg"setDeserializedValue
- : Sets the editor's current value from slates Descendant object array. It takes an optional parameter shouldDeleteAttachments that defaults to true. If true, will delete current attachmentssetAttachments
- : Takes an attachments HTML markup string, or an array of attachment object, and sets the attachments.deleteAttachments
- : Deletes current attachmentsclear
- : This method clears the current editor value state and empties the editable area. It takes an optional parameter shouldDeleteAttachments that defaults to true. If true, will delete current attachmentsisEmpty
- : This is a read-only property that tells you if the current state of the editor is empty or not.getEditorAPI
- : A function that accesses the store with the uniqueKey and returns the corresponding EditorAPI for this editor instance. Notice that this uniqueKey should be the same one as the one provided for the NagwaHTMLEditor component. deleteEditorAPI
This function is only namely exported.
- : A function that accesses the store with the uniqueKey and deletes the corresponding EditorAPI for this editor instance. Notice that this uniqueKey should be the same one as the one provided for the NagwaHTMLEditor component.
This function is only namely exported.
#### 1.2.3. Static API Interface
The Static library uses the same API as the component library with some differences.
`ts
type Descendant = CustomElement | CustomText
type StaticHTMLEditorProps = HTMLEditorProps & { containerId: string }
class NagwaHTMLEditor {
public static init: (config: StaticHTMLEditorProps) => EditorAPI
}
`
#### 1.2.4. Static API Explanation
The static library API uses the same API of the Component API's Interface with few different exported items.
- NagwaHTMLEditor:init
- : The main method that initiates the app with the desired config and returns EditorAPI object with utility methods.EditorConfig
- :containerId
- : The id of the HTML element to contain the app. Note that the element corresponding with the provided id will be replaced with a div element with the same provided id. This property is mandatory for the app to run, if not provided the app won't run.
Here are some editor output samples that you can get using the getValue method:
- 1 text samples (bold, italic, ... etc.):
- EN:
!Example 1 Input English Sample
` This is Bold. This is Italic. This is Underlined. This is Colored. This is Bold Italic. This is Bold and Underlined. This is Bold and Colored. This is Italic and Underlined. This is Italic and Colored. This is Underlined and Colored. This is Bold, Italic, and Underlined. This is Bold, Italic, and Colored This is Bold, Underlined, and Colored. This is Italic, Underlined, and Colored This is Bold, Italic, Underlined and Colored.HTML`
- FR:
!Example 1 Input French Sample
` C'est audacieux. C'est en italique. Ceci est souligné. C'est coloré. Ceci est en gras italique. Ceci est gras et souligné. C'est audacieux et coloré. Ceci est en italique et souligné. Ceci est en italique et en couleur. Ceci est souligné et coloré. Ceci est en gras, italique et souligné. Ceci est gras, italique et coloré. Ceci est gras, souligné et coloré. Ceci est en italique, souligné et coloré. Ceci est gras, italique, souligné et coloré.HTML`
- AR:
!Example 1 Arabic Input Sample
` هذا غامق. هذا مائل. هذا مسطر. هذا ملون. هذا غامق ومائل. هذا غامق ومسطر. هذا غامق وملون. هذا مائل ومسطر. هذا مائل وملون. هذا مسطر وملون. هذا غامق، مائل ومسطر. هذا غامق، مائل وملون. هذا غامق، مسطر وملون. هذا مائل، مسطر وملون هذا غامق، مائل، مسطر وملون.HTML`
- 2 Text (bold, italic, ... etc.) + inline math:
- EN:
!Example 2 Input English Sample
`HTML`
This is Bold and here's an equation:
value="x+y=z"
lang="en"
style="display: inline-block"
read-only="true"
> >.
This is Italic and here's an equation : >
value="\sin\left(\frac{x}{y}\right)"
lang="en"
style="display: inline-block"
read-only="true"
> >.
This is Underlined and here's an equation:
value="\sqrt[3]{x^2+y^2}"
lang="en"
style="display: inline-block"
read-only="true"
> >.
This is Strikethrough and here's an equation:
value="\sqrt[3]{x^2+y^2}"
lang="en"
style="display: inline-block"
read-only="true"
> >.
This is Colored and here's an equation:
value="x^{\left(\frac{\sin45}{\cos45}\right)}"
lang="en"
style="display: inline-block"
read-only="true"
> >.
- AR:
!Example 2 Arabic Input Sample
`HTML`
هذا غامق وهذه معادلة:
value="س+ص=ع"
lang="en"
style="display: inline-block"
read-only="true"
> >. هذا مائل وهذه معادلة:
value="\ga\left(\frac{س}{ص}\right)"
lang="en"
style="display: inline-block"
read-only="true"
> >.
هذا مسطر وهذه معادلة:
value="\sqrt[٣]{س^٢+ص^٢}"
lang="en"
style="display: inline-block"
read-only="true"
> >. هذا خط بعرض النص وهذه معادلة: >
value="س+ص=ع"
lang="en"
style="display: inline-block"
read-only="true"
> >.
هذا ملون وهذه معادلة:
value="س^{\left(\frac{\ga٤٥}{\gata٤٥}\right)}"
lang="en"
style="display: inline-block"
read-only="true"
> >.
- 3 Text + inline math + Displayed math:
- EN:
!Example 3 Input English Sample
` Here's an inline equation: Here's a display equation:HTML`
- AR:
!Example 3 Arabic Input Sample
` هذه معادلة في نفس السطر: هذه معادلة في سطر منفصل:HTML`
- 4 Text + inline math + chemistry:
- EN:
!Example 4 Input English Sample
` This is an inline equation This is a display chemistry equation:HTML`
- AR:
!Example 4 Arabic Input Sample
` هذه معادلة في نفس السطر: هذه معادلة كيميائية في سطر منفصل:HTML`
- 5 Text + inline math + chemistry + Table (cells include chemistry, math, text):
- EN:
!Example 5 Input English Sample
` Table without Headers: Table with Headers:HTML`
Cell1
Cell2
Cell3
This is an inline equation:
This is an inline chemistry equation:
Cell4
Cell5
Cell6
Cell7
Heading1
Heading2
Heading3
Cell1
Cell2
Cell3
Cell4
Cell5
Cell6
- AR:
!Example 5 Arabic Input Sample
` جدول بلا عناوين: جدول بعناوين:HTML`
خلية٣
خلية٢
خلية١
هذه معادلة:
هذه معادلة كيميائية:
className="hoverable-mathlive-mathfield inline">
خلية٤
خلية٧
خلية٦
خلية٥
عنوان ٣
عنوان ٢
عنوان ١
خلية٣
خلية٢
خلية١
خلية٦
خلية٥
خلية٤
- 6 Text + inline math + image with style:
- EN:
!Example 6 Input English Sample
` Here's an equation: Here's an unordered list: Here's an ordered list:HTML`

- AR:
!Example 6 Arabic Input Sample
` هذه معادلة: هذه قائمة غير مرقمة: هذه قائمة مرقمة:HTML`

- 7 Text + inline math + audio:
- EN:
!Example 7 Input English Sample
` Here's an audio element: Here's an unordered list: Here's an ordered list:HTML`
Here's an equation:
value="\frac{x+y}{x+z}=y+2"
dir="ltr"
lang="en"
style="display: inline-block"
read-only="true"
>
equation:
value="x^2+1"
dir="ltr"
lang="en"
style="display: inline-block"
read-only="true"
>
- AR:
!Example 7 Arabic Input Sample
` هذه قائمة غير مرقمة: هذه قائمة مرقمة:HTML`
هذه معادلة:
value="\frac{س+ص}{س+ع}=ص+٢"
lang="en"
style="display: inline-block"
read-only="true"
>
معادلة:
value="س^٢+١"
dir="rtl"
lang="ar"
style="display: inline-block"
read-only="true"
>
- 8 Text + attachment:
- EN:
!Example 8 Input English Sample
` abcHTML`
- AR:
!Example 8 Arabic Input Sample
` ابجدHTML`
- 9 Poem:
- حر:
!Example 9 Input English Sample
- مشطور:
!Example 9 Input English Sample
- عمودي:
!Example 9 Input English Sample
- مثلث:
!Example 9 Input English Sample
All poems are serialized to same structure with 1 minor difference, the poemMode. The 4 values of the poem mode in order are free, vertical, vertical-split, and triangle.
` عَلى قَدْرِ أهْلِ العَزْم تأتي العَزائِمُ وَتأتي علَى قَدْرِ الكِرامِ المَكارمُ وَتَعْظُمُ في عَينِ الصّغيرِ صغارُها وَتَصْغُرُ في عَين العَظيمِ العَظائِمُ يُكَلّفُ سيفُ الدّوْلَةِ الجيشَ هَمّهُ وَقد عَجِزَتْ عنهُ الجيوشُ الخضارمُHTML`
#### 1.4.1. Using the Static API
Here's an example of how to consume the API.
Folder Structure:
`tree
build
├─ index.html
└─ static
├─ css
│ ├─ NagwaHTMLEditor-min.css
│ └─ NagwaHTMLEditor-min.css.map
├─ fonts
│ ├─ KaTeX_AMS-Regular.woff2
│ ├─ KaTeX_Caligraphic-Bold.woff2
│ ├─ KaTeX_Caligraphic-Regular.woff2
│ ├─ KaTeX_Fraktur-Bold.woff2
│ ├─ KaTeX_Fraktur-Regular.woff2
│ ├─ KaTeX_Main-Bold.woff2
│ ├─ KaTeX_Main-BoldItalic.woff2
│ ├─ KaTeX_Main-Italic.woff2
│ ├─ KaTeX_Main-Regular.woff2
│ ├─ KaTeX_Math-BoldItalic.woff2
│ ├─ KaTeX_Math-Italic.woff2
│ ├─ KaTeX_SansSerif-Bold.woff2
│ ├─ KaTeX_SansSerif-Italic.woff2
│ ├─ KaTeX_SansSerif-Regular.woff2
│ ├─ KaTeX_Script-Regular.woff2
│ ├─ KaTeX_Size1-Regular.woff2
│ ├─ KaTeX_Size2-Regular.woff2
│ ├─ KaTeX_Size3-Regular.woff2
│ ├─ KaTeX_Size4-Regular.woff2
│ ├─ KaTeX_Typewriter-Regular.woff2
│ ├─ NagwaArabicMath.woff2
│ ├─ NagwaMath.woff2
│ ├─ NotoNaskhArabic-Bold.woff2
│ ├─ NotoNaskhArabic-Regular.woff2
│ ├─ STIX2Text-Bold.woff2
│ ├─ STIX2Text-BoldItalic.woff2
│ ├─ STIX2Text-Italic.woff2
│ ├─ STIX2Text-Regular.woff2
│ ├─ droidnaskh-bold.woff2
│ ├─ droidnaskh-regular.woff2
│ ├─ fa-brands-400.woff2
│ ├─ fa-light-300.woff2
│ ├─ fa-regular-400.woff2
│ ├─ fa-solid-900.woff2
│ ├─ notosans-bold-webfont.woff2
│ ├─ notosans-regular-webfont.woff2
│ ├─ summernote.eot
│ ├─ summernote.ttf
│ ├─ summernote.woff
│ ├─ summernote.woff2
│ └─ times-extrabold.woff2
├─ images
│ ├─ image-file.svg
│ ├─ latex-icon-blue.svg
│ ├─ latex-icon.svg
│ ├─ pattern.svg
│ ├─ select-arrow.svg
│ ├─ sorting-asc.svg
│ ├─ sorting-desc.svg
│ ├─ sorting.svg
│ ├─ three-dots.svg
│ ├─ upload-cloud-icon.svg
│ ├─ video-play-blue.svg
│ └─ video_play.svg
└─ js
├─ NagwaHTMLEditor.js
├─ NagwaHTMLEditor.js.LICENSE.txt
└─ NagwaHTMLEditor.js.map
`
index.html:
`HTML
`
#### 1.4.2. Using the Component Library API
Here's an example of how to consume the Component Library API.
After installing the library (see: Install Component Library Using NPM), in your react app import the editor and the needed functions from the library as follows:
`Typescript
import { FC, useEffect } from "react"
import NagwaHTMLEditor, { getEditorAPI } from "nagwa-html-editor"
const uniqueKey = "" //make sure it's unique for every editor instance
const Component:FC = () => {
useEffect(() => {
const editorAPI = getEditorAPI(uniqueKey)
console.log(editorAPI)
})
return
}
`
These instructions will get you a copy of the project up and running on your local machine.
You have to have Node.js v14.18.1, and npm v6.14.15 installed.
Also, check ./package.json for all the packages used in this project
Clone this repo, open the terminal and navigate to the repo directory on your local machine, and then run:
`cli`
npm install
wait until it's done and you're good to go!
Note: if installation fails because if npm, make sure you're using v16. if it still fails, install using v14, then re-install using v16.
Note: There will be a high severity audit problem when you install the packages.
This Problem is caused by react-scripts package.
This is a false positive according to #9469 (comment) from the maintainers on this issue, so there's nothing to worry about.
- TypeScript - The main language used.
- Node.js v16 - The run-time environment used to run and build the app (Currently working using v16).
- React - The web framework used.
- Slate - The library used to create the text editor.
- Inserting any type of text.
- Making text bold.
- Making text italic.
- Making text underlined.
- Making text code.
- Making text superscript.
- Making text subscript.
- Inserting bulleted list.
- Inserting numbered list.
- Aligning text to any direction.
- Justify text.
- Setting the direction of the text to "ltr" or "rtl.
- Inserting a table.
- Inserting inline editable math equation.
- Inserting display editable math equation.
A commit messages consists of three distinct parts separated by a blank line: the title, an optional body and an optional footer. The layout looks like this:
`Git
type: subject
body
`
#### 5.1.1. The Type
The type is contained within the title and can be one of these types:
- feat: a new feature
- fix: a bug fix
- docs: changes to documentation
- style: formatting, missing semi colons, etc; no code change
- refactor: refactoring production code
- test: adding tests, refactoring test; no production code change
- chore: updating build tasks, package manager configs, etc; no production code change
#### 5.1.2. The Subject
Subjects should be no greater than 50 characters, should begin with a capital letter and do not end with a period.
Use an imperative tone to describe what a commit does, rather than what it did. For example, use change; not changed or changes.
#### 5.1.3. The Body
Not all commits are complex enough to warrant a body, therefore it is optional and only used when a commit requires a bit of explanation and context. Use the body to explain the what and why of a commit, not the how.
When writing a body, the blank line between the title and the body is required and you should limit the length of each line to no more than 72 characters.
For more information about the style guide for Git and programming Languages check: Udacity's Code Style Guide
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- @vitejs/plugin-react uses Babel for Fast Refresh
- @vitejs/plugin-react-swc uses SWC for Fast Refresh
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
- Configure the top-level parserOptions property like this:
`js`
export default {
// other rules...
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
project: ["./tsconfig.json", "./tsconfig.node.json"],
tsconfigRootDir: __dirname,
},
}
- Replace plugin:@typescript-eslint/recommended to plugin:@typescript-eslint/recommended-type-checked or plugin:@typescript-eslint/strict-type-checkedplugin:@typescript-eslint/stylistic-type-checked
- Optionally add plugin:react/recommended
- Install eslint-plugin-react and add & plugin:react/jsx-runtime to the extends` list