ko4j/src/main/java/org/netbeans/html/ko4j/Knockout.java
author Jaroslav Tulach <jtulach@netbeans.org>
Tue, 16 Dec 2014 21:03:16 +0100
branchApplyId
changeset 908 ee7a0b3b2d4c
parent 902 5c65f811cf55
child 925 2e197c8a6a60
permissions -rw-r--r--
Providing an ability to apply model to element with certain id
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
     5  *
     6  * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
     7  * Other names may be trademarks of their respective owners.
     8  *
     9  * The contents of this file are subject to the terms of either the GNU
    10  * General Public License Version 2 only ("GPL") or the Common
    11  * Development and Distribution License("CDDL") (collectively, the
    12  * "License"). You may not use this file except in compliance with the
    13  * License. You can obtain a copy of the License at
    14  * http://www.netbeans.org/cddl-gplv2.html
    15  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    16  * specific language governing permissions and limitations under the
    17  * License.  When distributing the software, include this License Header
    18  * Notice in each file and include the License file at
    19  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    20  * particular file as subject to the "Classpath" exception as provided
    21  * by Oracle in the GPL Version 2 section of the License file that
    22  * accompanied this code. If applicable, add the following below the
    23  * License Header, with the fields enclosed by brackets [] replaced by
    24  * your own identifying information:
    25  * "Portions Copyrighted [year] [name of copyright owner]"
    26  *
    27  * Contributor(s):
    28  *
    29  * The Original Software is NetBeans. The Initial Developer of the Original
    30  * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
    31  *
    32  * If you wish your version of this file to be governed by only the CDDL
    33  * or only the GPL Version 2, indicate your decision by adding
    34  * "[Contributor] elects to include this software in this distribution
    35  * under the [CDDL or GPL Version 2] license." If you do not indicate a
    36  * single choice of license, a recipient has the option to distribute
    37  * your version of this file under either the CDDL, the GPL Version 2 or
    38  * to extend the choice of license to its licensees as provided above.
    39  * However, if you add GPL Version 2 code and therefore, elected the GPL
    40  * Version 2 license, then the option applies only if the new code is
    41  * made subject to such option by the copyright holder.
    42  */
    43 package org.netbeans.html.ko4j;
    44 
    45 import java.lang.ref.ReferenceQueue;
    46 import java.lang.ref.WeakReference;
    47 import net.java.html.js.JavaScriptBody;
    48 import net.java.html.js.JavaScriptResource;
    49 import net.java.html.json.Model;
    50 import org.netbeans.html.json.spi.FunctionBinding;
    51 import org.netbeans.html.json.spi.PropertyBinding;
    52 
    53 /** This is an implementation package - just
    54  * include its JAR on classpath and use official {@link Context} API
    55  * to access the functionality.
    56  * <p>
    57  * Provides binding between {@link Model models} and knockout.js running
    58  * inside a JavaFX WebView. 
    59  *
    60  * @author Jaroslav Tulach
    61  */
    62 @JavaScriptResource("knockout-3.2.0.debug.js")
    63 final class Knockout extends WeakReference<Object> {
    64     private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue();
    65     
    66     private PropertyBinding[] props;
    67     private FunctionBinding[] funcs;
    68     private Object js;
    69     private Object strong;
    70 
    71     public Knockout(Object model, Object js, PropertyBinding[] props, FunctionBinding[] funcs) {
    72         super(model, QUEUE);
    73         this.js = js;
    74         this.props = new PropertyBinding[props.length];
    75         for (int i = 0; i < props.length; i++) {
    76             this.props[i] = props[i].weak();
    77         }
    78         this.funcs = new FunctionBinding[funcs.length];
    79         for (int i = 0; i < funcs.length; i++) {
    80             this.funcs[i] = funcs[i].weak();
    81         }
    82     }
    83     
    84     static void cleanUp() {
    85         for (;;) {
    86             Knockout ko = (Knockout)QUEUE.poll();
    87             if (ko == null) {
    88                 return;
    89             }
    90             clean(ko.js);
    91             ko.js = null;
    92             ko.props = null;
    93             ko.funcs = null;
    94         }
    95     }
    96     
    97     final void hold() {
    98         strong = get();
    99     }
   100     
   101     final Object getValue(int index) {
   102         return props[index].getValue();
   103     }
   104     
   105     final void setValue(int index, Object v) {
   106         if (v instanceof Knockout) {
   107             v = ((Knockout)v).get();
   108         }
   109         props[index].setValue(v);
   110     }
   111     
   112     final void call(int index, Object data, Object ev) {
   113         funcs[index].call(data, ev);
   114     }
   115     
   116     @JavaScriptBody(args = { "model", "prop", "oldValue", "newValue" }, 
   117         wait4js = false,
   118         body =
   119           "if (model) {\n"
   120         + "  var koProp = model[prop];\n"
   121         + "  if (koProp && koProp['valueHasMutated']) {\n"
   122         + "    if ((oldValue !== null || newValue !== null)) {\n"
   123         + "      koProp['valueHasMutated'](newValue);\n"
   124         + "    } else if (koProp['valueHasMutated']) {\n"
   125         + "      koProp['valueHasMutated']();\n"
   126         + "    }\n"
   127         + "  }\n"
   128         + "}\n"
   129     )
   130     public native static void valueHasMutated(
   131         Object model, String prop, Object oldValue, Object newValue
   132     );
   133 
   134     @JavaScriptBody(args = { "id", "bindings" }, body = 
   135         "var d = window['document'];\n" +
   136         "var e = id ? d['getElementById'](id) : d['body'];\n" +
   137         "ko['cleanNode'](e);\n" +
   138         "ko['applyBindings'](bindings, e);\n" +
   139         "return bindings['ko4j'];\n"
   140     )
   141     native static Object applyBindings(String id, Object bindings);
   142     
   143     @JavaScriptBody(args = { "cnt" }, body = 
   144         "var arr = new Array(cnt);\n" +
   145         "for (var i = 0; i < cnt; i++) arr[i] = new Object();\n" +
   146         "return arr;\n"
   147     )
   148     native static Object[] allocJS(int cnt);
   149     
   150     @JavaScriptBody(
   151         javacall = true,
   152         keepAlive = false,
   153         wait4js = false,
   154         args = { "ret", "propNames", "propReadOnly", "propValues", "funcNames" },
   155         body = 
   156           "Object.defineProperty(ret, 'ko4j', { value : this });\n"
   157         + "function koComputed(index, name, readOnly, value) {\n"
   158         + "  var trigger = ko['observable']()['extend']({'notify':'always'});"
   159         + "  function realGetter() {\n"
   160         + "    var self = ret['ko4j'];\n"
   161         + "    try {\n"
   162         + "      var v = self ? self.@org.netbeans.html.ko4j.Knockout::getValue(I)(index) : null;\n"
   163         + "      return v;\n"
   164         + "    } catch (e) {\n"
   165         + "      alert(\"Cannot call getValue on \" + self + \" prop: \" + name + \" error: \" + e);\n"
   166         + "    }\n"
   167         + "  }\n"
   168         + "  var activeGetter = function() { return value; };\n"
   169         + "  var bnd = {\n"
   170         + "    'read': function() {\n"
   171         + "      trigger();\n"
   172         + "      var r = activeGetter();\n"
   173         + "      activeGetter = realGetter;\n"
   174         + "      if (r) try { var br = r.valueOf(); } catch (err) {}\n"
   175         + "      return br === undefined ? r: br;\n"
   176         + "    },\n"
   177         + "    'owner': ret\n"
   178         + "  };\n"
   179         + "  if (!readOnly) {\n"
   180         + "    bnd['write'] = function(val) {\n"
   181         + "      var self = ret['ko4j'];\n"
   182         + "      if (!self) return;\n"
   183         + "      var model = val['ko4j'];\n"
   184         + "      var s = ret['ko4j'];\n"
   185         + "      s.@org.netbeans.html.ko4j.Knockout::setValue(ILjava/lang/Object;)(index, model ? model : val);\n"
   186         + "    };\n"
   187         + "  };\n"
   188         + "  var cmpt = ko['computed'](bnd);\n"
   189         + "  cmpt['valueHasMutated'] = function(val) {\n"
   190         + "    if (arguments.length === 1) activeGetter = function() { return val; };\n"
   191         + "    trigger['valueHasMutated']();\n"
   192         + "  };\n"
   193         + "  ret[name] = cmpt;\n"
   194         + "}\n"
   195         + "for (var i = 0; i < propNames.length; i++) {\n"
   196         + "  koComputed(i, propNames[i], propReadOnly[i], propValues[i]);\n"
   197         + "}\n"
   198         + "function koExpose(index, name) {\n"
   199         + "  ret[name] = function(data, ev) {\n"
   200         + "    var self = ret['ko4j'];\n"
   201         + "    if (!self) return;\n"
   202         + "    self.@org.netbeans.html.ko4j.Knockout::call(ILjava/lang/Object;Ljava/lang/Object;)(index, data, ev);\n"
   203         + "  };\n"
   204         + "}\n"
   205         + "for (var i = 0; i < funcNames.length; i++) {\n"
   206         + "  koExpose(i, funcNames[i]);\n"
   207         + "}\n"
   208         )
   209     native void wrapModel(
   210         Object ret, 
   211         String[] propNames, boolean[] propReadOnly, Object propValues,
   212         String[] funcNames
   213     );
   214     
   215     @JavaScriptBody(args = { "js" }, wait4js = false, body = 
   216         "delete js['ko4j'];\n" +
   217         "for (var p in js) {\n" +
   218         "  delete js[p];\n" +
   219         "};\n" +
   220         "\n"
   221     )
   222     private static native void clean(Object js);
   223     
   224     @JavaScriptBody(args = { "o" }, body = "return o['ko4j'] ? o['ko4j'] : o;")
   225     private static native Object toModelImpl(Object wrapper);
   226     static Object toModel(Object wrapper) {
   227         Object o = toModelImpl(wrapper);
   228         if (o instanceof Knockout) {
   229             return ((Knockout)o).get();
   230         } else {
   231             return o;
   232         }
   233     }
   234 }