Created
January 27, 2019 10:24
-
-
Save kmelve/808f13166254ea2c7a8c1fdb95543c68 to your computer and use it in GitHub Desktop.
An example of simple text analysis for Sanity.io’s editor for Portable Text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Fragment } from 'react' | |
| import { BlockEditor } from 'part:@sanity/form-builder' | |
| import calculateLix from 'lix-index' | |
| const lixIllustration = lix => { | |
| if (lix > 55) return '😭' // very difficult | |
| if (lix > 45) return '😟' // difficult | |
| if (lix > 35) return '😐' // medium | |
| if (lix > 25) return '🙂' // easy | |
| if (lix > 10) return '😃' // very easy | |
| return '😆' // super easy | |
| } | |
| class CustomEditor extends React.PureComponent { | |
| render() { | |
| const { value = [] } = this.props | |
| const wordsPerMinute = 200 | |
| const plainText = blocksToText(value) | |
| const wordTokens = plainText.split(/\w+/g).filter(Boolean) | |
| const characterCount = plainText.length | |
| const wordCount = wordTokens.length | |
| const readingTime = Math.ceil(wordCount / wordsPerMinute) | |
| const lix = calculateLix(plainText) | |
| return ( | |
| <div> | |
| <BlockEditor {...this.props} /> | |
| <div> | |
| 🔠{characterCount} 🚾{wordCount} ⏱{readingTime} min{' '} | |
| {lixIllustration(lix)} | |
| {lix} | |
| </div> | |
| </div> | |
| ) | |
| } | |
| } | |
| export default { | |
| name: 'simpleBlockContent', | |
| type: 'array', | |
| title: 'simpleBlockContent', | |
| inputComponent: EditorWithToC, | |
| of: [ | |
| { | |
| type: 'block' | |
| } | |
| ] | |
| } | |
| const defaults = { nonTextBehavior: 'remove' } | |
| function blocksToText(blocks, opts = {}) { | |
| const options = Object.assign({}, defaults, opts) | |
| return blocks | |
| .map(block => { | |
| if (block._type !== 'block' || !block.children) { | |
| return options.nonTextBehavior === 'remove' | |
| ? '' | |
| : `[${block._type} block]` | |
| } | |
| return block.children.map(child => child.text).join('') | |
| }) | |
| .join('\n\n') | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment