dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/app.js
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 11 Feb 2013 19:55:00 +0100
branchemul
changeset 711 333326d65bf9
parent 579 942deef87200
permissions -rw-r--r--
Allows two isolated bck2brwsr VM in a single JavaScript page/context
     1 // 'use strict';
     2 
     3 // Declare app level module which depends on filters, and services
     4 angular.module('bck2brwsr', []).
     5   directive('uiCodemirror', ['$timeout', function($timeout) {
     6         'use strict';
     7 
     8         var events = ["cursorActivity", "viewportChange", "gutterClick", "focus", "blur", "scroll", "update"];
     9         return {
    10             restrict: 'A',
    11             require: 'ngModel',
    12             link: function(scope, elm, attrs, ngModel) {
    13                 var options, opts, onChange, deferCodeMirror, codeMirror, timeoutId, val;
    14 
    15                 if (elm[0].type !== 'textarea') {
    16                     throw new Error('uiCodemirror3 can only be applied to a textarea element');
    17                 }
    18 
    19                 options = /* uiConfig.codemirror  || */ {};
    20                 opts = angular.extend({}, options, scope.$eval(attrs.uiCodemirror));
    21 
    22                 onChange = function(instance, changeObj) {                    
    23                     val = instance.getValue();
    24                     $timeout.cancel(timeoutId);
    25                     timeoutId = $timeout(function() {
    26                         ngModel.$setViewValue(val);                        
    27                       }, 500);                    
    28                 };
    29                 
    30                 deferCodeMirror = function() {
    31                     codeMirror = CodeMirror.fromTextArea(elm[0], opts);
    32                     elm[0].codeMirror = codeMirror;
    33                     // codeMirror.on("change", onChange(opts.onChange));
    34                     codeMirror.on("change", onChange);
    35 
    36                     for (var i = 0, n = events.length, aEvent; i < n; ++i) {
    37                         aEvent = opts["on" + events[i].charAt(0).toUpperCase() + events[i].slice(1)];
    38                         if (aEvent === void 0)
    39                             continue;
    40                         if (typeof aEvent !== "function")
    41                             continue;
    42                                                 
    43                         var bound = _.bind( aEvent, scope );
    44                         
    45                         codeMirror.on(events[i], bound);
    46                     }
    47 
    48                     // CodeMirror expects a string, so make sure it gets one.
    49                     // This does not change the model.
    50                     ngModel.$formatters.push(function(value) {
    51                         if (angular.isUndefined(value) || value === null) {
    52                             return '';
    53                         }
    54                         else if (angular.isObject(value) || angular.isArray(value)) {
    55                             throw new Error('ui-codemirror cannot use an object or an array as a model');
    56                         }
    57                         return value;
    58                     });
    59 
    60                     // Override the ngModelController $render method, which is what gets called when the model is updated.
    61                     // This takes care of the synchronizing the codeMirror element with the underlying model, in the case that it is changed by something else.
    62                     ngModel.$render = function() {
    63                         codeMirror.setValue(ngModel.$viewValue);
    64                     };
    65 
    66                 };
    67 
    68                 $timeout(deferCodeMirror);
    69 
    70             }
    71         };
    72 }]);
    73 
    74 function DevCtrl( $scope, $http ) {
    75     var templateHtml = 
    76 "<html><body>\n" +
    77 "  <input data-bind=\"value: value, valueUpdate: 'afterkeydown'\" \n" +
    78 "     value=\"0\" type=\"number\">\n" +
    79 "  </input>\n" +
    80 "  * <span data-bind=\"text: value\">0</span> \n" +
    81 "  = <span data-bind=\"text: powerValue\">0</span>\n" +
    82 "  <br/>\n" +
    83 "  <button id='dupl'>Duplicate!</button>\n" +
    84 "  <button id=\"clear\">Clear!</button>" +
    85 " <hr/>\n" +
    86 "\n" +
    87 "\n" +
    88 "\n" +
    89 "\n" +
    90 "\n" +
    91 "\n" +
    92 "\n" +
    93 "\n" +
    94 "\n" +
    95 "\n" +
    96 "\n" +
    97 "\n" +
    98 "\n" +
    99 "\n" +
   100 "\n" +
   101 "\n" +
   102 "\n" +
   103 "\n" +
   104 "\n" +
   105 "\n" +
   106 " <script src=\"/bck2brwsr.js\"></script>\n" +
   107 " <script type=\"text/javascript\">\n" +
   108 "   function ldCls(res) {\n" +
   109 "     var request = new XMLHttpRequest();\n" +
   110 "     request.open('GET', '/classes/' + res, false);\n" +
   111 "     request.send();\n" +
   112 "     var arr = eval('(' + request.responseText + ')');\n" +
   113 "     return arr;\n" +
   114 "   }\n" +
   115 "   var vm = bck2brwsr(ldCls);\n" +
   116 "   vm.loadClass('${fqn}');\n" +
   117 " </script>\n" +
   118 "</body></html>";
   119     var templateJava = 
   120 "package bck2brwsr.demo;\n" +
   121 "import org.apidesign.bck2brwsr.htmlpage.api.*;\n" +
   122 "import static org.apidesign.bck2brwsr.htmlpage.api.OnEvent.*;\n" +
   123 "\n" +
   124 "@Page(xhtml=\"index.html\", className=\"Index\", properties={\n" +
   125 "  @Property(name=\"value\", type=int.class)\n" +
   126 "})\n" +
   127 "class YourFirstHTML5PageInRealLanguage {\n" +
   128 "  static { new Index().applyBindings(); }\n" +
   129 "  @On(event=CLICK, id=\"dupl\") static void duplicateValue(Index m) {\n" +
   130 "    m.setValue(m.getValue() * 2);\n" +
   131 "  }\n" +
   132 "  @On(event=CLICK, id=\"clear\") static void zeroTheValue(Index m) {\n" +
   133 "     m.setValue(0);;\n" +
   134 "  }\n" +
   135 "  @ComputedProperty static int powerValue(int value) {\n" +
   136 "    return value * value;\n" +
   137 "  }\n" +
   138 "}";
   139 
   140     
   141     $scope.makeMarker = function( editor, line ) {
   142         var marker = document.createElement("div");
   143         marker.innerHTML = " ";
   144         marker.className = "issue";
   145         
   146         var info = editor.lineInfo(line);
   147         editor.setGutterMarker(line, "issues", info.markers ? null : marker);
   148         
   149         return marker;
   150     };
   151     
   152     
   153     // Returns a function, that, as long as it continues to be invoked, will not
   154     // be triggered. The function will be called after it stops being called for
   155     // N milliseconds. If `immediate` is passed, trigger the function on the
   156     // leading edge, instead of the trailing.
   157     $scope.debounce = function(func, wait, immediate) {
   158       var timeout, result;
   159       return function() {
   160         var context = this, args = arguments;
   161         var later = function() {
   162           timeout = null;
   163           if (!immediate) result = func.apply(context, args);
   164         };
   165         var callNow = immediate && !timeout;
   166         clearTimeout(timeout);
   167         timeout = setTimeout(later, wait);
   168         if (callNow) result = func.apply(context, args);
   169         return result;
   170       };
   171     };
   172     
   173     $scope.reload = function() {
   174         $scope.errors = null;
   175         var frame = document.getElementById("result");        
   176         frame.src = "result.html";
   177         frame.contentDocument.location.reload(true);
   178         frame.contentWindow.location.reload();
   179         document.getElementById("editorJava").codeMirror.clearGutter("issues");   
   180     };
   181     
   182     $scope.fail = function( data ) {
   183         $scope.errors = eval( data );
   184         var editor = document.getElementById("editorJava").codeMirror;   
   185         editor.clearGutter( "issues" );
   186         
   187         for( var i = 0; i < $scope.errors.length; i ++ ) {
   188             $scope.makeMarker( editor, $scope.errors[i].line - 1 );
   189         }
   190         
   191     };
   192     
   193     $scope.post = function() {
   194         return $http({url: ".",
   195             method: "POST",
   196             //headers: this.headers,
   197             data: { html : $scope.html, java : $scope.java} 
   198         }).success( $scope.reload ).error( $scope.fail );
   199     };
   200     
   201     $scope.errorClass = function( kind ) {
   202         switch( kind ) {
   203             case "ERROR" :
   204                 return "error";
   205             default :         
   206                 return "warning";   
   207         }
   208     };
   209     
   210     $scope.gotoError = function( line, col ) {
   211         var editor = document.getElementById("editorJava").codeMirror;   
   212         editor.setCursor({ line: line - 1, ch : col - 1 });
   213         editor.focus();
   214     };
   215     
   216     $scope.tab = "html";
   217     $scope.html= templateHtml;  
   218     $scope.java = templateJava;  
   219     
   220     $scope.$watch( "html", $scope.debounce( $scope.post, 2000 ) );
   221     $scope.$watch( "java", $scope.debounce( $scope.post, 2000 ) );
   222     $scope.post();
   223     
   224 }