1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-09-02 11:42:53 +02:00

refactor mark component normalization

This commit is contained in:
Ian Storm Taylor
2016-08-13 17:15:27 -07:00
parent 722bf0cf83
commit 4f83f54683

View File

@@ -152,24 +152,7 @@ class Schema extends new Record(DEFAULTS) {
__getComponent(object) {
const match = this.rules.find(rule => rule.match(object) && rule.component)
if (!match) return
const { component } = match
// Marks need special handling to normalize components.
if (object.kind != 'mark') return match.component
// If it's a React component, we're good.
if (isReactComponent(component)) return component
// Handle all other types...
switch (typeOf(component)) {
case 'function':
return component
case 'object':
return props => <span style={component}>{props.children}</span>
case 'string':
return props => <span className={component}>{props.children}</span>
}
return match.component
}
/**
@@ -212,11 +195,33 @@ class Schema extends new Record(DEFAULTS) {
*/
function normalizeProperties(properties) {
let { rules, nodes, marks } = properties
if (!rules) rules = []
let { rules = [], nodes, marks } = properties
// If there's a `nodes` property, it's the node rule shorthand dictionary.
if (nodes) {
const array = normalizeNodes(nodes)
rules = rules.concat(array)
}
if (marks) {
const array = normalizeMarks(marks)
rules = rules.concat(array)
}
return {
rules: rules.map(normalizeRule)
}
}
/**
* Normalize a `nodes` shorthand argument.
*
* @param {Object} nodes
* @return {Array}
*/
function normalizeNodes(nodes) {
const rules = []
for (const key in nodes) {
const value = nodes[key]
const match = {
@@ -236,10 +241,20 @@ function normalizeProperties(properties) {
})
}
}
}
// If there's a `marks` property, it's the mark rule shorthand dictionary.
if (marks) {
return rules
}
/**
* Normalize a `marks` shorthand argument.
*
* @param {Object} marks
* @return {Array}
*/
function normalizeMarks(marks) {
const rules = []
for (const key in marks) {
const value = marks[key]
const match = {
@@ -251,18 +266,36 @@ function normalizeProperties(properties) {
rules.push({
match,
...value,
component: normalizeMarkComponent(value.component),
})
} else {
rules.push({
match,
component: value
component: normalizeMarkComponent(value)
})
}
}
}
return {
rules: rules.map(normalizeRule)
return rules
}
/**
* Normalize a mark `component`.
*
* @param {Component || Function || Object || String} component
* @return {Component}
*/
function normalizeMarkComponent(component) {
if (isReactComponent(component)) return component
switch (typeOf(component)) {
case 'function':
return component
case 'object':
return props => <span style={component}>{props.children}</span>
case 'string':
return props => <span className={component}>{props.children}</span>
}
}