Skip to content

Commit

Permalink
Allow only 1 <hr> at a time
Browse files Browse the repository at this point in the history
  • Loading branch information
mduvall committed Sep 8, 2013
1 parent c91e2f3 commit 7b45776
Showing 1 changed file with 36 additions and 14 deletions.
50 changes: 36 additions & 14 deletions js/grande.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@
}, 1);
};

document.onkeydown = preprocessKeyDown;

document.onkeyup = function(event){
var sel = window.getSelection();

Expand Down Expand Up @@ -148,19 +150,36 @@
});
}

function preprocessKeyDown(event) {
var sel = window.getSelection(),
prevSibling = sel.anchorNode.previousSibling;

if (event.keyCode === 13) {
// Stop enters from creating another <p> after a <hr> on enter
if (prevSibling && prevSibling.nodeName === "HR") {
event.preventDefault();
}
}
}

function triggerNodeAnalysis(event) {
var sel = window.getSelection(),
anchorNode,
parentP,
hr;
hr,
prevSibling;

if (event.keyCode === 13) {
parentP = getParentWithTag(sel.anchorNode, 'p');
// Enters should replace it's parent <div> with a <p>
if (sel.anchorNode.nodeName === "DIV") {
toggleFormatBlock("p");
}

if (sel.anchorNode.nodeName.toLowerCase() === 'p' || parentP) {
if (parentP.previousSibling.nodeName.toLowerCase() === 'p' && !parentP.previousSibling.textContent.length) {
hr = document.createElement('hr');
parentP.parentNode.replaceChild(hr, parentP.previousSibling);
}
prevSibling = sel.anchorNode.previousSibling;

if (prevSibling.nodeName === "P" && !prevSibling.textContent.length) {
hr = document.createElement("hr");
hr.contentEditable = false;
sel.anchorNode.parentNode.replaceChild(hr, prevSibling);
}
}
}
Expand Down Expand Up @@ -224,15 +243,18 @@
parent = insertedNode.parentNode;
parent.parentNode.insertBefore(insertedNode, parent);
parent.parentNode.removeChild(parent);

range = document.createRange();
range.setStart(node, 0);
range.setEnd(node, 0);
sel.removeAllRanges();
sel.addRange(range);
moveCursorToBeginningOfSelection(sel, node);
}
}

function moveCursorToBeginningOfSelection(selection, node) {
range = document.createRange();
range.setStart(node, 0);
range.setEnd(node, 0);
selection.removeAllRanges();
selection.addRange(range);
}

function triggerTextStyling(node) {
var className = node.className,
tagClass,
Expand Down

1 comment on commit 7b45776

@mduvall
Copy link
Owner Author

@mduvall mduvall commented on 7b45776 Sep 8, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@y-lohse Want to take a look at this and give it a spin? I updated it closely to match the behavior on Medium (prevents events when the <p> is blank and doesn't let them stack) and the look a bit. Your feedback is appreciated!

Please sign in to comment.