function AnnotationPlugin(options) {
const { onChange } = options
return {
onSelect(event, editor, next) {
event.preventDefault()
const { value } = editor
const { selection } = value
const { start, end} = selection
if (selection.isCollapsed) {
return next();
}
const nodes = [];
let hasStarted = false;
let hasEnded = false;
// Keep only the relevant nodes,
// i.e. nodes which are contained within selection
value.document.nodes.forEach((node) => {
if (start.isInNode(node)) {
hasStarted = true;
}
if (hasStarted && !hasEnded) {
nodes.push(node);
}
if (end.isAtEndOfNode(node)) {
hasEnded = true;
}
});
// Concatenate the nodes text
const text = nodes.map((node) => {
let textStart = start.isInNode(node) ? start.offset : 0;
let textEnd = end.isAtEndOfNode(node) ? end.offset : node.text.length;
return node.text.substring(textStart,textEnd);
}).join('\n');
if (onChange) {
onChange(text, start.offset, end.offset);
}
return next();
}
};
}
export default AnnotationPlugin;