1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-02-24 17:23:07 +01:00
slate/lib/models/block.js

111 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-06-23 10:43:36 -07:00
import Data from './data'
import Inline from './inline'
import Node from './node'
2016-06-23 10:43:36 -07:00
import Text from './text'
import uid from 'uid'
2016-06-23 10:43:36 -07:00
import Immutable, { Map, OrderedMap, Record } from 'immutable'
/**
* Default properties.
*/
const DEFAULTS = {
data: new Map(),
key: null,
nodes: new OrderedMap(),
type: null
}
/**
* Block.
*/
class Block extends Record(DEFAULTS) {
/**
* Create a new `Block` with `properties`.
*
* @param {Object} properties
* @return {Block} element
*/
static create(properties = {}) {
2016-06-23 10:43:36 -07:00
if (properties instanceof Block) return properties
if (properties instanceof Inline) return properties
if (properties instanceof Text) return properties
if (!properties.type) throw new Error('You must pass a block `type`.')
2016-06-23 10:43:36 -07:00
properties.key = uid(4)
2016-06-23 10:43:36 -07:00
properties.data = Data.create(properties.data)
properties.nodes = Block.createMap(properties.nodes)
let block = new Block(properties)
return block.normalize()
}
/**
* Create an ordered map of `Blocks` from an array of `Blocks`.
*
* @param {Array} elements
* @return {OrderedMap} map
*/
static createMap(elements = []) {
2016-06-23 10:43:36 -07:00
if (OrderedMap.isOrderedMap(elements)) return elements
return elements
.map(Block.create)
.reduce((map, element) => {
return map.set(element.key, element)
}, new OrderedMap())
}
/**
* Get the node's kind.
*
* @return {String} kind
*/
get kind() {
return 'block'
}
/**
* Get the length of the concatenated text of the node.
*
* @return {Number} length
*/
get length() {
return this.text.length
}
/**
* Get the concatenated text `string` of all child nodes.
*
* @return {String} text
*/
get text() {
return this.nodes
.map(node => node.text)
.join('')
}
}
/**
* Mix in `Node` methods.
*/
for (const method in Node) {
Block.prototype[method] = Node[method]
}
/**
* Export.
*/
export default Block