Mercurial Hosting > freedit
diff src/bbcode/bbcode.js @ 44:96f0c3d65698
add /bbcode
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Thu, 10 Nov 2022 23:18:58 -0700 |
parents | |
children | 2d4f00755092 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/bbcode/bbcode.js Thu Nov 10 23:18:58 2022 -0700 @@ -0,0 +1,87 @@ +function fixTextarea(textarea) { + let height = textarea.scrollHeight; + if( height > textarea.clientHeight ) { + textarea.style.height = (height+2) + "px"; + } +} + +function fileButtonClick(button) { + button.parentNode.querySelector('input[type="file"]').click(); +} + +function upload(input,callback) { + let file = input.files[0]; + input.value = null; + let request = new XMLHttpRequest(); + let url = 'https://upload.uploadcare.com/base/'; + request.open( 'POST', url ); + request.onload = function() { + if( request.status !== 200 ) { + let err = 'ajax failed: ' + request.status; + if( request.responseText ) { + err += '\n' + request.responseText; + document.write('<pre>'+request.responseText+'</pre>'); + } + console.log(err); + ajax( '/error_log.js', 'err='+encodeURIComponent(err) ); + return; + } + let response = JSON.parse(request.responseText); + let filename = file.name; + let url = 'https://ucarecdn.com/' + response.file + '/' + filename; + callback(input,url,filename); + }; + let formData = new FormData(); + formData.append( 'UPLOADCARE_PUB_KEY', 'fe3d30f3088a50941d45' ); + formData.append( 'file', file ); + request.send(formData); +} + +function getBbcodeDiv(node) { + do { + //console.log(node); + if( node.getAttribute('bbcode') !== null ) + return node; + } while( node = node.parentNode ); +} + +function uploaded(input,url,filename) { + let div = getBbcodeDiv(input); + let textarea = div.querySelector('textarea'); + textarea.focus(); + textarea.setRangeText(url,textarea.selectionStart,textarea.selectionEnd,'select'); +} + +function bbcodeCreate(div,options) { + if( typeof(div) === 'string' ) + div = document.querySelector(div); + let content = options.content || ''; + let save = options.save; + let cancel = options.cancel; + let html = `\ + <div bbcode> + <textarea oninput="fixTextarea(this)"></textarea> + <p> + <input type=file onchange="upload(this,uploaded)"> + <button type=button onclick="fileButtonClick(this)">Upload File</button> +` ; + if(save) { + html += `\ + <button type=button save>save</button> +` ; + } + if(cancel) { + html += `\ + <button type=button cancel>cancel</button> +` ; + } + html += `\ + </p> + </div> +` ; + div.innerHTML = html; + if(save) + div.querySelector('button[save]').addEventListener('click',save); + if(cancel) + div.querySelector('button[cancel]').addEventListener('click',cancel); +}