diff --git a/htdocs/edit.html b/htdocs/edit.html index 9190b5fd71..6783fecaa9 100644 --- a/htdocs/edit.html +++ b/htdocs/edit.html @@ -53,12 +53,24 @@
+
Sorry, RCloud's internal state has become inconsistent. Please reload to return to a working state.
" + message + "
"; RCloud.UI.fatal_dialog(message, "Reload", url); }, @@ -1115,7 +1121,7 @@ var editor = function () { open_notebook: function(gistname, version, selroot, new_window) { // really just load_notebook except possibly in a new window if(new_window) { - var url = ui_utils.make_url('edit.html', {notebook: gistname, version: version}); + var url = ui_utils.make_url(window.location.pathname.substr(1), {notebook: gistname, version: version}); window.open(url, "_blank"); } else diff --git a/htdocs/fiddle.js b/htdocs/fiddle.js new file mode 100644 index 0000000000..701e1499f2 --- /dev/null +++ b/htdocs/fiddle.js @@ -0,0 +1,49 @@ +$(function () { + window.fiddle = { + call_notebook: function(notebook) { + //if(args === undefined) { + // args = {}; + //} + //args.cookies = document.cookie; + //args.redirecturl = window.location.pathname; + + return new Promise(function(resolve,reject) { + rclient = RClient.create({ + debug: false, + host: location.href.replace(/^http/,"ws").replace(/#.*$/,""), + on_connect: function(ocaps) { + rcloud = RCloud.create(ocaps.rcloud); + + var promise; + if (rcloud.authenticated) { + promise = rcloud.session_init(rcloud.username(), rcloud.github_token()); + } else { + promise = rcloud.anonymous_session_init(); + } + promise.then(function(hello) { + rclient.post_response(hello); + }); + + // resolve(rcloud.init_client_side_data()); // what was this for?!? + + version = null; + rcloud.call_notebook(notebook, version).then(function(x) { + resolve(x); + }); + }, + on_error: function(msg, status_code) { + // debugger; + if (msg == 'Login failed. Shutting down!') { + window.location = + (window.location.protocol + + '//' + window.location.host + + '/login.R?redirect=' + + encodeURIComponent(window.location.pathname + window.location.search)); + reject(new Error(msg)); + } else reject(new Error(msg)); + } + }); + }); + } + } +}); \ No newline at end of file diff --git a/htdocs/fiddle_default.html b/htdocs/fiddle_default.html new file mode 100644 index 0000000000..fdec73c7cd --- /dev/null +++ b/htdocs/fiddle_default.html @@ -0,0 +1,19 @@ + + + + + +
+
+
\ No newline at end of file
diff --git a/htdocs/img/rcloud.png b/htdocs/img/rcloud.png
new file mode 100644
index 0000000000..714a46201d
Binary files /dev/null and b/htdocs/img/rcloud.png differ
diff --git a/htdocs/js/Makefile b/htdocs/js/Makefile
index b2f8a3dfd7..0416182820 100644
--- a/htdocs/js/Makefile
+++ b/htdocs/js/Makefile
@@ -53,6 +53,7 @@ rcloud_bundle.js: \
ui/progress.js \
ui/right_panel.js \
ui/run_button.js \
+ ui/toggle_button.js \
ui/scratchpad.js \
ui/search.js \
ui/session_pane.js \
diff --git a/htdocs/js/rcloud_bundle.js b/htdocs/js/rcloud_bundle.js
index 23be9782d3..485f0ba396 100644
--- a/htdocs/js/rcloud_bundle.js
+++ b/htdocs/js/rcloud_bundle.js
@@ -5976,6 +5976,7 @@ RCloud.UI.init = function() {
shell.notebook.controller.save_button(saveb);
RCloud.UI.run_button.init();
+ RCloud.UI.toggle_button.init();
//////////////////////////////////////////////////////////////////////////
// allow reordering cells by dragging them
@@ -6856,10 +6857,16 @@ RCloud.UI.run_button = (function() {
return {
init: function() {
var that = this;
+
run_button_.click(function() {
if(running_) {
that.stop();
}
+ else if ($('#iframe').css('display')!=='none') {
+ shell.save_notebook();
+ var target_url = window.location.origin+'/notebook.R/'+shell.gistname()+'/index.html';
+ $('#iframe').attr('src',target_url);
+ }
else
shell.run_notebook();
});
@@ -6909,6 +6916,103 @@ RCloud.UI.run_button = (function() {
}
};
})();
+RCloud.UI.toggle_button = (function() {
+ var toggle_button_ = $("#toggle-view"),
+ external_link_ = $('#external-link'),
+ iframe_ = $('#iframe'),
+ output_ = $('#output'),
+ end_of_output_ = $('#end-of-output');
+
+ function display(icon, title) {
+ $('i', toggle_button_).removeClass().addClass(icon);
+ toggle_button_.attr('title', title);
+ }
+ function highlight(whether) {
+ toggle_button_.parent().find('.button-highlight').animate({opacity: whether ? 1 : 0}, 250);
+ }
+ function createIndex() {
+ var found = shell.notebook.model.get_asset('index.html');
+
+ var indexTemplate =
+
+"\n\
+\n\
+\n\
+\n\
+\n\
+\n\
+\n\
+\n\
+Hello World!\n\
+\n\
+\n\
+\n\
+";
+
+ if(found) {
+ found.controller.select();
+ }
+ else {
+ shell.notebook.controller
+ .append_asset(indexTemplate, 'index.html')
+ .spread(function(_, controller) {
+ controller.select();
+ ui_utils.ace_set_pos(RCloud.UI.scratchpad.widget, 2, 1);
+ });
+ }
+ }
+
+ function toggleHTML5() {
+ toggle_button_.click(function () {});
+ createIndex();
+ $('#new-tab a').attr('href',window.location.origin+'/notebook.R/'+shell.gistname()+'/index.html');
+
+ output_.hide();
+ end_of_output_.hide();
+ $('#prompt-area').hide();
+ iframe_.show();
+ $('#new-tab').show();
+ display('icon-code','Toggle Notebook');
+ toggle_button_.click(toggleCode);
+ highlight(false);
+ }
+
+ function toggleCode() {
+ toggle_button_.click(function () {});
+ iframe_.hide();
+ $('#new-tab').hide();
+ output_.show();
+ end_of_output_.show();
+ $('#prompt-area').show();
+ display('icon-html5','Toggle Web View');
+ toggle_button_.click(toggleHTML5);
+ highlight(false);
+ }
+
+ return {
+ init: function() {
+ toggleCode();
+ }
+ };
+})();
RCloud.UI.scratchpad = {
session: null,
widget: null,
diff --git a/htdocs/js/rcloud_bundle.min.js b/htdocs/js/rcloud_bundle.min.js
index 68c1cbf239..baaea3eb09 100644
--- a/htdocs/js/rcloud_bundle.min.js
+++ b/htdocs/js/rcloud_bundle.min.js
@@ -2,5 +2,5 @@ RClient={create:function(opts){opts=_.defaults(opts,{debug:false});function on_c
var text=el.firstChild.textContent;var range=document.createRange();range.setStart(el.firstChild,0);range.setEnd(el.firstChild,text.lastIndexOf(".")>0?text.lastIndexOf("."):text.length);return range}var editable_opts={change:rename_file,select:select,validate:function(name){return editor.validate_name(name)}};filename_span.click(function(){if(!asset_model.active())asset_model.controller.select()});remove.click(function(){asset_model.controller.remove()});var result={filename_updated:function(){anchor.text(asset_model.filename())},content_updated:function(){if(asset_model.active())RCloud.UI.scratchpad.content_updated()},language_updated:function(){if(asset_model.active())RCloud.UI.scratchpad.language_updated()},active_updated:function(){if(asset_model.active()){if(!shell.notebook.model.read_only())ui_utils.editable(filename_span,$.extend({allow_edit:true,inactive_text:filename_span.text(),active_text:filename_span.text()},editable_opts));filename_div.addClass("active")}else{ui_utils.editable(filename_span,"destroy");filename_div.removeClass("active")}},self_removed:function(){filename_div.remove()},set_readonly:function(readonly){if(readonly)remove.hide();else remove.show()},div:function(){return filename_div}};return result};Notebook.Asset.create_model=function(content,filename){var cursor_position_;var active_=false;var result=Notebook.Buffer.create_model(content);var base_change_object=result.change_object;_.extend(result,{active:function(new_active){if(!_.isUndefined(new_active)){if(active_!==new_active){active_=new_active;this.notify_views(function(view){view.active_updated()});return active_}else{return null}}return active_},cursor_position:function(new_cursor_position){if(!_.isUndefined(new_cursor_position))cursor_position_=new_cursor_position;return cursor_position_},filename:function(new_filename){if(!_.isUndefined(new_filename)){if(filename!=new_filename){filename=new_filename;this.notify_views(function(view){view.filename_updated()});return filename}else return null}return filename},json:function(){return{content:content,filename:this.filename(),language:this.language()}},change_object:function(obj){obj=obj||{};obj.filename=obj.filename||this.filename();return base_change_object.call(this,obj)}});return result};Notebook.Asset.create_controller=function(asset_model){var result={select:function(){if(RCloud.UI.scratchpad.current_model){RCloud.UI.scratchpad.current_model.controller.deselect()}asset_model.active(true);RCloud.UI.scratchpad.set_model(asset_model)},deselect:function(){asset_model.active(false)},remove:function(force){var asset_name=asset_model.filename();var msg="Do you want to remove the asset '"+asset_name+"' from the notebook?";if(force||confirm(msg)){asset_model.parent_model.controller.remove_asset(asset_model);if(asset_model===RCloud.UI.scratchpad.current_model){var assets=asset_model.parent_model.assets;if(assets.length)assets[0].controller.select();else{RCloud.UI.scratchpad.set_model(null)}}}}};return result};(function(){function ensure_image_has_hash(img){if(img.dataset.sha256)return img.dataset.sha256;var hasher=new sha256(img.getAttribute("src"),"TEXT");img.dataset.sha256=hasher.getHash("SHA-256","HEX");return img.dataset.sha256}var MIN_LINES=2;var EXTRA_HEIGHT_SOURCE=2,EXTRA_HEIGHT_INPUT=10;function create_cell_html_view(language,cell_model){var ace_widget_;var ace_session_;var ace_document_;var am_read_only_="unknown";var source_div_;var code_div_;var result_div_,has_result_;var current_result_;var current_error_;var change_content_;var cell_status_;var above_between_controls_,cell_controls_,left_controls_;var edit_mode_;var highlights_;var code_preprocessors_=[];var running_state_;var prompt_text_;var input_div_,input_ace_div_,input_widget_,input_kont_,input_anim_;var result={};var notebook_cell_div=$("");notebook_cell_div.data("rcloud.model",cell_model);function update_model(){if(!ace_session_)return null;return cell_model.content(ace_session_.getValue())}function update_div_id(){notebook_cell_div.attr("id",Notebook.part_name(cell_model.id(),cell_model.language()));if(left_controls_)left_controls_.controls["cell_number"].set(cell_model.id())}function set_widget_height(){outer_ace_div.css("height",ui_utils.ace_editor_height(ace_widget_,MIN_LINES)+EXTRA_HEIGHT_SOURCE+"px")}cell_status_=$("");var cell_status_left=$("");cell_status_.append(cell_status_left);left_controls_=RCloud.UI.cell_commands.decorate("left",cell_status_left,cell_model,result);if(!shell.is_view_mode()){var cell_control_bar=$("");cell_status_.append(cell_control_bar);cell_control_bar.mousedown(function(e){e.stopPropagation()});cell_controls_=RCloud.UI.cell_commands.decorate("cell",cell_control_bar,cell_model,result);var cell_commands_above=$("");above_between_controls_=RCloud.UI.cell_commands.decorate("above_between",cell_commands_above,cell_model,result);notebook_cell_div.append(cell_commands_above)}notebook_cell_div.append(cell_status_);var edit_colors_={markdown:"#F7EEE4",code:"#E8F1FA"};function set_background_class(div){var md=RCloud.language.is_a_markdown(language);div.toggleClass(md?"edit-markdown":"edit-code",true);div.toggleClass(md?"edit-code":"edit-markdown",false)}function update_language(){language=cell_model.language();if(!RCloud.language.is_a_markdown(language))result.hide_source&&result.hide_source(false);if(cell_controls_)cell_controls_.controls["language_cell"].set(language);set_background_class(code_div_.find("pre"));if(ace_widget_){ace_div.toggleClass("active",true);set_background_class(ace_div);var LangMode=ace.require(RCloud.language.ace_mode(language)).Mode;ace_session_.setMode(new LangMode(false,ace_document_,ace_session_))}}var inner_div=$("");var clear_div=$("");notebook_cell_div.append(inner_div);notebook_cell_div.append(clear_div);source_div_=$('');code_div_=$('');source_div_.append(code_div_);var outer_ace_div=$('');var ace_div=$('');set_background_class(ace_div);update_div_id();outer_ace_div.append(ace_div);source_div_.append(outer_ace_div);inner_div.append(source_div_);function click_to_edit(div,whether){whether&=!am_read_only_;if(whether){set_background_class(code_div_.find("pre"));div.toggleClass("inactive",true);div.on({"mousedown.rcloud-cell":function(e){$(this).data("p0",{x:e.pageX,y:e.pageY})},"mouseup.rcloud-cell":function(e){var p0=$(this).data("p0");if(p0){var p1={x:e.pageX,y:e.pageY},d=Math.sqrt(Math.pow(p1.x-p0.x,2)+Math.pow(p1.y-p0.y,2));if(d<4){result.edit_source(true,e);div.mouseleave()}}}})}else div.off("mousedown.rcloud-cell mouseup.rcloud-cell")}function display_status(status){result_div_.html('");pre.append(current_result_);result_div_.append(pre)}current_result_.append(_.escape(r));break;case"error":if(!current_error_){pre=$("");current_error_=$('');pre.append(current_error_);result_div_.append(pre)}current_error_.append(_.escape(r));break;case"selection":case"html":result_div_.append(r);break;case"deferred_result":result_div_.append(''+r+"");break;default:throw new Error("unknown result type "+type)}result_updated()},end_output:function(error){if(!has_result_){result_div_.empty();has_result_=true}this.state_changed(error?"error":"complete");current_result_=current_error_=null},clear_result:clear_result,set_readonly:function(readonly){am_read_only_=readonly;if(ace_widget_)ui_utils.set_ace_readonly(ace_widget_,readonly);[cell_controls_,above_between_controls_,left_controls_].forEach(function(controls){if(controls)controls.set_flag("modify",!readonly)});click_to_edit(code_div_.find("pre"),!readonly);cell_status_.toggleClass("readonly",readonly)},set_show_cell_numbers:function(whether){left_controls_.set_flag("cell-numbers",whether)},click_to_edit:click_to_edit,execute_cell:function(){var new_content=update_model();var promise;if(new_content!==null)promise=cell_model.parent_model.controller.update_cell(cell_model);else promise=Promise.resolve(undefined);promise.then(function(){cell_model.controller.enqueue_execution_snapshot()})},toggle_edit:function(){return this.edit_source(!edit_mode_)},edit_source:function(edit_mode,event){if(edit_mode===edit_mode_){if(edit_mode)ace_widget_.focus();return}if(edit_mode){if(RCloud.language.is_a_markdown(language))this.hide_source(false);code_div_.hide();create_edit_widget();outer_ace_div.show();ace_widget_.resize(true);set_widget_height();ace_widget_.resize(true);if(cell_controls_)cell_controls_.set_flag("edit",true);outer_ace_div.show();ace_widget_.resize();ace_widget_.focus();if(event){var screenPos=ace_widget_.renderer.pixelToScreenCoordinates(event.pageX,event.pageY);var docPos=ace_session_.screenToDocumentPosition(Math.abs(screenPos.row),Math.abs(screenPos.column));var Range=ace.require("ace/range").Range;var row=Math.abs(docPos.row),column=Math.abs(docPos.column);var range=new Range(row,column,row,column);ace_widget_.getSelection().setSelectionRange(range)}}else{var new_content=update_model();if(new_content!==null)cell_model.parent_model.controller.update_cell(cell_model);source_div_.css({height:""});if(cell_controls_)cell_controls_.set_flag("edit",false);code_div_.show();outer_ace_div.hide()}edit_mode_=edit_mode;this.change_highlights(highlights_)},hide_source:function(whether){if(whether)source_div_.hide();else source_div_.show()},get_input:function(type,prompt,k){if(!has_result_){result_div_.empty();has_result_=true}prompt_text_=prompt;create_input_widget();input_widget_.setValue("");input_div_.show();input_div_.css("height","36px");input_widget_.renderer.$gutterLayer.gutterWidth=0;input_widget_.renderer.$changes|=input_widget_.renderer.__proto__.CHANGE_FULL;input_widget_.resize(true);input_widget_.focus();input_div_.css("border-color","#eeeeee");var dir=false;var switch_color=function(){input_div_.animate({borderColor:dir?"#ffac88":"#E34234"},{duration:1e3,easing:"easeInOutCubic",queue:false});dir=!dir};switch_color();input_anim_=window.setInterval(switch_color,1e3);ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,input_div_);input_kont_=k},div:function(){return notebook_cell_div},update_model:function(){return update_model()},focus:function(){ace_widget_.focus();return this},get_content:function(){return cell_model.content()},reformat:function(){if(edit_mode_){ace_widget_.resize();set_widget_height();ace_widget_.resize()}return this},check_buttons:function(){if(above_between_controls_)above_between_controls_.betweenness(!!cell_model.parent_model.prior_cell(cell_model));return this},change_highlights:function(ranges){highlights_=ranges;if(edit_mode_){var markers=ace_session_.getMarkers();for(var marker in markers){if(markers[marker].type==="rcloud-select")ace_session_.removeMarker(marker)}if(ranges)ranges.forEach(function(range){var ace_range=ui_utils.ace_range_of_character_range(ace_widget_,range.begin,range.end);ace_session_.addMarker(ace_range,highlight_classes(range.kind),"rcloud-select");if(/active/.test(range.kind)){ace_widget_.scrollToLine(ace_range.start.row);window.setTimeout(function(){var hl=ace_div.find(".find-highlight."+range.kind);if(hl.size())ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,ace_div,hl)},0)}})}else{assign_code();var $active=code_div_.find(".find-highlight.active, .find-highlight.activereplaced");if($active.size())ui_utils.scroll_into_view($("#rcloud-cellarea"),100,100,notebook_cell_div,code_div_,$active)}return this}});result.edit_source(false);return result}Notebook.Cell.create_html_view=function(cell_model){return create_cell_html_view(cell_model.language(),cell_model)}})();Notebook.Cell.create_model=function(content,language){var id_=-1;var result=Notebook.Buffer.create_model(content,language);var base_change_object=result.change_object;_.extend(result,{id:function(new_id){if(!_.isUndefined(new_id)&&new_id!=id_){id_=new_id;this.notify_views(function(view){view.id_updated()})}return id_},filename:function(){if(arguments.length)throw new Error("can't set filename of cell");return Notebook.part_name(this.id(),this.language())},get_execution_snapshot:function(){var language=this.language()||"Text";return{controller:this.controller,json_rep:this.json(),partname:Notebook.part_name(this.id(),language),language:language,version:this.parent_model.controller.current_gist().history[0].version}},json:function(){return{content:content,language:this.language()}},change_object:function(obj){obj=obj||{};if(obj.id&&obj.filename)throw new Error("must specify only id or filename");if(!obj.filename){var id=obj.id||this.id();if(id>0!==true)throw new Error("bad id for cell change object: "+id);obj.filename=Notebook.part_name(id,this.language())}if(obj.rename&&_.isNumber(obj.rename))obj.rename=Notebook.part_name(obj.rename,this.language());return base_change_object.call(this,obj)}});return result};Notebook.Cell.create_controller=function(cell_model){var execution_context_=null;var result={enqueue_execution_snapshot:function(){var that=this;if(!execution_context_){function appender(type){return that.append_result.bind(this,type)}var resulter=appender("code");execution_context_={start:this.start_output.bind(this),end:this.end_output.bind(this),out:resulter,err:appender("error"),msg:resulter,html_out:appender("html"),deferred_result:appender("deferred_result"),selection_out:appender("selection"),"in":this.get_input.bind(this,"in")}}var context_id=RCloud.register_output_context(execution_context_);that.set_run_state("waiting");that.edit_source(false);var snapshot=cell_model.get_execution_snapshot();RCloud.UI.run_button.enqueue(function(){that.set_run_state("running");return cell_model.parent_model.controller.execute_cell_version(context_id,snapshot)},function(){that.set_run_state("cancelled")})},set_run_state:function(msg){cell_model.notify_views(function(view){view.state_changed(msg)})},clear_result:function(){cell_model.notify_views(function(view){view.clear_result()})},start_output:function(){cell_model.notify_views(function(view){view.start_output()})},append_result:function(type,msg){cell_model.notify_views(function(view){view.add_result(type,msg)})},end_output:function(error){cell_model.notify_views(function(view){if(error&&error!==true)view.add_result("error",error);view.end_output(error)})},get_input:function(type,prompt,k){var view=_.find(cell_model.views,function(v){return v.get_input});if(!view)k("cell view does not support input",null);else view.get_input(type,prompt,k)},edit_source:function(whether){cell_model.notify_views(function(view){view.edit_source(whether)})},change_language:function(language){cell_model.language(language)}};return result};Notebook.Cell.preprocessors=RCloud.extension.create();Notebook.Cell.postprocessors=RCloud.extension.create();Notebook.Cell.postprocessors.add({device_pixel_ratio:{sort:1e3,disable:true,process:function(div){var dpr=rcloud.display.get_device_pixel_ratio();div.find("img").each(function(i,img){function update(){img.style.width=img.width/dpr}if(img.width===0){$(img).on("load",update)}else{update()}})}},deferred_results:{sort:2e3,process:function(div){var uuid=rcloud.deferred_knitr_uuid;div.find("span.deferred-result").each(function(){var that=this;var uuids=this.textContent.split("|");var ocap=[uuids[1]];ocap.r_attributes={"class":"OCref"};var f=rclient._rserve.wrap_ocap(ocap);f(function(err,future){var data;if(RCloud.is_exception(future)){data=RCloud.exception_message(future);$(that).replaceWith(function(){return ui_utils.string_error(data)})}else{data=future();$(that).replaceWith(function(){return data})}})})}},mathjax:{sort:3e3,process:function(div){if(!_.isUndefined(MathJax))MathJax.Hub.Queue(["Typeset",MathJax.Hub])}},shade_pre_r:{sort:4e3,process:function(div){div.find("pre code").filter(function(i,e){return e.classList.length>0}).parent().toggleClass("r",true)}},hide_source:{sort:5e3,process:function(div){if(!shell.notebook.controller._r_source_visible){Notebook.hide_r_source(div)}}},click_markdown_code:{sort:6e3,process:function(div,view){view.click_to_edit(div.find("pre.r"),true)}}});Notebook.Cell.preprocessors.add({quote_deferred_results:{sort:1e3,process:function(){var deferred_result_uuid_,deferred_regexp_,deferred_replacement_;function make_deferred_regexp(){deferred_result_uuid_=rcloud.deferred_knitr_uuid;deferred_regexp_=new RegExp(deferred_result_uuid_+"\\|[@a-zA-Z_0-9.]*","g");deferred_replacement_='$&'}return function(r){if(!deferred_result_uuid_!=rcloud.deferred_knitr_uuid)make_deferred_regexp();return r.replace(deferred_regexp_,deferred_replacement_)}}()}});Notebook.create_html_view=function(model,root_div){var show_cell_numbers_;function on_rearrange(){_.each(result.sub_views,function(view){view.check_buttons()})}function init_cell_view(cell_view){cell_view.set_readonly(model.read_only()||shell.is_view_mode());cell_view.set_show_cell_numbers(show_cell_numbers_)}var result={model:model,sub_views:[],asset_sub_views:[],cell_appended:function(cell_model){var cell_view=Notebook.Cell.create_html_view(cell_model);cell_model.views.push(cell_view);root_div.append(cell_view.div());this.sub_views.push(cell_view);init_cell_view(cell_view);on_rearrange();return cell_view},asset_appended:function(asset_model){var asset_view=Notebook.Asset.create_html_view(asset_model);asset_model.views.push(asset_view);$("#asset-list").append(asset_view.div());this.asset_sub_views.push(asset_view);on_rearrange();return asset_view},cell_inserted:function(cell_model,cell_index){var cell_view=Notebook.Cell.create_html_view(cell_model);cell_model.views.push(cell_view);root_div.append(cell_view.div());$(cell_view.div()).insertBefore(root_div.children(".notebook-cell")[cell_index]);this.sub_views.splice(cell_index,0,cell_view);init_cell_view(cell_view);on_rearrange();return cell_view},cell_removed:function(cell_model,cell_index){_.each(cell_model.views,function(view){view.self_removed()});this.sub_views.splice(cell_index,1);on_rearrange()},asset_removed:function(asset_model,asset_index){_.each(asset_model.views,function(view){view.self_removed()});this.asset_sub_views.splice(asset_index,1)},cell_moved:function(cell_model,pre_index,post_index){this.sub_views.splice(pre_index,1);this.sub_views.splice(post_index,0,cell_model.views[0]);on_rearrange()},set_readonly:function(readonly){_.each(this.sub_views,function(view){view.set_readonly(readonly)});_.each(this.asset_sub_views,function(view){view.set_readonly(readonly)})},set_show_cell_numbers:function(whether){show_cell_numbers_=whether;_.each(this.sub_views,function(view){view.set_show_cell_numbers(whether)})},update_urls:function(){RCloud.UI.scratchpad.update_asset_url()},update_model:function(){return _.map(this.sub_views,function(cell_view){return cell_view.update_model()})},reformat:function(){_.each(this.sub_views,function(view){view.reformat()})}};model.views.push(result);return result};Notebook.create_model=function(){var readonly_=false;var user_="";function last_id(cells){if(cells.length)return cells[cells.length-1].id();else return 0}return{cells:[],assets:[],views:[],dishers:[],execution_watchers:[],clear:function(){var cells_removed=this.remove_cell(null,last_id(this.cells));var assets_removed=this.remove_asset(null,this.assets.length);return cells_removed.concat(assets_removed)},get_asset:function(filename){return _.find(this.assets,function(asset){return asset.filename()==filename})},append_asset:function(asset_model,filename,skip_event){asset_model.parent_model=this;var changes=[];changes.push(asset_model.change_object());this.assets.push(asset_model);if(!skip_event)_.each(this.views,function(view){view.asset_appended(asset_model)});return changes},append_cell:function(cell_model,id,skip_event){cell_model.parent_model=this;cell_model.renew_content();var changes=[];var n=1;id=id||1;id=Math.max(id,last_id(this.cells)+1);while(n){cell_model.id(id);changes.push(cell_model.change_object());this.cells.push(cell_model);if(!skip_event)_.each(this.views,function(view){view.cell_appended(cell_model)});++id;--n}return changes},insert_cell:function(cell_model,id,skip_event){var that=this;cell_model.parent_model=this;cell_model.renew_content();var changes=[];var n=1,x=0;while(x"+files[i]+""}RCloud.UI.help_frame.display_content(html)},editor:function(what,content,name){append_session_info("what: "+what+"\ncontents:"+content+"\nname: "+name+"\n")},"console.out":forward_to_context("out"),"console.msg":forward_to_context("msg"),"console.err":forward_to_context("err"),"img.url.update":handle_img.bind(null,"img.url.update"),"img.url.final":handle_img.bind(null,"img.url.final"),stdout:append_session_info,stderr:append_session_info,"start.cell.output":function(context){curr_context_id_=context;if(output_contexts_[context]&&output_contexts_[context].start)output_contexts_[context].start()},"html.out":forward_to_context("html_out"),"deferred.result":forward_to_context("deferred_result")};var on_data=function(v){v=v.value.json();console.log("OOB send arrived: ['"+v[0]+"']"+(oob_sends[v[0]]?"":" (unhandled)"));if(oob_sends[v[0]])oob_sends[v[0]].apply(null,v.slice(1))};var oob_messages={"console.in":forward_to_context("in",true)};var on_message=function(v,k){v=v.value.json();console.log("OOB message arrived: ['"+v[0]+"']"+(oob_messages[v[0]]?"":" (unhandled)"));if(oob_messages[v[0]]){v.push(k);oob_messages[v[0]].apply(null,v.slice(1))}else k("unhandled",null)};function could_not_initialize_error(err){var msg="Could not initialize session. The GitHub backend might be down or you might have an invalid authorization token. (You could try clearing your cookies, for example).";if(err)msg+="
'+message+"
",default_button,ignore_button,'');default_button.click(function(e){e.preventDefault();window.location=href});ignore_button.click(function(){fatal_dialog_.modal("hide")});fatal_dialog_=$('').append($('').append($('').append($('').append(body))));$("body").append(fatal_dialog_);fatal_dialog_.on("shown.bs.modal",function(){default_button.focus()})}fatal_dialog_.modal({keyboard:false})}})();RCloud.UI.find_replace=function(){var find_dialog_=null,regex_,find_desc_,find_input_,replace_desc_,replace_input_,replace_stuff_,find_next_,find_last_,replace_next_,replace_all_,shown_=false,replace_mode_=false,find_cycle_=null,replace_cycle_=null,matches_=[],active_match_;function toggle_find_replace(replace){if(!find_dialog_){find_dialog_=$('');var find_form=$('');find_desc_=$('');find_input_=$('');find_next_=$('');find_last_=$('');var replace_break=$("Import notebooks from another GitHub instance.
Currently import does not preserve history.
",'source repo api url: ','
notebooks:
prefix (e.g. folder/ to put notebooks in a folder): '].join("")));var cancel=$('Cancel').on("click",function(){$(dialog).modal("hide")});var go=$('Import').on("click",do_import);var footer=$('
The search engine in RCloud uses Lucene for advanced search features.',"It appears you may have used one of the special characters in Lucene syntax incorrectly. ",'Please see this link to learn about Lucene syntax. ','
Or, if you mean to search for the character itself, escape it using a backslash, e.g. "foo\\:"
'];function go_to_page(page_num,incr_by){var start=parseInt(page_num)*parseInt(incr_by);var end=parseInt(start)+parseInt(incr_by);var qry=$("#input-text-search").val();var sortby=$("#sort-by option:selected").val();var orderby=$("#order-by option:selected").val();$("#input-text-search").blur();if(!($("#input-text-search").val()===""))RCloud.UI.search.exec(qry,sortby,orderby,start,end,true)}function sortby(){return $("#sort-by option:selected").val()}function orderby(){return $("#order-by option:selected").val()}function order_from_sort(){var orderby;switch(sortby()){case"starcount":case"updated_at":orderby="desc";break;case"user":case"description":orderby="asc";break}$("#order-by").val(orderby)}return{body:function(){return RCloud.UI.panel_loader.load_snippet("search-snippet")},init:function(){if(!rcloud.search)$("#search-wrapper").text("Search engine not enabled on server");else{$("#search-form").submit(function(e){searchproc();return false});$("#sort-by").change(function(){rcloud.config.set_user_option("search-sort-by",sortby());order_from_sort();rcloud.config.set_user_option("search-order-by",orderby());searchproc()});$("#order-by").change(function(){rcloud.config.set_user_option("search-order-by",orderby());searchproc()});var searchproc=function(){var start=0;var qry=$("#input-text-search").val();$("#input-text-search").focus();if(!($("#input-text-search").val()==="")){RCloud.UI.search.exec(qry,sortby(),orderby(),start,page_size_)}else{$("#paging").html("");$("#search-results").html("");$("#search-summary").html("")}}}},load:function(){return rcloud.config.get_user_option(["search-results-per-page","search-sort-by","search-order-by"]).then(function(opts){if(opts["search-results-per-page"])page_size_=opts["search-results-per-page"];if(!opts["search-sort-by"])opts["search-sort-by"]="starcount";$("#sort-by").val(opts["search-sort-by"]);if(opts["search-order-by"])$("#order-by").val(opts["search-order-by"]);else order_from_sort()})},panel_sizer:function(el){var padding=RCloud.UI.collapsible_column.default_padder(el);var height=24+$("#search-summary").height()+$("#search-results").height()+$("#search-results-pagination").height();height+=30;return{height:height,padding:padding}},toggle:function(id,togid){$("#"+togid+"").text(function(_,txt){var ret="";if(txt.indexOf("Show me more...")>-1){ret="Show me less...";$("#"+id+"").css("height","auto")}else{ret="Show me more...";$("#"+id+"").css("height","150px")}return ret});return false},exec:function(query,sortby,orderby,start,noofrows,pgclick){function summary(html,color){$("#search-summary").css("color",color||"black");$("#search-summary").show().html($("").append(html))}function err_msg(html,color){$("#search-summary").css("display","none");$("#search-results").css("color",color||"black");$("#search-results-row").show().animate({scrollTop:$(document).height()},"slow");$("#search-results").show().html($("").append(html))}function create_list_of_search_results(d){var i;var custom_msg="";if(d===null||d==="null"||d===""){summary("No Results Found")}else if(d[0]==="error"){d[1]=d[1].replace(/\n/g,""+content[l]+"| "+'"+d[i].user+" / "+d[i].notebook+""+image_string+" modified at "+d[i].updated_at+" | |
"+parts_table+" | |
File "+filename+" exists.
");var overwrite=bootstrap_utils.button({"class":"btn-danger"}).click(overwrite_click).text("Overwrite");p.append(overwrite);var alert_box=result_alert(p);$("button.close",alert_box).click(function(){callback(new Error("Overwrite cancelled"),null)})})}}options=upload_ui_opts(options||{});if(options.$result_panel.length)RCloud.UI.right_panel.collapse(options.$result_panel,false);var file_error_handler=function(err){var message=err.message;var p,done=true;if(message==="empty"){p=$("File is empty.
")}else if(message==="Overwrite cancelled"){p=$("").append(message)}else if(message==="badname"){p=$("
Filename not allowed.
")}else{p=$("(unexpected) "+message+"
");console.log(message,err.stack)}result_alert(p);throw err};var promise=to_notebook?RCloud.upload_assets(options,asset_react(options)):RCloud.upload_files(options,file_react(options));return promise.catch(function(err){return file_error_handler(err,options)}).then(function(){if(options.$progress.length)window.setTimeout(function(){options.$progress.hide()},5e3)})}return upload_files}();RCloud.UI.upload_frame={body:function(){return RCloud.UI.panel_loader.load_snippet("file-upload-snippet")},init:function(){$("#file").change(function(){$("#progress-bar").css("width","0%")});$("#upload-submit").click(function(){if($("#file")[0].files.length===0)return;var to_notebook=$("#upload-to-notebook").is(":checked");RCloud.UI.upload_with_alerts(to_notebook).catch(function(){})});RCloud.session.listeners.push({on_reset:function(){$(".progress").hide();$("#file-upload-results").empty()}})},panel_sizer:function(el){var padding=RCloud.UI.collapsible_column.default_padder(el);var height=24+$("#file-upload-controls").height()+$("#file-upload-results").height();return{height:height,padding:padding}}}; \ No newline at end of file +notebook_desc.show();notebook=Notebook.sanitize(notebook);ui_utils.enable_bs_button(import_button)};fr.readAsText(file)}function do_import(){if(notebook){notebook.description=notebook_desc_content.val();rcloud.create_notebook(notebook).then(function(notebook){editor.star_notebook(true,{notebook:notebook}).then(function(){editor.set_notebook_visibility(notebook.id,true)})})}dialog.modal("hide")}var body=$('');var file_select=$('');file_select.click(function(){ui_utils.disable_bs_button(import_button)}).change(function(){do_upload(file_select[0].files[0])});notebook_status=$("");notebook_status.append(notebook_status);var notebook_desc=$("Notebook description: ");notebook_desc_content=$('').keypress(function(e){if(e.which===$.ui.keyCode.ENTER){do_import();return false}return true});notebook_desc.append(notebook_desc_content);body.append($("").append(file_select)).append($("").append(notebook_status.hide())).append($("").append(notebook_desc.hide()));var cancel=$('Cancel').on("click",function(){$(dialog).modal("hide")});import_button=$('Import').on("click",do_import);ui_utils.disable_bs_button(import_button);var footer=$('').append(cancel).append(import_button);var header=$(['The search engine in RCloud uses Lucene for advanced search features.',"It appears you may have used one of the special characters in Lucene syntax incorrectly. ",'Please see this link to learn about Lucene syntax. ','
Or, if you mean to search for the character itself, escape it using a backslash, e.g. "foo\\:"
'];function go_to_page(page_num,incr_by){var start=parseInt(page_num)*parseInt(incr_by);var end=parseInt(start)+parseInt(incr_by);var qry=$("#input-text-search").val();var sortby=$("#sort-by option:selected").val();var orderby=$("#order-by option:selected").val();$("#input-text-search").blur();if(!($("#input-text-search").val()===""))RCloud.UI.search.exec(qry,sortby,orderby,start,end,true)}function sortby(){return $("#sort-by option:selected").val()}function orderby(){return $("#order-by option:selected").val()}function order_from_sort(){var orderby;switch(sortby()){case"starcount":case"updated_at":orderby="desc";break;case"user":case"description":orderby="asc";break}$("#order-by").val(orderby)}return{body:function(){return RCloud.UI.panel_loader.load_snippet("search-snippet")},init:function(){if(!rcloud.search)$("#search-wrapper").text("Search engine not enabled on server");else{$("#search-form").submit(function(e){searchproc();return false});$("#sort-by").change(function(){rcloud.config.set_user_option("search-sort-by",sortby());order_from_sort();rcloud.config.set_user_option("search-order-by",orderby());searchproc()});$("#order-by").change(function(){rcloud.config.set_user_option("search-order-by",orderby());searchproc()});var searchproc=function(){var start=0;var qry=$("#input-text-search").val();$("#input-text-search").focus();if(!($("#input-text-search").val()==="")){RCloud.UI.search.exec(qry,sortby(),orderby(),start,page_size_)}else{$("#paging").html(""); +$("#search-results").html("");$("#search-summary").html("")}}}},load:function(){return rcloud.config.get_user_option(["search-results-per-page","search-sort-by","search-order-by"]).then(function(opts){if(opts["search-results-per-page"])page_size_=opts["search-results-per-page"];if(!opts["search-sort-by"])opts["search-sort-by"]="starcount";$("#sort-by").val(opts["search-sort-by"]);if(opts["search-order-by"])$("#order-by").val(opts["search-order-by"]);else order_from_sort()})},panel_sizer:function(el){var padding=RCloud.UI.collapsible_column.default_padder(el);var height=24+$("#search-summary").height()+$("#search-results").height()+$("#search-results-pagination").height();height+=30;return{height:height,padding:padding}},toggle:function(id,togid){$("#"+togid+"").text(function(_,txt){var ret="";if(txt.indexOf("Show me more...")>-1){ret="Show me less...";$("#"+id+"").css("height","auto")}else{ret="Show me more...";$("#"+id+"").css("height","150px")}return ret});return false},exec:function(query,sortby,orderby,start,noofrows,pgclick){function summary(html,color){$("#search-summary").css("color",color||"black");$("#search-summary").show().html($("").append(html))}function err_msg(html,color){$("#search-summary").css("display","none");$("#search-results").css("color",color||"black");$("#search-results-row").show().animate({scrollTop:$(document).height()},"slow");$("#search-results").show().html($("").append(html))}function create_list_of_search_results(d){var i;var custom_msg="";if(d===null||d==="null"||d===""){summary("No Results Found")}else if(d[0]==="error"){d[1]=d[1].replace(/\n/g,""+content[l]+"| "+'"+d[i].user+" / "+d[i].notebook+""+image_string+" modified at "+d[i].updated_at+" | |
"+parts_table+" | |
File "+filename+" exists.
");var overwrite=bootstrap_utils.button({"class":"btn-danger"}).click(overwrite_click).text("Overwrite");p.append(overwrite);var alert_box=result_alert(p);$("button.close",alert_box).click(function(){callback(new Error("Overwrite cancelled"),null)})})}}options=upload_ui_opts(options||{});if(options.$result_panel.length)RCloud.UI.right_panel.collapse(options.$result_panel,false);var file_error_handler=function(err){var message=err.message;var p,done=true;if(message==="empty"){p=$("File is empty.
")}else if(message==="Overwrite cancelled"){p=$("").append(message)}else if(message==="badname"){p=$("
Filename not allowed.
")}else{p=$("(unexpected) "+message+"
");console.log(message,err.stack)}result_alert(p);throw err};var promise=to_notebook?RCloud.upload_assets(options,asset_react(options)):RCloud.upload_files(options,file_react(options));return promise.catch(function(err){return file_error_handler(err,options)}).then(function(){if(options.$progress.length)window.setTimeout(function(){options.$progress.hide()},5e3)})}return upload_files}();RCloud.UI.upload_frame={body:function(){return RCloud.UI.panel_loader.load_snippet("file-upload-snippet")},init:function(){$("#file").change(function(){$("#progress-bar").css("width","0%")});$("#upload-submit").click(function(){if($("#file")[0].files.length===0)return;var to_notebook=$("#upload-to-notebook").is(":checked");RCloud.UI.upload_with_alerts(to_notebook).catch(function(){})});RCloud.session.listeners.push({on_reset:function(){$(".progress").hide();$("#file-upload-results").empty()}})},panel_sizer:function(el){var padding=RCloud.UI.collapsible_column.default_padder(el);var height=24+$("#file-upload-controls").height()+$("#file-upload-results").height();return{height:height,padding:padding}}}; \ No newline at end of file diff --git a/htdocs/js/ui/init.js b/htdocs/js/ui/init.js index 6e08540ca2..8d2bf27de2 100644 --- a/htdocs/js/ui/init.js +++ b/htdocs/js/ui/init.js @@ -19,6 +19,7 @@ RCloud.UI.init = function() { shell.notebook.controller.save_button(saveb); RCloud.UI.run_button.init(); + RCloud.UI.toggle_button.init(); ////////////////////////////////////////////////////////////////////////// // allow reordering cells by dragging them diff --git a/htdocs/js/ui/run_button.js b/htdocs/js/ui/run_button.js index 6bcf3ca388..a8e39a1604 100644 --- a/htdocs/js/ui/run_button.js +++ b/htdocs/js/ui/run_button.js @@ -39,10 +39,16 @@ RCloud.UI.run_button = (function() { return { init: function() { var that = this; + run_button_.click(function() { if(running_) { that.stop(); } + else if ($('#iframe').css('display')!=='none') { + shell.save_notebook(); + var target_url = window.location.origin+'/notebook.R/'+shell.gistname()+'/index.html'; + $('#iframe').attr('src',target_url); + } else shell.run_notebook(); }); diff --git a/htdocs/js/ui/toggle_button.js b/htdocs/js/ui/toggle_button.js new file mode 100644 index 0000000000..bb44117daf --- /dev/null +++ b/htdocs/js/ui/toggle_button.js @@ -0,0 +1,97 @@ +RCloud.UI.toggle_button = (function() { + var toggle_button_ = $("#toggle-view"), + external_link_ = $('#external-link'), + iframe_ = $('#iframe'), + output_ = $('#output'), + end_of_output_ = $('#end-of-output'); + + function display(icon, title) { + $('i', toggle_button_).removeClass().addClass(icon); + toggle_button_.attr('title', title); + } + function highlight(whether) { + toggle_button_.parent().find('.button-highlight').animate({opacity: whether ? 1 : 0}, 250); + } + function createIndex() { + var found = shell.notebook.model.get_asset('index.html'); + + var indexTemplate = + +"\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +Hello World!\n\ +\n\ +\n\ +\n\ +"; + + if(found) { + found.controller.select(); + } + else { + shell.notebook.controller + .append_asset(indexTemplate, 'index.html') + .spread(function(_, controller) { + controller.select(); + ui_utils.ace_set_pos(RCloud.UI.scratchpad.widget, 2, 1); + }); + } + } + + function toggleHTML5() { + toggle_button_.click(function () {}); + createIndex(); + $('#new-tab a').attr('href',window.location.origin+'/notebook.R/'+shell.gistname()+'/index.html'); + + output_.hide(); + end_of_output_.hide(); + $('#prompt-area').hide(); + iframe_.show(); + $('#new-tab').show(); + display('icon-code','Toggle Notebook'); + toggle_button_.click(toggleCode); + highlight(false); + } + + function toggleCode() { + toggle_button_.click(function () {}); + iframe_.hide(); + $('#new-tab').hide(); + output_.show(); + end_of_output_.show(); + $('#prompt-area').show(); + display('icon-html5','Toggle Web View'); + toggle_button_.click(toggleHTML5); + highlight(false); + } + + return { + init: function() { + toggleCode(); + } + }; +})(); diff --git a/htdocs/lib/js/require-fiddle-output.js b/htdocs/lib/js/require-fiddle-output.js new file mode 100644 index 0000000000..ad246e7c95 --- /dev/null +++ b/htdocs/lib/js/require-fiddle-output.js @@ -0,0 +1,18 @@ +requirejs.config(requirejs_config_obj); + +var deps = common_deps; + +deps.push( + // rcloud's fiddle.js and bundle + "rcloud_bundle" +); + +start_require(deps); + +function main() { + $.getScript('/fiddle.js', function () { + if(window.start) { + window.start(); + } + }); +} diff --git a/htdocs/lib/js/require-fiddle.js b/htdocs/lib/js/require-fiddle.js new file mode 100644 index 0000000000..bd1277d9b7 --- /dev/null +++ b/htdocs/lib/js/require-fiddle.js @@ -0,0 +1,15 @@ +requirejs.config(requirejs_config_obj); + +var deps = common_deps; + +deps.push( + // rcloud's edit.js and bundle + "../../edit", "../../fiddle.js", "rcloud_bundle", + + // rcloud's other files + "shell_tab", "editor_tab" +); + +start_require(deps); + +function main() { $.getScript('/fiddle.js', function () {}) } \ No newline at end of file