+
+ var style_popup = null;
+ function update_style() {
+ var action = $(this).data('action');
+ var param = null;
+ if (action == 'code') {
+ action = 'insertHTML';
+ param = $('<code></code>', {text: window.getSelection().toString()})[0].outerHTML;
+ }
+ document.execCommand(action, false, param);
+ }
+
+ function show_style_popup(sel) {
+ if (style_popup === null) {
+ style_popup = $('<div id="style-popup">' +
+ '<button data-action="italic"><i>i</i></button>' +
+ '<button data-action="bold"><b>b</b></button>' +
+ '<button data-action="code">#</button>' +
+ '<button data-action="removeFormat">×</button>' +
+ '</div>');
+ style_popup.hide();
+ style_popup.insertAfter($('div[contenteditable]'));
+ style_popup.find('button').on('click', update_style);
+ }
+ style_popup.css('position', 'absolute');
+ var pos = sel.getRangeAt(0).getClientRects()[0];
+ style_popup.css('top', pos.top + window.scrollY - $('main').offset().top - 33);
+ style_popup.css('left', pos.left + window.scrollX - $('main').offset().left);
+ style_popup.show();
+ };
+ $(document).on('selectionchange', function(event) {
+ var sel = window.getSelection();
+ if ($(sel.anchorNode).parents('div[contenteditable]').length && sel.toString()) {
+ show_style_popup(sel);
+ } else if (style_popup) {
+ $(style_popup).hide();
+ }
+ });