Skip to content
This repository has been archived by the owner on Feb 21, 2019. It is now read-only.

Commit

Permalink
Add rule for orphan code lines
Browse files Browse the repository at this point in the history
  • Loading branch information
Soreine committed Dec 14, 2016
1 parent a198422 commit e283b36
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 2 deletions.
44 changes: 42 additions & 2 deletions lib/makeSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,53 @@ const Slate = require('slate');
function makeSchema(opts) {
return {
rules: [
noMarks(opts),
noOrphanLine(opts),
onlyLine(opts),
onlyText(opts)
onlyText(opts),
noMarks(opts)
]
};
}

/**
* @return {Object} A rule that ensure code lines are always children
* of a code block.
*/
function noOrphanLine(opts) {

return {
// Match all blocks that are not code blocks
match(node) {
return (node.kind === 'block' || node.kind === 'document')
&& node.type !== opts.containerType;
},

validate(node) {
const codeLines = node.nodes.filter(n => n.type === opts.lineType);

if (codeLines.isEmpty()) {
// All good
return null;
} else {
// Wrap the orphan lines
return {
toWrap: codeLines
};
}
},

/**
* Wrap the given blocks in code containers
* @param {List<Nodes>} value.toWrap
*/
normalize(transform, node, value) {
return value.toWrap.reduce((tr, n) => {
return tr.wrapBlockByKey(n.key, opts.containerType);
}, transform);
}
};
}

/**
* @return {Object} A rule that ensure code blocks only contain lines of code, and no marks
*/
Expand Down
18 changes: 18 additions & 0 deletions tests/schema-no-orphan-line/expected.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

nodes:
- kind: block
type: code_block
nodes:
- kind: block
type: code_line
nodes:
- kind: text
text: "Some orphan code"
- kind: block
type: code_block
nodes:
- kind: block
type: code_line
nodes:
- kind: text
text: "Some other code"
15 changes: 15 additions & 0 deletions tests/schema-no-orphan-line/input.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

nodes:
- kind: block
type: code_line
nodes:
- kind: text
text: "Some orphan code"
- kind: block
type: code_block
nodes:
- kind: block
type: code_line
nodes:
- kind: text
text: "Some other code"
8 changes: 8 additions & 0 deletions tests/schema-no-orphan-line/transform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const Slate = require('slate');

module.exports = function(plugin, state) {
const schema = new Slate.Schema(plugin.schema);
return state.transform()
.normalize(schema)
.apply();
};

0 comments on commit e283b36

Please sign in to comment.