Skip to content

Instantly share code, notes, and snippets.

@pingpoli
Created June 2, 2023 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pingpoli/f63eca5c7dc6955b25e4e79c342965e2 to your computer and use it in GitHub Desktop.
Save pingpoli/f63eca5c7dc6955b25e4e79c342965e2 to your computer and use it in GitHub Desktop.
/*
Copyright 2023 Christian Behler (pingpoli.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
class pingpoliEditor
{
constructor( divID )
{
this.div = document.getElementById( divID );
this.div.style.display = "inline-block";
this.fileInput = null;
this.div.addEventListener( "mouseup" , ( event ) => {
this.hidePanel();
this.hideLinkPanel();
this.hideEmptyLinePanel();
var selection = window.getSelection();
if ( selection.toString().length > 0 )
{
var range = selection.getRangeAt( 0 );
var bb = range.getBoundingClientRect();
this.panel.style.left = bb.x+"px";
this.panel.style.top = bb.y+bb.height+5+"px";
this.linkPanel.style.left = bb.x+"px";
this.linkPanel.style.top = bb.y+bb.height+5+"px";
this.showPanel();
}
else
{
// var range = selection.getRangeAt( 0 );
// var bb = range.getBoundingClientRect();
var caretPosition = this.#getCaretPosition( selection );
this.#restoreCaretPosition( selection );
if ( ( this.div.innerHTML.indexOf( "<br>" , caretPosition-4 ) === caretPosition-4 || this.div.innerHTML.indexOf( "<div>" , caretPosition-5 || this.div.innerHTML.indexOf( "<hr>" , caretPosition-4 ) === caretPosition-4 ) === caretPosition-5 ) && this.div.innerHTML.indexOf( "<br>" , caretPosition ) === caretPosition )
{
this.showEmptyLinePanel( event );
}
}
} );
this.div.addEventListener( "paste" , ( event ) => {
// cancel paste
event.preventDefault();
// get text representation of clipboard
var text = (event.originalEvent || event).clipboardData.getData( "text/plain" );
// keep line breaks
text = text.replaceAll( "\r\n" , "<br>" );
text = text.replaceAll( "\n" , "<br>" );
var selection = window.getSelection();
if ( selection.rangeCount === 0 ) return;
var range = selection.getRangeAt( 0 );
if ( this.#isChildOfDiv( range.commonAncestorContainer ) )
{
if ( selection.toString().length === 0 )
{
// range.deleteContents();
var tmpDiv = document.createElement( "div" );
tmpDiv.innerHTML = text;
range.insertNode( tmpDiv );
selection.empty();
this.#clean();
this.div.focus();
}
}
} );
this.div.addEventListener( "keypress" , ( event ) => {
this.hideEmptyLinePanel();
} );
this.div.addEventListener( "keyup" , ( event ) => {
this.hideEmptyLinePanel();
} );
this.init();
}
init()
{
var style = document.createElement( "style" );
style.innerHTML = `
#ppnEditorPanel {
grid-template-columns: auto auto auto auto auto auto auto;
}
#ppnEditorLinkPanel {
grid-template-columns: auto auto auto;
}
.ppnEditorPanel {
box-sizing: border-box;
position: absolute;
display: grid;
column-gap: 5px;
padding: 0px 5px;
background-color: #eeeeee;
border: 1px solid #cccccc;
border-radius: 7px;
font-size: 16px;
}
.ppnEditorInput {
box-sizing: border-box;
width: 200px;
height: 30px;
margin: 5px 0px;
padding: 0px 3px;
border: 1px solid #555555;
border-radius: 7px;
font-size: 16px;
line-height: 30px;
outline: none;
}
.ppnEditorButton {
box-sizing: border-box;
width: 30px;
height: 30px;
margin: 5px 0px;
padding: 0px;
background-color: #777777;
border: 1px solid #555555;
border-radius: 7px;
text-align: center;
font-family: monospace;
color: #ffffff;
font-size: 20px;
line-height: 30px;
}
.ppnEditorButton:hover {
background-color: #555555;
}
.wide {
width: 50px;
}
.ppnEditorSpacer {
width: 1px;
height: 100%;
background-color: #cccccc;
}
`;
document.body.appendChild( style );
this.panel = document.createElement( "div" );
this.panel.id = "ppnEditorPanel";
this.panel.className = "ppnEditorPanel";
this.panel.style.display = "none";
var button = document.createElement( "button" );
button.className = "ppnEditorButton";
button.innerHTML = "B";
button.onclick = () => { this.style( "STRONG" ); };
this.panel.appendChild( button );
var button = document.createElement( "button" );
button.className = "ppnEditorButton";
button.innerHTML = "I";
button.onclick = () => { this.style( "EM" ); };
this.panel.appendChild( button );
var spacer = document.createElement( "div" );
spacer.className = "ppnEditorSpacer";
this.panel.appendChild( spacer );
var button = document.createElement( "button" );
button.className = "ppnEditorButton";
button.innerHTML = "H1";
button.onclick = () => { this.style( "H1" ); };
this.panel.appendChild( button );
var button = document.createElement( "button" );
button.className = "ppnEditorButton";
button.innerHTML = "H2";
button.onclick = () => { this.style( "H2" ); };
this.panel.appendChild( button );
var spacer = document.createElement( "div" );
spacer.className = "ppnEditorSpacer";
this.panel.appendChild( spacer );
var button = document.createElement( "button" );
button.className = "ppnEditorButton";
button.innerHTML = "A";
button.onclick = () => {
this.style( "A" , "" );
};
this.panel.appendChild( button );
document.body.appendChild( this.panel );
// link panel
this.linkPanel = document.createElement( "div" );
this.linkPanel.id = "ppnEditorLinkPanel";
this.linkPanel.className = "ppnEditorPanel";
this.linkPanel.style.display = "none";
this.linkInput = document.createElement( "input" );
this.linkInput.className = "ppnEditorInput";
this.linkPanel.appendChild( this.linkInput );
var button = document.createElement( "button" );
button.className = "ppnEditorButton";
button.innerHTML = "Ok";
button.onclick = () => {
if ( this.linkInput.value !== "" )
{
this.div.innerHTML = this.div.innerHTML.replaceAll( "I_AM_A_LINK_PLACEHOLDER" , this.linkInput.value );
this.hideLinkPanel();
}
};
this.linkPanel.appendChild( button );
document.body.appendChild( this.linkPanel );
// empty line panel
this.emptyLinePanel = document.createElement( "div" );
this.emptyLinePanel.id = "ppnEditorLinkPanel";
this.emptyLinePanel.className = "ppnEditorPanel";
this.emptyLinePanel.style.display = "none";
var button = document.createElement( "button" );
button.className = "ppnEditorButton wide";
button.innerHTML = "HR";
button.onclick = () => { this.hr(); };
this.emptyLinePanel.appendChild( button );
var button = document.createElement( "button" );
button.className = "ppnEditorButton wide";
button.innerHTML = "IMG";
button.onclick = () => {
this.openImageUploadWindow();
};
this.emptyLinePanel.appendChild( button );
var button = document.createElement( "button" );
button.className = "ppnEditorButton wide";
button.innerHTML = "CODE";
button.onclick = () => { this.code( "console.log( \"Hello World\" );" ); };
this.emptyLinePanel.appendChild( button );
document.body.appendChild( this.emptyLinePanel );
}
showPanel()
{
this.panel.style.display = "grid";
this.hideEmptyLinePanel();
}
hidePanel()
{
this.panel.style.display = "none";
}
showLinkPanel()
{
this.linkPanel.style.display = "grid";
}
hideLinkPanel()
{
this.linkInput.value = "";
this.linkPanel.style.display = "none";
}
showEmptyLinePanel( event )
{
this.emptyLinePanel.style.left = event.clientX+"px";
this.emptyLinePanel.style.top = event.clientY+"px";
this.emptyLinePanel.style.display = "grid";
this.hidePanel();
}
hideEmptyLinePanel()
{
this.emptyLinePanel.style.display = "none";
}
openImageUploadWindow()
{
if ( this.fileInput === null )
{
this.fileInput = document.createElement( "input" );
this.fileInput.type = "file";
this.fileInput.name = "pingpoliEditorFileInput";
this.fileInput.style.position = "absolute";
this.fileInput.style.left = "-1000px";
this.fileInput.style.display = "none";
document.body.appendChild( this.fileInput );
this.fileInput.onchange = ( event ) => {
if ( this.onImageUpload !== undefined ) this.onImageUpload( this.fileInput );
};
}
this.fileInput.click();
}
hr()
{
var selection = window.getSelection();
if ( selection.rangeCount === 0 ) return;
var range = selection.getRangeAt( 0 );
if ( this.#isChildOfDiv( range.commonAncestorContainer ) )
{
if ( selection.type === "Caret" )
{
range.insertNode( document.createElement( "BR" ) );
range.insertNode( document.createElement( "HR" ) );
selection.empty();
this.#clean();
this.hideEmptyLinePanel();
}
}
}
img( url )
{
var selection = window.getSelection();
if ( selection.rangeCount === 0 ) return;
var range = selection.getRangeAt( 0 );
if ( this.#isChildOfDiv( range.commonAncestorContainer ) )
{
if ( selection.type === "Caret" )
{
var linkNode = document.createElement( "A" );
linkNode.href = url;
linkNode.target = "_blank";
var imgNode = document.createElement( "IMG" );
imgNode.src = url;
linkNode.appendChild( imgNode );
range.insertNode( linkNode );
selection.empty();
this.#clean();
this.hideEmptyLinePanel();
}
}
}
code( code )
{
var selection = window.getSelection();
if ( selection.rangeCount === 0 ) return;
var range = selection.getRangeAt( 0 );
if ( this.#isChildOfDiv( range.commonAncestorContainer ) )
{
if ( selection.type === "Caret" )
{
range.insertNode( document.createElement( "BR" ) );
var codeNode = document.createElement( "CODE" );
if ( code !== undefined ) codeNode.innerHTML = code;
range.insertNode( codeNode );
selection.empty();
this.#clean();
this.hideEmptyLinePanel();
}
}
}
style( nodeName , value )
{
var selection = window.getSelection();
if ( selection.isCollapsed ) return;
var range = selection.getRangeAt( 0 );
const startContainerNode = this.#isInside( range.startContainer , nodeName );
const endContainerNode = this.#isInside( range.endContainer , nodeName );
if ( startContainerNode !== false || endContainerNode !== false )
{
// both range container nodes are part of the same node
if ( startContainerNode === endContainerNode )
{
this.#removeNode( startContainerNode );
}
else
{
// remove start container node
if ( startContainerNode !== false )
{
this.#removeNode( startContainerNode );
}
// remove end container node
if ( endContainerNode !== false )
{
this.#removeNode( endContainerNode );
}
}
}
else
{
// check if the selection fully contains a node of the same type
// e.g. "Hello <strong>World</strong>!", if we would just surround the selection, the <strong>s would be nested like "<strong>Hello <strong>World</strong>!</strong>", which works, but isn't pretty, so we remove all nodes of the same type that are fully within the selection
for ( let i = 0 ; i < range.commonAncestorContainer.childNodes.length ; ++i )
{
if ( range.commonAncestorContainer.childNodes[i].nodeName === nodeName )
{
this.#removeNode( range.commonAncestorContainer.childNodes[i] );
}
}
if ( nodeName === "A" )
{
if ( value === "" )
{
var newNode = document.createElement( nodeName );
newNode.href = "I_AM_A_LINK_PLACEHOLDER";
newNode.target = "_blank";
newNode.appendChild( range.extractContents() );
range.insertNode( newNode );
this.hidePanel();
this.showLinkPanel();
}
}
else
{
var newNode = document.createElement( nodeName );
newNode.appendChild( range.extractContents() );
range.insertNode( newNode );
}
}
selection.empty();
this.hidePanel();
this.#clean();
this.div.focus();
console.log( this.div.innerHTML );
}
#isInside( node , nodeName )
{
if ( node === this.div ) return false;
if ( node === document.body ) return false;
if ( node.parentElement.nodeName === nodeName )
{
return node.parentElement;
}
else
{
return this.#isInside( node.parentElement , nodeName );
}
}
#isInsideCode( node )
{
if ( node === this.div ) return false;
if ( node === document.body ) return false;
if ( node.nodeName === "CODE" ) return true;
return this.#isInsideCode( node.parentElement );
}
#removeNode( node )
{
let parent = node.parentElement;
for ( let i = 0 ; i < parent.childNodes.length ; ++i )
{
if ( parent.childNodes[i] === node )
{
while ( node.childNodes.length > 0 )
{
parent.insertBefore( node.firstChild , node );
}
parent.removeChild( node );
return;
}
}
}
#isChildOfDiv( node )
{
if ( node === this.div ) return true;
if ( node === document.body ) return false;
return this.#isChildOfDiv( node.parentElement );
}
#clean()
{
// for some reason chrome encapsulates line breaks and subsequent blocks of text in div containers, which look ugly in the source code, so just yeet them
// not really efficient for long texts, but who cares
this.div.innerHTML = this.div.innerHTML.replaceAll( "<div>" , "<br>" );
this.div.innerHTML = this.div.innerHTML.replaceAll( "</div>" , "" );
this.div.innerHTML = this.div.innerHTML.replaceAll( "&nbsp;" , " " );
console.log( this.div.innerHTML );
}
clean()
{
this.#clean();
}
#getCaretPosition( selection )
{
if ( selection.type == "Caret" )
{
var tempNode = document.createTextNode( "\0" );
selection.getRangeAt( 0 ).insertNode( tempNode );
var caretPosition = this.div.innerHTML.indexOf( "\0" );
tempNode.parentNode.removeChild( tempNode );
return caretPosition;
}
else return false;
}
#restoreCaretPosition( selection )
{
var range = document.createRange();
range.setStart( selection.focusNode , selection.focusOffset );
range.collapse( false );
selection.removeAllRanges();
selection.addRange( range );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment