1.1 --- a/ko-fx/pom.xml Thu Jan 09 11:53:46 2014 +0100
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,115 +0,0 @@
1.4 -<?xml version="1.0"?>
1.5 -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
1.6 - <modelVersion>4.0.0</modelVersion>
1.7 - <parent>
1.8 - <groupId>org.netbeans.html</groupId>
1.9 - <artifactId>pom</artifactId>
1.10 - <version>0.7-SNAPSHOT</version>
1.11 - </parent>
1.12 - <groupId>org.netbeans.html</groupId>
1.13 - <artifactId>ko-fx</artifactId>
1.14 - <version>0.7-SNAPSHOT</version>
1.15 - <packaging>bundle</packaging>
1.16 - <name>Knockout.fx</name>
1.17 - <url>http://maven.apache.org</url>
1.18 - <properties>
1.19 - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
1.20 - <bundleSymbolicName>org.netbeans.html.ko-fx</bundleSymbolicName>
1.21 - </properties>
1.22 - <build>
1.23 - <plugins>
1.24 - <plugin>
1.25 - <groupId>org.apache.felix</groupId>
1.26 - <artifactId>maven-bundle-plugin</artifactId>
1.27 - </plugin>
1.28 - <plugin>
1.29 - <groupId>org.apache.maven.plugins</groupId>
1.30 - <artifactId>maven-javadoc-plugin</artifactId>
1.31 - <configuration>
1.32 - <skip>false</skip>
1.33 - </configuration>
1.34 - </plugin>
1.35 - <plugin>
1.36 - <groupId>org.apache.maven.plugins</groupId>
1.37 - <artifactId>maven-compiler-plugin</artifactId>
1.38 - <version>2.3.2</version>
1.39 - <configuration>
1.40 - <source>1.7</source>
1.41 - <target>1.7</target>
1.42 - </configuration>
1.43 - </plugin>
1.44 - </plugins>
1.45 - </build>
1.46 - <dependencies>
1.47 - <dependency>
1.48 - <groupId>com.oracle</groupId>
1.49 - <artifactId>javafx</artifactId>
1.50 - <version>2.2</version>
1.51 - <scope>system</scope>
1.52 - <systemPath>${jfxrt.jar}</systemPath>
1.53 - </dependency>
1.54 - <dependency>
1.55 - <groupId>de.twentyeleven.skysail</groupId>
1.56 - <artifactId>org.json-osgi</artifactId>
1.57 - </dependency>
1.58 - <dependency>
1.59 - <groupId>org.netbeans.html</groupId>
1.60 - <artifactId>net.java.html.json</artifactId>
1.61 - <version>${project.version}</version>
1.62 - </dependency>
1.63 - <dependency>
1.64 - <groupId>org.testng</groupId>
1.65 - <artifactId>testng</artifactId>
1.66 - <scope>test</scope>
1.67 - </dependency>
1.68 - <dependency>
1.69 - <groupId>${project.groupId}</groupId>
1.70 - <artifactId>net.java.html.json.tck</artifactId>
1.71 - <version>${project.version}</version>
1.72 - <scope>test</scope>
1.73 - </dependency>
1.74 - <dependency>
1.75 - <groupId>org.netbeans.api</groupId>
1.76 - <artifactId>org-openide-util-lookup</artifactId>
1.77 - <scope>provided</scope>
1.78 - </dependency>
1.79 - <dependency>
1.80 - <groupId>org.netbeans.html</groupId>
1.81 - <artifactId>net.java.html.boot</artifactId>
1.82 - <version>${project.version}</version>
1.83 - <type>jar</type>
1.84 - </dependency>
1.85 - <dependency>
1.86 - <groupId>${project.groupId}</groupId>
1.87 - <artifactId>net.java.html.boot.fx</artifactId>
1.88 - <version>${project.version}</version>
1.89 - <scope>test</scope>
1.90 - </dependency>
1.91 - <dependency>
1.92 - <groupId>org.glassfish.grizzly</groupId>
1.93 - <artifactId>grizzly-http-server</artifactId>
1.94 - <version>2.3.3</version>
1.95 - <scope>test</scope>
1.96 - </dependency>
1.97 - <dependency>
1.98 - <groupId>org.glassfish.grizzly</groupId>
1.99 - <artifactId>grizzly-websockets-server</artifactId>
1.100 - <version>2.3.3</version>
1.101 - <scope>test</scope>
1.102 - <type>jar</type>
1.103 - </dependency>
1.104 - <dependency>
1.105 - <groupId>org.glassfish.grizzly</groupId>
1.106 - <artifactId>grizzly-http-servlet</artifactId>
1.107 - <version>2.3.3</version>
1.108 - <scope>test</scope>
1.109 - </dependency>
1.110 - <dependency>
1.111 - <groupId>javax.servlet</groupId>
1.112 - <artifactId>javax.servlet-api</artifactId>
1.113 - <scope>test</scope>
1.114 - <version>3.1.0</version>
1.115 - </dependency>
1.116 - </dependencies>
1.117 - <description>Binds net.java.html.json APIs together with JavaFX WebView.</description>
1.118 -</project>
2.1 --- a/ko-fx/src/main/java/org/netbeans/html/kofx/FXContext.java Thu Jan 09 11:53:46 2014 +0100
2.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
2.3 @@ -1,222 +0,0 @@
2.4 -/**
2.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2.6 - *
2.7 - * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
2.8 - *
2.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
2.10 - * Other names may be trademarks of their respective owners.
2.11 - *
2.12 - * The contents of this file are subject to the terms of either the GNU
2.13 - * General Public License Version 2 only ("GPL") or the Common
2.14 - * Development and Distribution License("CDDL") (collectively, the
2.15 - * "License"). You may not use this file except in compliance with the
2.16 - * License. You can obtain a copy of the License at
2.17 - * http://www.netbeans.org/cddl-gplv2.html
2.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
2.19 - * specific language governing permissions and limitations under the
2.20 - * License. When distributing the software, include this License Header
2.21 - * Notice in each file and include the License file at
2.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
2.23 - * particular file as subject to the "Classpath" exception as provided
2.24 - * by Oracle in the GPL Version 2 section of the License file that
2.25 - * accompanied this code. If applicable, add the following below the
2.26 - * License Header, with the fields enclosed by brackets [] replaced by
2.27 - * your own identifying information:
2.28 - * "Portions Copyrighted [year] [name of copyright owner]"
2.29 - *
2.30 - * Contributor(s):
2.31 - *
2.32 - * The Original Software is NetBeans. The Initial Developer of the Original
2.33 - * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
2.34 - *
2.35 - * If you wish your version of this file to be governed by only the CDDL
2.36 - * or only the GPL Version 2, indicate your decision by adding
2.37 - * "[Contributor] elects to include this software in this distribution
2.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
2.39 - * single choice of license, a recipient has the option to distribute
2.40 - * your version of this file under either the CDDL, the GPL Version 2 or
2.41 - * to extend the choice of license to its licensees as provided above.
2.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
2.43 - * Version 2 license, then the option applies only if the new code is
2.44 - * made subject to such option by the copyright holder.
2.45 - */
2.46 -package org.netbeans.html.kofx;
2.47 -
2.48 -import java.io.Closeable;
2.49 -import java.io.IOException;
2.50 -import java.io.InputStream;
2.51 -import java.util.ServiceLoader;
2.52 -import java.util.concurrent.Executor;
2.53 -import java.util.logging.Logger;
2.54 -import net.java.html.js.JavaScriptBody;
2.55 -import org.apidesign.html.boot.spi.Fn;
2.56 -import org.apidesign.html.context.spi.Contexts;
2.57 -import org.apidesign.html.json.spi.FunctionBinding;
2.58 -import org.apidesign.html.json.spi.JSONCall;
2.59 -import org.apidesign.html.json.spi.PropertyBinding;
2.60 -import org.apidesign.html.json.spi.Technology;
2.61 -import org.apidesign.html.json.spi.Transfer;
2.62 -import org.apidesign.html.json.spi.WSTransfer;
2.63 -import org.openide.util.lookup.ServiceProvider;
2.64 -
2.65 -/** This is an implementation package - just
2.66 - * include its JAR on classpath and use official {@link Context} API
2.67 - * to access the functionality.
2.68 - * <p>
2.69 - * Registers {@link ContextProvider}, so {@link ServiceLoader} can find it.
2.70 - *
2.71 - * @author Jaroslav Tulach <jtulach@netbeans.org>
2.72 - */
2.73 -public final class FXContext
2.74 -implements Technology.BatchInit<Object>, Transfer, WSTransfer<LoadWS> {
2.75 - static final Logger LOG = Logger.getLogger(FXContext.class.getName());
2.76 - private static Boolean javaScriptEnabled;
2.77 - private final Fn.Presenter browserContext;
2.78 -
2.79 - public FXContext(Fn.Presenter browserContext) {
2.80 - this.browserContext = browserContext;
2.81 - }
2.82 -
2.83 - @JavaScriptBody(args = {}, body = "return true;")
2.84 - private static boolean isJavaScriptEnabledJs() {
2.85 - return false;
2.86 - }
2.87 -
2.88 - static boolean isJavaScriptEnabled() {
2.89 - if (javaScriptEnabled != null) {
2.90 - return javaScriptEnabled;
2.91 - }
2.92 - return javaScriptEnabled = isJavaScriptEnabledJs();
2.93 - }
2.94 -
2.95 - final boolean areWebSocketsSupported() {
2.96 - return LoadWS.isSupported();
2.97 - }
2.98 -
2.99 -
2.100 - @Override
2.101 - public Object wrapModel(Object model, PropertyBinding[] propArr, FunctionBinding[] funcArr) {
2.102 - String[] propNames = new String[propArr.length];
2.103 - boolean[] propReadOnly = new boolean[propArr.length];
2.104 - Object[] propValues = new Object[propArr.length];
2.105 - for (int i = 0; i < propNames.length; i++) {
2.106 - propNames[i] = propArr[i].getPropertyName();
2.107 - propReadOnly[i] = propArr[i].isReadOnly();
2.108 - propValues[i] = propArr[i].getValue();
2.109 - }
2.110 - String[] funcNames = new String[funcArr.length];
2.111 - for (int i = 0; i < funcNames.length; i++) {
2.112 - funcNames[i] = funcArr[i].getFunctionName();
2.113 - }
2.114 - Object ret = Knockout.wrapModel(model,
2.115 - propNames, propReadOnly, propValues, propArr,
2.116 - funcNames, funcArr
2.117 - );
2.118 - return ret;
2.119 - }
2.120 -
2.121 - @Override
2.122 - public Object wrapModel(Object model) {
2.123 - throw new UnsupportedOperationException();
2.124 - }
2.125 -
2.126 - @Override
2.127 - public void bind(PropertyBinding b, Object model, Object data) {
2.128 - throw new UnsupportedOperationException();
2.129 - }
2.130 -
2.131 - @Override
2.132 - public void valueHasMutated(Object data, String propertyName) {
2.133 - Knockout.valueHasMutated(data, propertyName);
2.134 - }
2.135 -
2.136 - @Override
2.137 - public void expose(FunctionBinding fb, Object model, Object d) {
2.138 - throw new UnsupportedOperationException();
2.139 - }
2.140 -
2.141 - @Override
2.142 - public void applyBindings(Object data) {
2.143 - Knockout.applyBindings(data);
2.144 - }
2.145 -
2.146 - @Override
2.147 - public Object wrapArray(Object[] arr) {
2.148 - return arr;
2.149 - }
2.150 -
2.151 - @Override
2.152 - public void extract(Object obj, String[] props, Object[] values) {
2.153 - LoadJSON.extractJSON(obj, props, values);
2.154 - }
2.155 -
2.156 - @Override
2.157 - public void loadJSON(final JSONCall call) {
2.158 - LoadJSON.loadJSON(call);
2.159 - }
2.160 -
2.161 - @Override
2.162 - public <M> M toModel(Class<M> modelClass, Object data) {
2.163 - return modelClass.cast(Knockout.toModel(data));
2.164 - }
2.165 -
2.166 - @Override
2.167 - public Object toJSON(InputStream is) throws IOException {
2.168 - return LoadJSON.parse(is);
2.169 - }
2.170 -
2.171 - @Override
2.172 - public void runSafe(final Runnable r) {
2.173 - class Wrap implements Runnable {
2.174 - @Override public void run() {
2.175 - Closeable c = Fn.activate(browserContext);
2.176 - try {
2.177 - r.run();
2.178 - } finally {
2.179 - try {
2.180 - c.close();
2.181 - } catch (IOException ex) {
2.182 - // cannot be thrown
2.183 - }
2.184 - }
2.185 - }
2.186 - }
2.187 - Wrap w = new Wrap();
2.188 - if (browserContext instanceof Executor) {
2.189 - ((Executor)browserContext).execute(w);
2.190 - } else {
2.191 - w.run();
2.192 - }
2.193 - }
2.194 -
2.195 - @Override
2.196 - public LoadWS open(String url, JSONCall onReply) {
2.197 - return new LoadWS(onReply, url);
2.198 - }
2.199 -
2.200 - @Override
2.201 - public void send(LoadWS socket, JSONCall data) {
2.202 - socket.send(data);
2.203 - }
2.204 -
2.205 - @Override
2.206 - public void close(LoadWS socket) {
2.207 - socket.close();
2.208 - }
2.209 -
2.210 - @ServiceProvider(service = Contexts.Provider.class)
2.211 - public static final class Prvdr implements Contexts.Provider {
2.212 - @Override
2.213 - public void fillContext(Contexts.Builder context, Class<?> requestor) {
2.214 - if (isJavaScriptEnabled()) {
2.215 - FXContext c = new FXContext(Fn.activePresenter());
2.216 -
2.217 - context.register(Technology.class, c, 100);
2.218 - context.register(Transfer.class, c, 100);
2.219 - if (c.areWebSocketsSupported()) {
2.220 - context.register(WSTransfer.class, c, 100);
2.221 - }
2.222 - }
2.223 - }
2.224 - }
2.225 -}
3.1 --- a/ko-fx/src/main/java/org/netbeans/html/kofx/Knockout.java Thu Jan 09 11:53:46 2014 +0100
3.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
3.3 @@ -1,134 +0,0 @@
3.4 -/**
3.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3.6 - *
3.7 - * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
3.8 - *
3.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
3.10 - * Other names may be trademarks of their respective owners.
3.11 - *
3.12 - * The contents of this file are subject to the terms of either the GNU
3.13 - * General Public License Version 2 only ("GPL") or the Common
3.14 - * Development and Distribution License("CDDL") (collectively, the
3.15 - * "License"). You may not use this file except in compliance with the
3.16 - * License. You can obtain a copy of the License at
3.17 - * http://www.netbeans.org/cddl-gplv2.html
3.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
3.19 - * specific language governing permissions and limitations under the
3.20 - * License. When distributing the software, include this License Header
3.21 - * Notice in each file and include the License file at
3.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
3.23 - * particular file as subject to the "Classpath" exception as provided
3.24 - * by Oracle in the GPL Version 2 section of the License file that
3.25 - * accompanied this code. If applicable, add the following below the
3.26 - * License Header, with the fields enclosed by brackets [] replaced by
3.27 - * your own identifying information:
3.28 - * "Portions Copyrighted [year] [name of copyright owner]"
3.29 - *
3.30 - * Contributor(s):
3.31 - *
3.32 - * The Original Software is NetBeans. The Initial Developer of the Original
3.33 - * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
3.34 - *
3.35 - * If you wish your version of this file to be governed by only the CDDL
3.36 - * or only the GPL Version 2, indicate your decision by adding
3.37 - * "[Contributor] elects to include this software in this distribution
3.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
3.39 - * single choice of license, a recipient has the option to distribute
3.40 - * your version of this file under either the CDDL, the GPL Version 2 or
3.41 - * to extend the choice of license to its licensees as provided above.
3.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
3.43 - * Version 2 license, then the option applies only if the new code is
3.44 - * made subject to such option by the copyright holder.
3.45 - */
3.46 -package org.netbeans.html.kofx;
3.47 -
3.48 -import net.java.html.js.JavaScriptBody;
3.49 -import net.java.html.js.JavaScriptResource;
3.50 -import net.java.html.json.Model;
3.51 -import org.apidesign.html.json.spi.FunctionBinding;
3.52 -import org.apidesign.html.json.spi.PropertyBinding;
3.53 -
3.54 -/** This is an implementation package - just
3.55 - * include its JAR on classpath and use official {@link Context} API
3.56 - * to access the functionality.
3.57 - * <p>
3.58 - * Provides binding between {@link Model models} and knockout.js running
3.59 - * inside a JavaFX WebView.
3.60 - *
3.61 - * @author Jaroslav Tulach <jtulach@netbeans.org>
3.62 - */
3.63 -@JavaScriptResource("knockout-2.2.1.js")
3.64 -final class Knockout {
3.65 - static {
3.66 - loadKnockout();
3.67 - }
3.68 -
3.69 - @JavaScriptBody(args = { }, body = "")
3.70 - private static native void loadKnockout();
3.71 -
3.72 - @JavaScriptBody(args = { "model", "prop" }, body =
3.73 - "if (model) {\n"
3.74 - + " var koProp = model[prop];\n"
3.75 - + " if (koProp && koProp['valueHasMutated']) {\n"
3.76 - + " koProp['valueHasMutated']();\n"
3.77 - + " }\n"
3.78 - + "}\n"
3.79 - )
3.80 - public native static void valueHasMutated(Object model, String prop);
3.81 -
3.82 - @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);\n")
3.83 - native static void applyBindings(Object bindings);
3.84 -
3.85 - @JavaScriptBody(
3.86 - javacall = true,
3.87 - args = {"model", "propNames", "propReadOnly", "propValues", "propArr", "funcNames", "funcArr"},
3.88 - body
3.89 - = "var ret = {};\n"
3.90 - + "ret['ko-fx.model'] = model;\n"
3.91 - + "function koComputed(name, readOnly, value, prop) {\n"
3.92 - + " function realGetter() {\n"
3.93 - + " try {\n"
3.94 - + " var v = prop.@org.apidesign.html.json.spi.PropertyBinding::getValue()();\n"
3.95 - + " return v;\n"
3.96 - + " } catch (e) {\n"
3.97 - + " alert(\"Cannot call getValue on \" + model + \" prop: \" + name + \" error: \" + e);\n"
3.98 - + " }\n"
3.99 - + " }\n"
3.100 - + " var activeGetter = function() { return value; };\n"
3.101 - + " var bnd = {\n"
3.102 - + " read: function() {\n"
3.103 - + " var r = activeGetter();\n"
3.104 - + " activeGetter = realGetter;\n"
3.105 - + " return r == null ? null : r.valueOf();\n"
3.106 - + " },\n"
3.107 - + " owner: ret\n"
3.108 - + " };\n"
3.109 - + " if (!readOnly) {\n"
3.110 - + " bnd.write = function(val) {\n"
3.111 - + " prop.@org.apidesign.html.json.spi.PropertyBinding::setValue(Ljava/lang/Object;)(val);\n"
3.112 - + " };\n"
3.113 - + " };\n"
3.114 - + " ret[name] = ko.computed(bnd);\n"
3.115 - + "}\n"
3.116 - + "for (var i = 0; i < propNames.length; i++) {\n"
3.117 - + " koComputed(propNames[i], propReadOnly[i], propValues[i], propArr[i]);\n"
3.118 - + "}\n"
3.119 - + "function koExpose(name, func) {\n"
3.120 - + " ret[name] = function(data, ev) {\n"
3.121 - + " func.@org.apidesign.html.json.spi.FunctionBinding::call(Ljava/lang/Object;Ljava/lang/Object;)(data, ev);\n"
3.122 - + " };\n"
3.123 - + "}\n"
3.124 - + "for (var i = 0; i < funcNames.length; i++) {\n"
3.125 - + " koExpose(funcNames[i], funcArr[i]);\n"
3.126 - + "}\n"
3.127 - + "return ret;\n"
3.128 - )
3.129 - static native Object wrapModel(
3.130 - Object model,
3.131 - String[] propNames, boolean[] propReadOnly, Object propValues, PropertyBinding[] propArr,
3.132 - String[] funcNames, FunctionBinding[] funcArr
3.133 - );
3.134 -
3.135 - @JavaScriptBody(args = { "o" }, body = "return o['ko-fx.model'] ? o['ko-fx.model'] : o;")
3.136 - static native Object toModel(Object wrapper);
3.137 -}
4.1 --- a/ko-fx/src/main/java/org/netbeans/html/kofx/LoadJSON.java Thu Jan 09 11:53:46 2014 +0100
4.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
4.3 @@ -1,267 +0,0 @@
4.4 -/**
4.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4.6 - *
4.7 - * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
4.8 - *
4.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
4.10 - * Other names may be trademarks of their respective owners.
4.11 - *
4.12 - * The contents of this file are subject to the terms of either the GNU
4.13 - * General Public License Version 2 only ("GPL") or the Common
4.14 - * Development and Distribution License("CDDL") (collectively, the
4.15 - * "License"). You may not use this file except in compliance with the
4.16 - * License. You can obtain a copy of the License at
4.17 - * http://www.netbeans.org/cddl-gplv2.html
4.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
4.19 - * specific language governing permissions and limitations under the
4.20 - * License. When distributing the software, include this License Header
4.21 - * Notice in each file and include the License file at
4.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
4.23 - * particular file as subject to the "Classpath" exception as provided
4.24 - * by Oracle in the GPL Version 2 section of the License file that
4.25 - * accompanied this code. If applicable, add the following below the
4.26 - * License Header, with the fields enclosed by brackets [] replaced by
4.27 - * your own identifying information:
4.28 - * "Portions Copyrighted [year] [name of copyright owner]"
4.29 - *
4.30 - * Contributor(s):
4.31 - *
4.32 - * The Original Software is NetBeans. The Initial Developer of the Original
4.33 - * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
4.34 - *
4.35 - * If you wish your version of this file to be governed by only the CDDL
4.36 - * or only the GPL Version 2, indicate your decision by adding
4.37 - * "[Contributor] elects to include this software in this distribution
4.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
4.39 - * single choice of license, a recipient has the option to distribute
4.40 - * your version of this file under either the CDDL, the GPL Version 2 or
4.41 - * to extend the choice of license to its licensees as provided above.
4.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
4.43 - * Version 2 license, then the option applies only if the new code is
4.44 - * made subject to such option by the copyright holder.
4.45 - */
4.46 -package org.netbeans.html.kofx;
4.47 -
4.48 -import java.io.IOException;
4.49 -import java.io.InputStream;
4.50 -import java.io.InputStreamReader;
4.51 -import java.io.OutputStream;
4.52 -import java.io.PushbackInputStream;
4.53 -import java.io.Reader;
4.54 -import java.net.HttpURLConnection;
4.55 -import java.net.MalformedURLException;
4.56 -import java.net.URL;
4.57 -import java.net.URLConnection;
4.58 -import java.util.Iterator;
4.59 -import java.util.concurrent.Executor;
4.60 -import java.util.concurrent.Executors;
4.61 -import java.util.concurrent.ThreadFactory;
4.62 -import java.util.logging.Level;
4.63 -import java.util.logging.Logger;
4.64 -import javafx.application.Platform;
4.65 -import net.java.html.js.JavaScriptBody;
4.66 -import netscape.javascript.JSObject;
4.67 -import org.apidesign.html.json.spi.JSONCall;
4.68 -import org.json.JSONArray;
4.69 -import org.json.JSONException;
4.70 -import org.json.JSONObject;
4.71 -import org.json.JSONTokener;
4.72 -
4.73 -/** This is an implementation package - just
4.74 - * include its JAR on classpath and use official {@link Context} API
4.75 - * to access the functionality.
4.76 - *
4.77 - * @author Jaroslav Tulach <jtulach@netbeans.org>
4.78 - */
4.79 -final class LoadJSON implements Runnable {
4.80 - private static final Logger LOG = FXContext.LOG;
4.81 - private static final Executor REQ = Executors.newCachedThreadPool(new ThreadFactory() {
4.82 - @Override
4.83 - public Thread newThread(Runnable runnable) {
4.84 - Thread thread = Executors.defaultThreadFactory().newThread(runnable);
4.85 - thread.setDaemon(true);
4.86 - return thread;
4.87 - }
4.88 - });
4.89 -
4.90 - private final JSONCall call;
4.91 - private final URL base;
4.92 - private Throwable error;
4.93 - private Object json;
4.94 -
4.95 -
4.96 - private LoadJSON(JSONCall call) {
4.97 - this.call = call;
4.98 - URL b;
4.99 - try {
4.100 - b = new URL(findBaseURL());
4.101 - } catch (MalformedURLException ex) {
4.102 - LOG.log(Level.SEVERE, "Can't find base url for " + call.composeURL("dummy"), ex);
4.103 - b = null;
4.104 - }
4.105 - this.base = b;
4.106 - }
4.107 -
4.108 - public static void loadJSON(JSONCall call) {
4.109 - assert !"WebSocket".equals(call.getMethod());
4.110 - REQ.execute(new LoadJSON((call)));
4.111 - }
4.112 -
4.113 - @Override
4.114 - public void run() {
4.115 - if (Platform.isFxApplicationThread()) {
4.116 - if (error != null) {
4.117 - call.notifyError(error);
4.118 - } else {
4.119 - call.notifySuccess(json);
4.120 - }
4.121 - return;
4.122 - }
4.123 - final String url;
4.124 - if (call.isJSONP()) {
4.125 - url = call.composeURL("dummy");
4.126 - } else {
4.127 - url = call.composeURL(null);
4.128 - }
4.129 - try {
4.130 - final URL u = new URL(base, url.replace(" ", "%20"));
4.131 - URLConnection conn = u.openConnection();
4.132 - if (conn instanceof HttpURLConnection) {
4.133 - HttpURLConnection huc = (HttpURLConnection) conn;
4.134 - if (call.getMethod() != null) {
4.135 - huc.setRequestMethod(call.getMethod());
4.136 - }
4.137 - if (call.isDoOutput()) {
4.138 - huc.setDoOutput(true);
4.139 - final OutputStream os = huc.getOutputStream();
4.140 - call.writeData(os);
4.141 - os.flush();
4.142 - }
4.143 - }
4.144 - final PushbackInputStream is = new PushbackInputStream(
4.145 - conn.getInputStream(), 1
4.146 - );
4.147 - boolean array = false;
4.148 - boolean string = false;
4.149 - if (call.isJSONP()) {
4.150 - for (;;) {
4.151 - int ch = is.read();
4.152 - if (ch == -1) {
4.153 - break;
4.154 - }
4.155 - if (ch == '[') {
4.156 - is.unread(ch);
4.157 - array = true;
4.158 - break;
4.159 - }
4.160 - if (ch == '{') {
4.161 - is.unread(ch);
4.162 - break;
4.163 - }
4.164 - }
4.165 - } else {
4.166 - int ch = is.read();
4.167 - if (ch == -1) {
4.168 - string = true;
4.169 - } else {
4.170 - array = ch == '[';
4.171 - is.unread(ch);
4.172 - if (!array && ch != '{') {
4.173 - string = true;
4.174 - }
4.175 - }
4.176 - }
4.177 - try {
4.178 - if (string) {
4.179 - throw new JSONException("");
4.180 - }
4.181 - Reader r = new InputStreamReader(is, "UTF-8");
4.182 -
4.183 - JSONTokener tok = new JSONTokener(r);
4.184 - Object obj;
4.185 - obj = array ? new JSONArray(tok) : new JSONObject(tok);
4.186 - json = convertToArray(obj);
4.187 - } catch (JSONException ex) {
4.188 - Reader r = new InputStreamReader(is, "UTF-8");
4.189 - StringBuilder sb = new StringBuilder();
4.190 - for (;;) {
4.191 - int ch = r.read();
4.192 - if (ch == -1) {
4.193 - break;
4.194 - }
4.195 - sb.append((char)ch);
4.196 - }
4.197 - json = sb.toString();
4.198 - }
4.199 - } catch (IOException ex) {
4.200 - error = ex;
4.201 - } finally {
4.202 - Platform.runLater(this);
4.203 - }
4.204 - }
4.205 -
4.206 - static Object convertToArray(Object o) throws JSONException {
4.207 - if (o instanceof JSONArray) {
4.208 - JSONArray ja = (JSONArray)o;
4.209 - Object[] arr = new Object[ja.length()];
4.210 - for (int i = 0; i < arr.length; i++) {
4.211 - arr[i] = convertToArray(ja.get(i));
4.212 - }
4.213 - return arr;
4.214 - } else if (o instanceof JSONObject) {
4.215 - JSONObject obj = (JSONObject)o;
4.216 - Iterator it = obj.keys();
4.217 - while (it.hasNext()) {
4.218 - String key = (String)it.next();
4.219 - obj.put(key, convertToArray(obj.get(key)));
4.220 - }
4.221 - return obj;
4.222 - } else {
4.223 - return o;
4.224 - }
4.225 - }
4.226 -
4.227 - public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
4.228 - if (jsonObject instanceof JSONObject) {
4.229 - JSONObject obj = (JSONObject)jsonObject;
4.230 - for (int i = 0; i < props.length; i++) {
4.231 - try {
4.232 - values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
4.233 - } catch (JSONException ex) {
4.234 - LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
4.235 - }
4.236 - }
4.237 - }
4.238 - if (jsonObject instanceof JSObject) {
4.239 - JSObject obj = (JSObject)jsonObject;
4.240 - for (int i = 0; i < props.length; i++) {
4.241 - Object val = obj.getMember(props[i]);
4.242 - values[i] = isDefined(val) ? val : null;
4.243 - }
4.244 - }
4.245 - }
4.246 -
4.247 - public static Object parse(InputStream is) throws IOException {
4.248 - try {
4.249 - InputStreamReader r = new InputStreamReader(is, "UTF-8");
4.250 - JSONTokener t = new JSONTokener(r);
4.251 - return new JSONObject(t);
4.252 - } catch (JSONException ex) {
4.253 - throw new IOException(ex);
4.254 - }
4.255 - }
4.256 -
4.257 - @JavaScriptBody(args = { }, body =
4.258 - "var h;"
4.259 - + "if (!!window && !!window.location && !!window.location.href)\n"
4.260 - + " h = window.location.href;\n"
4.261 - + "else "
4.262 - + " h = null;"
4.263 - + "return h;\n"
4.264 - )
4.265 - private static native String findBaseURL();
4.266 -
4.267 - private static boolean isDefined(Object val) {
4.268 - return !"undefined".equals(val);
4.269 - }
4.270 -}
5.1 --- a/ko-fx/src/main/java/org/netbeans/html/kofx/LoadWS.java Thu Jan 09 11:53:46 2014 +0100
5.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
5.3 @@ -1,149 +0,0 @@
5.4 -/**
5.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
5.6 - *
5.7 - * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
5.8 - *
5.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
5.10 - * Other names may be trademarks of their respective owners.
5.11 - *
5.12 - * The contents of this file are subject to the terms of either the GNU
5.13 - * General Public License Version 2 only ("GPL") or the Common
5.14 - * Development and Distribution License("CDDL") (collectively, the
5.15 - * "License"). You may not use this file except in compliance with the
5.16 - * License. You can obtain a copy of the License at
5.17 - * http://www.netbeans.org/cddl-gplv2.html
5.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
5.19 - * specific language governing permissions and limitations under the
5.20 - * License. When distributing the software, include this License Header
5.21 - * Notice in each file and include the License file at
5.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
5.23 - * particular file as subject to the "Classpath" exception as provided
5.24 - * by Oracle in the GPL Version 2 section of the License file that
5.25 - * accompanied this code. If applicable, add the following below the
5.26 - * License Header, with the fields enclosed by brackets [] replaced by
5.27 - * your own identifying information:
5.28 - * "Portions Copyrighted [year] [name of copyright owner]"
5.29 - *
5.30 - * Contributor(s):
5.31 - *
5.32 - * The Original Software is NetBeans. The Initial Developer of the Original
5.33 - * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
5.34 - *
5.35 - * If you wish your version of this file to be governed by only the CDDL
5.36 - * or only the GPL Version 2, indicate your decision by adding
5.37 - * "[Contributor] elects to include this software in this distribution
5.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
5.39 - * single choice of license, a recipient has the option to distribute
5.40 - * your version of this file under either the CDDL, the GPL Version 2 or
5.41 - * to extend the choice of license to its licensees as provided above.
5.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
5.43 - * Version 2 license, then the option applies only if the new code is
5.44 - * made subject to such option by the copyright holder.
5.45 - */
5.46 -package org.netbeans.html.kofx;
5.47 -
5.48 -import net.java.html.js.JavaScriptBody;
5.49 -import org.apidesign.html.json.spi.JSONCall;
5.50 -import org.json.JSONArray;
5.51 -import org.json.JSONException;
5.52 -import org.json.JSONObject;
5.53 -import org.json.JSONTokener;
5.54 -
5.55 -/** Communication with WebSockets for WebView 1.8.
5.56 - *
5.57 - * @author Jaroslav Tulach <jtulach@netbeans.org>
5.58 - */
5.59 -final class LoadWS {
5.60 - private static final boolean SUPPORTED = isWebSocket();
5.61 - private final Object ws;
5.62 - private final JSONCall call;
5.63 -
5.64 - LoadWS(JSONCall first, String url) {
5.65 - call = first;
5.66 - ws = initWebSocket(this, url);
5.67 - if (ws == null) {
5.68 - first.notifyError(new IllegalArgumentException("Wrong URL: " + url));
5.69 - }
5.70 - }
5.71 -
5.72 - static boolean isSupported() {
5.73 - return SUPPORTED;
5.74 - }
5.75 -
5.76 - void send(JSONCall call) {
5.77 - push(call);
5.78 - }
5.79 -
5.80 - private synchronized void push(JSONCall call) {
5.81 - send(ws, call.getMessage());
5.82 - }
5.83 -
5.84 - void onOpen(Object ev) {
5.85 - if (!call.isDoOutput()) {
5.86 - call.notifySuccess(null);
5.87 - }
5.88 - }
5.89 -
5.90 - void onMessage(Object ev, String data) {
5.91 - Object json;
5.92 - try {
5.93 - data = data.trim();
5.94 -
5.95 - JSONTokener tok = new JSONTokener(data);
5.96 - Object obj;
5.97 - obj = data.startsWith("[") ? new JSONArray(tok) : new JSONObject(tok);
5.98 - json = LoadJSON.convertToArray(obj);
5.99 - } catch (JSONException ex) {
5.100 - json = data;
5.101 - }
5.102 - call.notifySuccess(json);
5.103 - }
5.104 -
5.105 - void onError(Object ev) {
5.106 - call.notifyError(new Exception(ev.toString()));
5.107 - }
5.108 -
5.109 - void onClose(boolean wasClean, int code, String reason) {
5.110 - call.notifyError(null);
5.111 - }
5.112 -
5.113 - @JavaScriptBody(args = {}, body = "if (window.WebSocket) return true; else return false;")
5.114 - private static boolean isWebSocket() {
5.115 - return false;
5.116 - }
5.117 -
5.118 - @JavaScriptBody(args = { "back", "url" }, javacall = true, body = ""
5.119 - + "if (window.WebSocket) {"
5.120 - + " try {"
5.121 - + " var ws = new window.WebSocket(url);"
5.122 - + " ws.onopen = function(ev) { back.@org.netbeans.html.kofx.LoadWS::onOpen(Ljava/lang/Object;)(ev); };"
5.123 - + " ws.onmessage = function(ev) { back.@org.netbeans.html.kofx.LoadWS::onMessage(Ljava/lang/Object;Ljava/lang/String;)(ev, ev.data); };"
5.124 - + " ws.onerror = function(ev) { back.@org.netbeans.html.kofx.LoadWS::onError(Ljava/lang/Object;)(ev); };"
5.125 - + " ws.onclose = function(ev) { back.@org.netbeans.html.kofx.LoadWS::onClose(ZILjava/lang/String;)(ev.wasClean, ev.code, ev.reason); };"
5.126 - + " return ws;"
5.127 - + " } catch (ex) {"
5.128 - + " return null;"
5.129 - + " }"
5.130 - + "} else {"
5.131 - + " return null;"
5.132 - + "}"
5.133 - )
5.134 - private static Object initWebSocket(Object back, String url) {
5.135 - return null;
5.136 - }
5.137 -
5.138 -
5.139 - @JavaScriptBody(args = { "ws", "msg" }, body = ""
5.140 - + "ws.send(msg);"
5.141 - )
5.142 - private void send(Object ws, String msg) {
5.143 - }
5.144 -
5.145 - @JavaScriptBody(args = { "ws" }, body = "ws.close();")
5.146 - private static void close(Object ws) {
5.147 - }
5.148 -
5.149 - void close() {
5.150 - close(ws);
5.151 - }
5.152 -}
6.1 --- a/ko-fx/src/main/resources/org/netbeans/html/kofx/knockout-2.2.1.js Thu Jan 09 11:53:46 2014 +0100
6.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
6.3 @@ -1,3594 +0,0 @@
6.4 -// Knockout JavaScript library v2.2.1
6.5 -// (c) Steven Sanderson - http://knockoutjs.com/
6.6 -// License: MIT (http://www.opensource.org/licenses/mit-license.php)
6.7 -
6.8 -(function(){
6.9 -var DEBUG=true;
6.10 -(function(window,document,navigator,jQuery,undefined){
6.11 -!function(factory) {
6.12 - // Support three module loading scenarios
6.13 - if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
6.14 - // [1] CommonJS/Node.js
6.15 - var target = module['exports'] || exports; // module.exports is for Node.js
6.16 - factory(target);
6.17 - } else if (typeof define === 'function' && define['amd']) {
6.18 - // [2] AMD anonymous module
6.19 - define(['exports'], factory);
6.20 - } else {
6.21 - // [3] No module loader (plain <script> tag) - put directly in global namespace
6.22 - factory(window['ko'] = {});
6.23 - }
6.24 -}(function(koExports){
6.25 -// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
6.26 -// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
6.27 -var ko = typeof koExports !== 'undefined' ? koExports : {};
6.28 -// Google Closure Compiler helpers (used only to make the minified file smaller)
6.29 -ko.exportSymbol = function(koPath, object) {
6.30 - var tokens = koPath.split(".");
6.31 -
6.32 - // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
6.33 - // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
6.34 - var target = ko;
6.35 -
6.36 - for (var i = 0; i < tokens.length - 1; i++)
6.37 - target = target[tokens[i]];
6.38 - target[tokens[tokens.length - 1]] = object;
6.39 -};
6.40 -ko.exportProperty = function(owner, publicName, object) {
6.41 - owner[publicName] = object;
6.42 -};
6.43 -ko.version = "2.2.1";
6.44 -
6.45 -ko.exportSymbol('version', ko.version);
6.46 -ko.utils = new (function () {
6.47 - var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
6.48 -
6.49 - // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
6.50 - var knownEvents = {}, knownEventTypesByEventName = {};
6.51 - var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
6.52 - knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
6.53 - knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
6.54 - for (var eventType in knownEvents) {
6.55 - var knownEventsForType = knownEvents[eventType];
6.56 - if (knownEventsForType.length) {
6.57 - for (var i = 0, j = knownEventsForType.length; i < j; i++)
6.58 - knownEventTypesByEventName[knownEventsForType[i]] = eventType;
6.59 - }
6.60 - }
6.61 - var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
6.62 -
6.63 - // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
6.64 - // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
6.65 - // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
6.66 - // If there is a future need to detect specific versions of IE10+, we will amend this.
6.67 - var ieVersion = (function() {
6.68 - var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
6.69 -
6.70 - // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
6.71 - while (
6.72 - div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
6.73 - iElems[0]
6.74 - );
6.75 - return version > 4 ? version : undefined;
6.76 - }());
6.77 - var isIe6 = ieVersion === 6,
6.78 - isIe7 = ieVersion === 7;
6.79 -
6.80 - function isClickOnCheckableElement(element, eventType) {
6.81 - if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
6.82 - if (eventType.toLowerCase() != "click") return false;
6.83 - var inputType = element.type;
6.84 - return (inputType == "checkbox") || (inputType == "radio");
6.85 - }
6.86 -
6.87 - return {
6.88 - fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
6.89 -
6.90 - arrayForEach: function (array, action) {
6.91 - for (var i = 0, j = array.length; i < j; i++)
6.92 - action(array[i]);
6.93 - },
6.94 -
6.95 - arrayIndexOf: function (array, item) {
6.96 - if (typeof Array.prototype.indexOf == "function")
6.97 - return Array.prototype.indexOf.call(array, item);
6.98 - for (var i = 0, j = array.length; i < j; i++)
6.99 - if (array[i] === item)
6.100 - return i;
6.101 - return -1;
6.102 - },
6.103 -
6.104 - arrayFirst: function (array, predicate, predicateOwner) {
6.105 - for (var i = 0, j = array.length; i < j; i++)
6.106 - if (predicate.call(predicateOwner, array[i]))
6.107 - return array[i];
6.108 - return null;
6.109 - },
6.110 -
6.111 - arrayRemoveItem: function (array, itemToRemove) {
6.112 - var index = ko.utils.arrayIndexOf(array, itemToRemove);
6.113 - if (index >= 0)
6.114 - array.splice(index, 1);
6.115 - },
6.116 -
6.117 - arrayGetDistinctValues: function (array) {
6.118 - array = array || [];
6.119 - var result = [];
6.120 - for (var i = 0, j = array.length; i < j; i++) {
6.121 - if (ko.utils.arrayIndexOf(result, array[i]) < 0)
6.122 - result.push(array[i]);
6.123 - }
6.124 - return result;
6.125 - },
6.126 -
6.127 - arrayMap: function (array, mapping) {
6.128 - array = array || [];
6.129 - var result = [];
6.130 - for (var i = 0, j = array.length; i < j; i++)
6.131 - result.push(mapping(array[i]));
6.132 - return result;
6.133 - },
6.134 -
6.135 - arrayFilter: function (array, predicate) {
6.136 - array = array || [];
6.137 - var result = [];
6.138 - for (var i = 0, j = array.length; i < j; i++)
6.139 - if (predicate(array[i]))
6.140 - result.push(array[i]);
6.141 - return result;
6.142 - },
6.143 -
6.144 - arrayPushAll: function (array, valuesToPush) {
6.145 - if (valuesToPush instanceof Array)
6.146 - array.push.apply(array, valuesToPush);
6.147 - else
6.148 - for (var i = 0, j = valuesToPush.length; i < j; i++)
6.149 - array.push(valuesToPush[i]);
6.150 - return array;
6.151 - },
6.152 -
6.153 - extend: function (target, source) {
6.154 - if (source) {
6.155 - for(var prop in source) {
6.156 - if(source.hasOwnProperty(prop)) {
6.157 - target[prop] = source[prop];
6.158 - }
6.159 - }
6.160 - }
6.161 - return target;
6.162 - },
6.163 -
6.164 - emptyDomNode: function (domNode) {
6.165 - while (domNode.firstChild) {
6.166 - ko.removeNode(domNode.firstChild);
6.167 - }
6.168 - },
6.169 -
6.170 - moveCleanedNodesToContainerElement: function(nodes) {
6.171 - // Ensure it's a real array, as we're about to reparent the nodes and
6.172 - // we don't want the underlying collection to change while we're doing that.
6.173 - var nodesArray = ko.utils.makeArray(nodes);
6.174 -
6.175 - var container = document.createElement('div');
6.176 - for (var i = 0, j = nodesArray.length; i < j; i++) {
6.177 - container.appendChild(ko.cleanNode(nodesArray[i]));
6.178 - }
6.179 - return container;
6.180 - },
6.181 -
6.182 - cloneNodes: function (nodesArray, shouldCleanNodes) {
6.183 - for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
6.184 - var clonedNode = nodesArray[i].cloneNode(true);
6.185 - newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
6.186 - }
6.187 - return newNodesArray;
6.188 - },
6.189 -
6.190 - setDomNodeChildren: function (domNode, childNodes) {
6.191 - ko.utils.emptyDomNode(domNode);
6.192 - if (childNodes) {
6.193 - for (var i = 0, j = childNodes.length; i < j; i++)
6.194 - domNode.appendChild(childNodes[i]);
6.195 - }
6.196 - },
6.197 -
6.198 - replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
6.199 - var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
6.200 - if (nodesToReplaceArray.length > 0) {
6.201 - var insertionPoint = nodesToReplaceArray[0];
6.202 - var parent = insertionPoint.parentNode;
6.203 - for (var i = 0, j = newNodesArray.length; i < j; i++)
6.204 - parent.insertBefore(newNodesArray[i], insertionPoint);
6.205 - for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
6.206 - ko.removeNode(nodesToReplaceArray[i]);
6.207 - }
6.208 - }
6.209 - },
6.210 -
6.211 - setOptionNodeSelectionState: function (optionNode, isSelected) {
6.212 - // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
6.213 - if (ieVersion < 7)
6.214 - optionNode.setAttribute("selected", isSelected);
6.215 - else
6.216 - optionNode.selected = isSelected;
6.217 - },
6.218 -
6.219 - stringTrim: function (string) {
6.220 - return (string || "").replace(stringTrimRegex, "");
6.221 - },
6.222 -
6.223 - stringTokenize: function (string, delimiter) {
6.224 - var result = [];
6.225 - var tokens = (string || "").split(delimiter);
6.226 - for (var i = 0, j = tokens.length; i < j; i++) {
6.227 - var trimmed = ko.utils.stringTrim(tokens[i]);
6.228 - if (trimmed !== "")
6.229 - result.push(trimmed);
6.230 - }
6.231 - return result;
6.232 - },
6.233 -
6.234 - stringStartsWith: function (string, startsWith) {
6.235 - string = string || "";
6.236 - if (startsWith.length > string.length)
6.237 - return false;
6.238 - return string.substring(0, startsWith.length) === startsWith;
6.239 - },
6.240 -
6.241 - domNodeIsContainedBy: function (node, containedByNode) {
6.242 - if (containedByNode.compareDocumentPosition)
6.243 - return (containedByNode.compareDocumentPosition(node) & 16) == 16;
6.244 - while (node != null) {
6.245 - if (node == containedByNode)
6.246 - return true;
6.247 - node = node.parentNode;
6.248 - }
6.249 - return false;
6.250 - },
6.251 -
6.252 - domNodeIsAttachedToDocument: function (node) {
6.253 - return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
6.254 - },
6.255 -
6.256 - tagNameLower: function(element) {
6.257 - // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
6.258 - // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
6.259 - // we don't need to do the .toLowerCase() as it will always be lower case anyway.
6.260 - return element && element.tagName && element.tagName.toLowerCase();
6.261 - },
6.262 -
6.263 - registerEventHandler: function (element, eventType, handler) {
6.264 - var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
6.265 - if (!mustUseAttachEvent && typeof jQuery != "undefined") {
6.266 - if (isClickOnCheckableElement(element, eventType)) {
6.267 - // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
6.268 - // it toggles the element checked state *after* the click event handlers run, whereas native
6.269 - // click events toggle the checked state *before* the event handler.
6.270 - // Fix this by intecepting the handler and applying the correct checkedness before it runs.
6.271 - var originalHandler = handler;
6.272 - handler = function(event, eventData) {
6.273 - var jQuerySuppliedCheckedState = this.checked;
6.274 - if (eventData)
6.275 - this.checked = eventData.checkedStateBeforeEvent !== true;
6.276 - originalHandler.call(this, event);
6.277 - this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
6.278 - };
6.279 - }
6.280 - jQuery(element)['bind'](eventType, handler);
6.281 - } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
6.282 - element.addEventListener(eventType, handler, false);
6.283 - else if (typeof element.attachEvent != "undefined")
6.284 - element.attachEvent("on" + eventType, function (event) {
6.285 - handler.call(element, event);
6.286 - });
6.287 - else
6.288 - throw new Error("Browser doesn't support addEventListener or attachEvent");
6.289 - },
6.290 -
6.291 - triggerEvent: function (element, eventType) {
6.292 - if (!(element && element.nodeType))
6.293 - throw new Error("element must be a DOM node when calling triggerEvent");
6.294 -
6.295 - if (typeof jQuery != "undefined") {
6.296 - var eventData = [];
6.297 - if (isClickOnCheckableElement(element, eventType)) {
6.298 - // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
6.299 - eventData.push({ checkedStateBeforeEvent: element.checked });
6.300 - }
6.301 - jQuery(element)['trigger'](eventType, eventData);
6.302 - } else if (typeof document.createEvent == "function") {
6.303 - if (typeof element.dispatchEvent == "function") {
6.304 - var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
6.305 - var event = document.createEvent(eventCategory);
6.306 - event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
6.307 - element.dispatchEvent(event);
6.308 - }
6.309 - else
6.310 - throw new Error("The supplied element doesn't support dispatchEvent");
6.311 - } else if (typeof element.fireEvent != "undefined") {
6.312 - // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
6.313 - // so to make it consistent, we'll do it manually here
6.314 - if (isClickOnCheckableElement(element, eventType))
6.315 - element.checked = element.checked !== true;
6.316 - element.fireEvent("on" + eventType);
6.317 - }
6.318 - else
6.319 - throw new Error("Browser doesn't support triggering events");
6.320 - },
6.321 -
6.322 - unwrapObservable: function (value) {
6.323 - return ko.isObservable(value) ? value() : value;
6.324 - },
6.325 -
6.326 - peekObservable: function (value) {
6.327 - return ko.isObservable(value) ? value.peek() : value;
6.328 - },
6.329 -
6.330 - toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
6.331 - if (classNames) {
6.332 - var cssClassNameRegex = /[\w-]+/g,
6.333 - currentClassNames = node.className.match(cssClassNameRegex) || [];
6.334 - ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
6.335 - var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
6.336 - if (indexOfClass >= 0) {
6.337 - if (!shouldHaveClass)
6.338 - currentClassNames.splice(indexOfClass, 1);
6.339 - } else {
6.340 - if (shouldHaveClass)
6.341 - currentClassNames.push(className);
6.342 - }
6.343 - });
6.344 - node.className = currentClassNames.join(" ");
6.345 - }
6.346 - },
6.347 -
6.348 - setTextContent: function(element, textContent) {
6.349 - var value = ko.utils.unwrapObservable(textContent);
6.350 - if ((value === null) || (value === undefined))
6.351 - value = "";
6.352 -
6.353 - if (element.nodeType === 3) {
6.354 - element.data = value;
6.355 - } else {
6.356 - // We need there to be exactly one child: a text node.
6.357 - // If there are no children, more than one, or if it's not a text node,
6.358 - // we'll clear everything and create a single text node.
6.359 - var innerTextNode = ko.virtualElements.firstChild(element);
6.360 - if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
6.361 - ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
6.362 - } else {
6.363 - innerTextNode.data = value;
6.364 - }
6.365 -
6.366 - ko.utils.forceRefresh(element);
6.367 - }
6.368 - },
6.369 -
6.370 - setElementName: function(element, name) {
6.371 - element.name = name;
6.372 -
6.373 - // Workaround IE 6/7 issue
6.374 - // - https://github.com/SteveSanderson/knockout/issues/197
6.375 - // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
6.376 - if (ieVersion <= 7) {
6.377 - try {
6.378 - element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
6.379 - }
6.380 - catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
6.381 - }
6.382 - },
6.383 -
6.384 - forceRefresh: function(node) {
6.385 - // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
6.386 - if (ieVersion >= 9) {
6.387 - // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
6.388 - var elem = node.nodeType == 1 ? node : node.parentNode;
6.389 - if (elem.style)
6.390 - elem.style.zoom = elem.style.zoom;
6.391 - }
6.392 - },
6.393 -
6.394 - ensureSelectElementIsRenderedCorrectly: function(selectElement) {
6.395 - // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
6.396 - // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
6.397 - if (ieVersion >= 9) {
6.398 - var originalWidth = selectElement.style.width;
6.399 - selectElement.style.width = 0;
6.400 - selectElement.style.width = originalWidth;
6.401 - }
6.402 - },
6.403 -
6.404 - range: function (min, max) {
6.405 - min = ko.utils.unwrapObservable(min);
6.406 - max = ko.utils.unwrapObservable(max);
6.407 - var result = [];
6.408 - for (var i = min; i <= max; i++)
6.409 - result.push(i);
6.410 - return result;
6.411 - },
6.412 -
6.413 - makeArray: function(arrayLikeObject) {
6.414 - var result = [];
6.415 - for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
6.416 - result.push(arrayLikeObject[i]);
6.417 - };
6.418 - return result;
6.419 - },
6.420 -
6.421 - isIe6 : isIe6,
6.422 - isIe7 : isIe7,
6.423 - ieVersion : ieVersion,
6.424 -
6.425 - getFormFields: function(form, fieldName) {
6.426 - var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
6.427 - var isMatchingField = (typeof fieldName == 'string')
6.428 - ? function(field) { return field.name === fieldName }
6.429 - : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
6.430 - var matches = [];
6.431 - for (var i = fields.length - 1; i >= 0; i--) {
6.432 - if (isMatchingField(fields[i]))
6.433 - matches.push(fields[i]);
6.434 - };
6.435 - return matches;
6.436 - },
6.437 -
6.438 - parseJson: function (jsonString) {
6.439 - if (typeof jsonString == "string") {
6.440 - jsonString = ko.utils.stringTrim(jsonString);
6.441 - if (jsonString) {
6.442 - if (window.JSON && window.JSON.parse) // Use native parsing where available
6.443 - return window.JSON.parse(jsonString);
6.444 - return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
6.445 - }
6.446 - }
6.447 - return null;
6.448 - },
6.449 -
6.450 - stringifyJson: function (data, replacer, space) { // replacer and space are optional
6.451 - if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
6.452 - throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
6.453 - return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
6.454 - },
6.455 -
6.456 - postJson: function (urlOrForm, data, options) {
6.457 - options = options || {};
6.458 - var params = options['params'] || {};
6.459 - var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
6.460 - var url = urlOrForm;
6.461 -
6.462 - // If we were given a form, use its 'action' URL and pick out any requested field values
6.463 - if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
6.464 - var originalForm = urlOrForm;
6.465 - url = originalForm.action;
6.466 - for (var i = includeFields.length - 1; i >= 0; i--) {
6.467 - var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
6.468 - for (var j = fields.length - 1; j >= 0; j--)
6.469 - params[fields[j].name] = fields[j].value;
6.470 - }
6.471 - }
6.472 -
6.473 - data = ko.utils.unwrapObservable(data);
6.474 - var form = document.createElement("form");
6.475 - form.style.display = "none";
6.476 - form.action = url;
6.477 - form.method = "post";
6.478 - for (var key in data) {
6.479 - var input = document.createElement("input");
6.480 - input.name = key;
6.481 - input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
6.482 - form.appendChild(input);
6.483 - }
6.484 - for (var key in params) {
6.485 - var input = document.createElement("input");
6.486 - input.name = key;
6.487 - input.value = params[key];
6.488 - form.appendChild(input);
6.489 - }
6.490 - document.body.appendChild(form);
6.491 - options['submitter'] ? options['submitter'](form) : form.submit();
6.492 - setTimeout(function () { form.parentNode.removeChild(form); }, 0);
6.493 - }
6.494 - }
6.495 -})();
6.496 -
6.497 -ko.exportSymbol('utils', ko.utils);
6.498 -ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
6.499 -ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
6.500 -ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
6.501 -ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
6.502 -ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
6.503 -ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
6.504 -ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
6.505 -ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
6.506 -ko.exportSymbol('utils.extend', ko.utils.extend);
6.507 -ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
6.508 -ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
6.509 -ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
6.510 -ko.exportSymbol('utils.postJson', ko.utils.postJson);
6.511 -ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
6.512 -ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
6.513 -ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
6.514 -ko.exportSymbol('utils.range', ko.utils.range);
6.515 -ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
6.516 -ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
6.517 -ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
6.518 -
6.519 -if (!Function.prototype['bind']) {
6.520 - // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
6.521 - // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
6.522 - Function.prototype['bind'] = function (object) {
6.523 - var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
6.524 - return function () {
6.525 - return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
6.526 - };
6.527 - };
6.528 -}
6.529 -
6.530 -ko.utils.domData = new (function () {
6.531 - var uniqueId = 0;
6.532 - var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
6.533 - var dataStore = {};
6.534 - return {
6.535 - get: function (node, key) {
6.536 - var allDataForNode = ko.utils.domData.getAll(node, false);
6.537 - return allDataForNode === undefined ? undefined : allDataForNode[key];
6.538 - },
6.539 - set: function (node, key, value) {
6.540 - if (value === undefined) {
6.541 - // Make sure we don't actually create a new domData key if we are actually deleting a value
6.542 - if (ko.utils.domData.getAll(node, false) === undefined)
6.543 - return;
6.544 - }
6.545 - var allDataForNode = ko.utils.domData.getAll(node, true);
6.546 - allDataForNode[key] = value;
6.547 - },
6.548 - getAll: function (node, createIfNotFound) {
6.549 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
6.550 - var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
6.551 - if (!hasExistingDataStore) {
6.552 - if (!createIfNotFound)
6.553 - return undefined;
6.554 - dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
6.555 - dataStore[dataStoreKey] = {};
6.556 - }
6.557 - return dataStore[dataStoreKey];
6.558 - },
6.559 - clear: function (node) {
6.560 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
6.561 - if (dataStoreKey) {
6.562 - delete dataStore[dataStoreKey];
6.563 - node[dataStoreKeyExpandoPropertyName] = null;
6.564 - return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
6.565 - }
6.566 - return false;
6.567 - }
6.568 - }
6.569 -})();
6.570 -
6.571 -ko.exportSymbol('utils.domData', ko.utils.domData);
6.572 -ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
6.573 -
6.574 -ko.utils.domNodeDisposal = new (function () {
6.575 - var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
6.576 - var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
6.577 - var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
6.578 -
6.579 - function getDisposeCallbacksCollection(node, createIfNotFound) {
6.580 - var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
6.581 - if ((allDisposeCallbacks === undefined) && createIfNotFound) {
6.582 - allDisposeCallbacks = [];
6.583 - ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
6.584 - }
6.585 - return allDisposeCallbacks;
6.586 - }
6.587 - function destroyCallbacksCollection(node) {
6.588 - ko.utils.domData.set(node, domDataKey, undefined);
6.589 - }
6.590 -
6.591 - function cleanSingleNode(node) {
6.592 - // Run all the dispose callbacks
6.593 - var callbacks = getDisposeCallbacksCollection(node, false);
6.594 - if (callbacks) {
6.595 - callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
6.596 - for (var i = 0; i < callbacks.length; i++)
6.597 - callbacks[i](node);
6.598 - }
6.599 -
6.600 - // Also erase the DOM data
6.601 - ko.utils.domData.clear(node);
6.602 -
6.603 - // Special support for jQuery here because it's so commonly used.
6.604 - // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
6.605 - // so notify it to tear down any resources associated with the node & descendants here.
6.606 - if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
6.607 - jQuery['cleanData']([node]);
6.608 -
6.609 - // Also clear any immediate-child comment nodes, as these wouldn't have been found by
6.610 - // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
6.611 - if (cleanableNodeTypesWithDescendants[node.nodeType])
6.612 - cleanImmediateCommentTypeChildren(node);
6.613 - }
6.614 -
6.615 - function cleanImmediateCommentTypeChildren(nodeWithChildren) {
6.616 - var child, nextChild = nodeWithChildren.firstChild;
6.617 - while (child = nextChild) {
6.618 - nextChild = child.nextSibling;
6.619 - if (child.nodeType === 8)
6.620 - cleanSingleNode(child);
6.621 - }
6.622 - }
6.623 -
6.624 - return {
6.625 - addDisposeCallback : function(node, callback) {
6.626 - if (typeof callback != "function")
6.627 - throw new Error("Callback must be a function");
6.628 - getDisposeCallbacksCollection(node, true).push(callback);
6.629 - },
6.630 -
6.631 - removeDisposeCallback : function(node, callback) {
6.632 - var callbacksCollection = getDisposeCallbacksCollection(node, false);
6.633 - if (callbacksCollection) {
6.634 - ko.utils.arrayRemoveItem(callbacksCollection, callback);
6.635 - if (callbacksCollection.length == 0)
6.636 - destroyCallbacksCollection(node);
6.637 - }
6.638 - },
6.639 -
6.640 - cleanNode : function(node) {
6.641 - // First clean this node, where applicable
6.642 - if (cleanableNodeTypes[node.nodeType]) {
6.643 - cleanSingleNode(node);
6.644 -
6.645 - // ... then its descendants, where applicable
6.646 - if (cleanableNodeTypesWithDescendants[node.nodeType]) {
6.647 - // Clone the descendants list in case it changes during iteration
6.648 - var descendants = [];
6.649 - ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
6.650 - for (var i = 0, j = descendants.length; i < j; i++)
6.651 - cleanSingleNode(descendants[i]);
6.652 - }
6.653 - }
6.654 - return node;
6.655 - },
6.656 -
6.657 - removeNode : function(node) {
6.658 - ko.cleanNode(node);
6.659 - if (node.parentNode)
6.660 - node.parentNode.removeChild(node);
6.661 - }
6.662 - }
6.663 -})();
6.664 -ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
6.665 -ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
6.666 -ko.exportSymbol('cleanNode', ko.cleanNode);
6.667 -ko.exportSymbol('removeNode', ko.removeNode);
6.668 -ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
6.669 -ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
6.670 -ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
6.671 -(function () {
6.672 - var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
6.673 -
6.674 - function simpleHtmlParse(html) {
6.675 - // Based on jQuery's "clean" function, but only accounting for table-related elements.
6.676 - // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
6.677 -
6.678 - // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
6.679 - // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
6.680 - // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
6.681 - // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
6.682 -
6.683 - // Trim whitespace, otherwise indexOf won't work as expected
6.684 - var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
6.685 -
6.686 - // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
6.687 - var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
6.688 - !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
6.689 - (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
6.690 - /* anything else */ [0, "", ""];
6.691 -
6.692 - // Go to html and back, then peel off extra wrappers
6.693 - // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
6.694 - var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
6.695 - if (typeof window['innerShiv'] == "function") {
6.696 - div.appendChild(window['innerShiv'](markup));
6.697 - } else {
6.698 - div.innerHTML = markup;
6.699 - }
6.700 -
6.701 - // Move to the right depth
6.702 - while (wrap[0]--)
6.703 - div = div.lastChild;
6.704 -
6.705 - return ko.utils.makeArray(div.lastChild.childNodes);
6.706 - }
6.707 -
6.708 - function jQueryHtmlParse(html) {
6.709 - // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
6.710 - if (jQuery['parseHTML']) {
6.711 - return jQuery['parseHTML'](html);
6.712 - } else {
6.713 - // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
6.714 - var elems = jQuery['clean']([html]);
6.715 -
6.716 - // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
6.717 - // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
6.718 - // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
6.719 - if (elems && elems[0]) {
6.720 - // Find the top-most parent element that's a direct child of a document fragment
6.721 - var elem = elems[0];
6.722 - while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
6.723 - elem = elem.parentNode;
6.724 - // ... then detach it
6.725 - if (elem.parentNode)
6.726 - elem.parentNode.removeChild(elem);
6.727 - }
6.728 -
6.729 - return elems;
6.730 - }
6.731 - }
6.732 -
6.733 - ko.utils.parseHtmlFragment = function(html) {
6.734 - return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
6.735 - : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
6.736 - };
6.737 -
6.738 - ko.utils.setHtml = function(node, html) {
6.739 - ko.utils.emptyDomNode(node);
6.740 -
6.741 - // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
6.742 - html = ko.utils.unwrapObservable(html);
6.743 -
6.744 - if ((html !== null) && (html !== undefined)) {
6.745 - if (typeof html != 'string')
6.746 - html = html.toString();
6.747 -
6.748 - // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
6.749 - // for example <tr> elements which are not normally allowed to exist on their own.
6.750 - // If you've referenced jQuery we'll use that rather than duplicating its code.
6.751 - if (typeof jQuery != 'undefined') {
6.752 - jQuery(node)['html'](html);
6.753 - } else {
6.754 - // ... otherwise, use KO's own parsing logic.
6.755 - var parsedNodes = ko.utils.parseHtmlFragment(html);
6.756 - for (var i = 0; i < parsedNodes.length; i++)
6.757 - node.appendChild(parsedNodes[i]);
6.758 - }
6.759 - }
6.760 - };
6.761 -})();
6.762 -
6.763 -ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
6.764 -ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
6.765 -
6.766 -ko.memoization = (function () {
6.767 - var memos = {};
6.768 -
6.769 - function randomMax8HexChars() {
6.770 - return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
6.771 - }
6.772 - function generateRandomId() {
6.773 - return randomMax8HexChars() + randomMax8HexChars();
6.774 - }
6.775 - function findMemoNodes(rootNode, appendToArray) {
6.776 - if (!rootNode)
6.777 - return;
6.778 - if (rootNode.nodeType == 8) {
6.779 - var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
6.780 - if (memoId != null)
6.781 - appendToArray.push({ domNode: rootNode, memoId: memoId });
6.782 - } else if (rootNode.nodeType == 1) {
6.783 - for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
6.784 - findMemoNodes(childNodes[i], appendToArray);
6.785 - }
6.786 - }
6.787 -
6.788 - return {
6.789 - memoize: function (callback) {
6.790 - if (typeof callback != "function")
6.791 - throw new Error("You can only pass a function to ko.memoization.memoize()");
6.792 - var memoId = generateRandomId();
6.793 - memos[memoId] = callback;
6.794 - return "<!--[ko_memo:" + memoId + "]-->";
6.795 - },
6.796 -
6.797 - unmemoize: function (memoId, callbackParams) {
6.798 - var callback = memos[memoId];
6.799 - if (callback === undefined)
6.800 - throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
6.801 - try {
6.802 - callback.apply(null, callbackParams || []);
6.803 - return true;
6.804 - }
6.805 - finally { delete memos[memoId]; }
6.806 - },
6.807 -
6.808 - unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
6.809 - var memos = [];
6.810 - findMemoNodes(domNode, memos);
6.811 - for (var i = 0, j = memos.length; i < j; i++) {
6.812 - var node = memos[i].domNode;
6.813 - var combinedParams = [node];
6.814 - if (extraCallbackParamsArray)
6.815 - ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
6.816 - ko.memoization.unmemoize(memos[i].memoId, combinedParams);
6.817 - node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
6.818 - if (node.parentNode)
6.819 - node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
6.820 - }
6.821 - },
6.822 -
6.823 - parseMemoText: function (memoText) {
6.824 - var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
6.825 - return match ? match[1] : null;
6.826 - }
6.827 - };
6.828 -})();
6.829 -
6.830 -ko.exportSymbol('memoization', ko.memoization);
6.831 -ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
6.832 -ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
6.833 -ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
6.834 -ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
6.835 -ko.extenders = {
6.836 - 'throttle': function(target, timeout) {
6.837 - // Throttling means two things:
6.838 -
6.839 - // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
6.840 - // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
6.841 - target['throttleEvaluation'] = timeout;
6.842 -
6.843 - // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
6.844 - // so the target cannot change value synchronously or faster than a certain rate
6.845 - var writeTimeoutInstance = null;
6.846 - return ko.dependentObservable({
6.847 - 'read': target,
6.848 - 'write': function(value) {
6.849 - clearTimeout(writeTimeoutInstance);
6.850 - writeTimeoutInstance = setTimeout(function() {
6.851 - target(value);
6.852 - }, timeout);
6.853 - }
6.854 - });
6.855 - },
6.856 -
6.857 - 'notify': function(target, notifyWhen) {
6.858 - target["equalityComparer"] = notifyWhen == "always"
6.859 - ? function() { return false } // Treat all values as not equal
6.860 - : ko.observable["fn"]["equalityComparer"];
6.861 - return target;
6.862 - }
6.863 -};
6.864 -
6.865 -function applyExtenders(requestedExtenders) {
6.866 - var target = this;
6.867 - if (requestedExtenders) {
6.868 - for (var key in requestedExtenders) {
6.869 - var extenderHandler = ko.extenders[key];
6.870 - if (typeof extenderHandler == 'function') {
6.871 - target = extenderHandler(target, requestedExtenders[key]);
6.872 - }
6.873 - }
6.874 - }
6.875 - return target;
6.876 -}
6.877 -
6.878 -ko.exportSymbol('extenders', ko.extenders);
6.879 -
6.880 -ko.subscription = function (target, callback, disposeCallback) {
6.881 - this.target = target;
6.882 - this.callback = callback;
6.883 - this.disposeCallback = disposeCallback;
6.884 - ko.exportProperty(this, 'dispose', this.dispose);
6.885 -};
6.886 -ko.subscription.prototype.dispose = function () {
6.887 - this.isDisposed = true;
6.888 - this.disposeCallback();
6.889 -};
6.890 -
6.891 -ko.subscribable = function () {
6.892 - this._subscriptions = {};
6.893 -
6.894 - ko.utils.extend(this, ko.subscribable['fn']);
6.895 - ko.exportProperty(this, 'subscribe', this.subscribe);
6.896 - ko.exportProperty(this, 'extend', this.extend);
6.897 - ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
6.898 -}
6.899 -
6.900 -var defaultEvent = "change";
6.901 -
6.902 -ko.subscribable['fn'] = {
6.903 - subscribe: function (callback, callbackTarget, event) {
6.904 - event = event || defaultEvent;
6.905 - var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
6.906 -
6.907 - var subscription = new ko.subscription(this, boundCallback, function () {
6.908 - ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
6.909 - }.bind(this));
6.910 -
6.911 - if (!this._subscriptions[event])
6.912 - this._subscriptions[event] = [];
6.913 - this._subscriptions[event].push(subscription);
6.914 - return subscription;
6.915 - },
6.916 -
6.917 - "notifySubscribers": function (valueToNotify, event) {
6.918 - event = event || defaultEvent;
6.919 - if (this._subscriptions[event]) {
6.920 - ko.dependencyDetection.ignore(function() {
6.921 - ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
6.922 - // In case a subscription was disposed during the arrayForEach cycle, check
6.923 - // for isDisposed on each subscription before invoking its callback
6.924 - if (subscription && (subscription.isDisposed !== true))
6.925 - subscription.callback(valueToNotify);
6.926 - });
6.927 - }, this);
6.928 - }
6.929 - },
6.930 -
6.931 - getSubscriptionsCount: function () {
6.932 - var total = 0;
6.933 - for (var eventName in this._subscriptions) {
6.934 - if (this._subscriptions.hasOwnProperty(eventName))
6.935 - total += this._subscriptions[eventName].length;
6.936 - }
6.937 - return total;
6.938 - },
6.939 -
6.940 - extend: applyExtenders
6.941 -};
6.942 -
6.943 -
6.944 -ko.isSubscribable = function (instance) {
6.945 - return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
6.946 -};
6.947 -
6.948 -ko.exportSymbol('subscribable', ko.subscribable);
6.949 -ko.exportSymbol('isSubscribable', ko.isSubscribable);
6.950 -
6.951 -ko.dependencyDetection = (function () {
6.952 - var _frames = [];
6.953 -
6.954 - return {
6.955 - begin: function (callback) {
6.956 - _frames.push({ callback: callback, distinctDependencies:[] });
6.957 - },
6.958 -
6.959 - end: function () {
6.960 - _frames.pop();
6.961 - },
6.962 -
6.963 - registerDependency: function (subscribable) {
6.964 - if (!ko.isSubscribable(subscribable))
6.965 - throw new Error("Only subscribable things can act as dependencies");
6.966 - if (_frames.length > 0) {
6.967 - var topFrame = _frames[_frames.length - 1];
6.968 - if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
6.969 - return;
6.970 - topFrame.distinctDependencies.push(subscribable);
6.971 - topFrame.callback(subscribable);
6.972 - }
6.973 - },
6.974 -
6.975 - ignore: function(callback, callbackTarget, callbackArgs) {
6.976 - try {
6.977 - _frames.push(null);
6.978 - return callback.apply(callbackTarget, callbackArgs || []);
6.979 - } finally {
6.980 - _frames.pop();
6.981 - }
6.982 - }
6.983 - };
6.984 -})();
6.985 -var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
6.986 -
6.987 -ko.observable = function (initialValue) {
6.988 - var _latestValue = initialValue;
6.989 -
6.990 - function observable() {
6.991 - if (arguments.length > 0) {
6.992 - // Write
6.993 -
6.994 - // Ignore writes if the value hasn't changed
6.995 - if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
6.996 - observable.valueWillMutate();
6.997 - _latestValue = arguments[0];
6.998 - if (DEBUG) observable._latestValue = _latestValue;
6.999 - observable.valueHasMutated();
6.1000 - }
6.1001 - return this; // Permits chained assignments
6.1002 - }
6.1003 - else {
6.1004 - // Read
6.1005 - ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
6.1006 - return _latestValue;
6.1007 - }
6.1008 - }
6.1009 - if (DEBUG) observable._latestValue = _latestValue;
6.1010 - ko.subscribable.call(observable);
6.1011 - observable.peek = function() { return _latestValue };
6.1012 - observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
6.1013 - observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
6.1014 - ko.utils.extend(observable, ko.observable['fn']);
6.1015 -
6.1016 - ko.exportProperty(observable, 'peek', observable.peek);
6.1017 - ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
6.1018 - ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
6.1019 -
6.1020 - return observable;
6.1021 -}
6.1022 -
6.1023 -ko.observable['fn'] = {
6.1024 - "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
6.1025 - var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
6.1026 - return oldValueIsPrimitive ? (a === b) : false;
6.1027 - }
6.1028 -};
6.1029 -
6.1030 -var protoProperty = ko.observable.protoProperty = "__ko_proto__";
6.1031 -ko.observable['fn'][protoProperty] = ko.observable;
6.1032 -
6.1033 -ko.hasPrototype = function(instance, prototype) {
6.1034 - if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
6.1035 - if (instance[protoProperty] === prototype) return true;
6.1036 - return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
6.1037 -};
6.1038 -
6.1039 -ko.isObservable = function (instance) {
6.1040 - return ko.hasPrototype(instance, ko.observable);
6.1041 -}
6.1042 -ko.isWriteableObservable = function (instance) {
6.1043 - // Observable
6.1044 - if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
6.1045 - return true;
6.1046 - // Writeable dependent observable
6.1047 - if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
6.1048 - return true;
6.1049 - // Anything else
6.1050 - return false;
6.1051 -}
6.1052 -
6.1053 -
6.1054 -ko.exportSymbol('observable', ko.observable);
6.1055 -ko.exportSymbol('isObservable', ko.isObservable);
6.1056 -ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
6.1057 -ko.observableArray = function (initialValues) {
6.1058 - if (arguments.length == 0) {
6.1059 - // Zero-parameter constructor initializes to empty array
6.1060 - initialValues = [];
6.1061 - }
6.1062 - if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
6.1063 - throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
6.1064 -
6.1065 - var result = ko.observable(initialValues);
6.1066 - ko.utils.extend(result, ko.observableArray['fn']);
6.1067 - return result;
6.1068 -}
6.1069 -
6.1070 -ko.observableArray['fn'] = {
6.1071 - 'remove': function (valueOrPredicate) {
6.1072 - var underlyingArray = this.peek();
6.1073 - var removedValues = [];
6.1074 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
6.1075 - for (var i = 0; i < underlyingArray.length; i++) {
6.1076 - var value = underlyingArray[i];
6.1077 - if (predicate(value)) {
6.1078 - if (removedValues.length === 0) {
6.1079 - this.valueWillMutate();
6.1080 - }
6.1081 - removedValues.push(value);
6.1082 - underlyingArray.splice(i, 1);
6.1083 - i--;
6.1084 - }
6.1085 - }
6.1086 - if (removedValues.length) {
6.1087 - this.valueHasMutated();
6.1088 - }
6.1089 - return removedValues;
6.1090 - },
6.1091 -
6.1092 - 'removeAll': function (arrayOfValues) {
6.1093 - // If you passed zero args, we remove everything
6.1094 - if (arrayOfValues === undefined) {
6.1095 - var underlyingArray = this.peek();
6.1096 - var allValues = underlyingArray.slice(0);
6.1097 - this.valueWillMutate();
6.1098 - underlyingArray.splice(0, underlyingArray.length);
6.1099 - this.valueHasMutated();
6.1100 - return allValues;
6.1101 - }
6.1102 - // If you passed an arg, we interpret it as an array of entries to remove
6.1103 - if (!arrayOfValues)
6.1104 - return [];
6.1105 - return this['remove'](function (value) {
6.1106 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
6.1107 - });
6.1108 - },
6.1109 -
6.1110 - 'destroy': function (valueOrPredicate) {
6.1111 - var underlyingArray = this.peek();
6.1112 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
6.1113 - this.valueWillMutate();
6.1114 - for (var i = underlyingArray.length - 1; i >= 0; i--) {
6.1115 - var value = underlyingArray[i];
6.1116 - if (predicate(value))
6.1117 - underlyingArray[i]["_destroy"] = true;
6.1118 - }
6.1119 - this.valueHasMutated();
6.1120 - },
6.1121 -
6.1122 - 'destroyAll': function (arrayOfValues) {
6.1123 - // If you passed zero args, we destroy everything
6.1124 - if (arrayOfValues === undefined)
6.1125 - return this['destroy'](function() { return true });
6.1126 -
6.1127 - // If you passed an arg, we interpret it as an array of entries to destroy
6.1128 - if (!arrayOfValues)
6.1129 - return [];
6.1130 - return this['destroy'](function (value) {
6.1131 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
6.1132 - });
6.1133 - },
6.1134 -
6.1135 - 'indexOf': function (item) {
6.1136 - var underlyingArray = this();
6.1137 - return ko.utils.arrayIndexOf(underlyingArray, item);
6.1138 - },
6.1139 -
6.1140 - 'replace': function(oldItem, newItem) {
6.1141 - var index = this['indexOf'](oldItem);
6.1142 - if (index >= 0) {
6.1143 - this.valueWillMutate();
6.1144 - this.peek()[index] = newItem;
6.1145 - this.valueHasMutated();
6.1146 - }
6.1147 - }
6.1148 -}
6.1149 -
6.1150 -// Populate ko.observableArray.fn with read/write functions from native arrays
6.1151 -// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
6.1152 -// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
6.1153 -ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
6.1154 - ko.observableArray['fn'][methodName] = function () {
6.1155 - // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
6.1156 - // (for consistency with mutating regular observables)
6.1157 - var underlyingArray = this.peek();
6.1158 - this.valueWillMutate();
6.1159 - var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
6.1160 - this.valueHasMutated();
6.1161 - return methodCallResult;
6.1162 - };
6.1163 -});
6.1164 -
6.1165 -// Populate ko.observableArray.fn with read-only functions from native arrays
6.1166 -ko.utils.arrayForEach(["slice"], function (methodName) {
6.1167 - ko.observableArray['fn'][methodName] = function () {
6.1168 - var underlyingArray = this();
6.1169 - return underlyingArray[methodName].apply(underlyingArray, arguments);
6.1170 - };
6.1171 -});
6.1172 -
6.1173 -ko.exportSymbol('observableArray', ko.observableArray);
6.1174 -ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
6.1175 - var _latestValue,
6.1176 - _hasBeenEvaluated = false,
6.1177 - _isBeingEvaluated = false,
6.1178 - readFunction = evaluatorFunctionOrOptions;
6.1179 -
6.1180 - if (readFunction && typeof readFunction == "object") {
6.1181 - // Single-parameter syntax - everything is on this "options" param
6.1182 - options = readFunction;
6.1183 - readFunction = options["read"];
6.1184 - } else {
6.1185 - // Multi-parameter syntax - construct the options according to the params passed
6.1186 - options = options || {};
6.1187 - if (!readFunction)
6.1188 - readFunction = options["read"];
6.1189 - }
6.1190 - if (typeof readFunction != "function")
6.1191 - throw new Error("Pass a function that returns the value of the ko.computed");
6.1192 -
6.1193 - function addSubscriptionToDependency(subscribable) {
6.1194 - _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
6.1195 - }
6.1196 -
6.1197 - function disposeAllSubscriptionsToDependencies() {
6.1198 - ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
6.1199 - subscription.dispose();
6.1200 - });
6.1201 - _subscriptionsToDependencies = [];
6.1202 - }
6.1203 -
6.1204 - function evaluatePossiblyAsync() {
6.1205 - var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
6.1206 - if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
6.1207 - clearTimeout(evaluationTimeoutInstance);
6.1208 - evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
6.1209 - } else
6.1210 - evaluateImmediate();
6.1211 - }
6.1212 -
6.1213 - function evaluateImmediate() {
6.1214 - if (_isBeingEvaluated) {
6.1215 - // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
6.1216 - // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
6.1217 - // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
6.1218 - // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
6.1219 - return;
6.1220 - }
6.1221 -
6.1222 - // Don't dispose on first evaluation, because the "disposeWhen" callback might
6.1223 - // e.g., dispose when the associated DOM element isn't in the doc, and it's not
6.1224 - // going to be in the doc until *after* the first evaluation
6.1225 - if (_hasBeenEvaluated && disposeWhen()) {
6.1226 - dispose();
6.1227 - return;
6.1228 - }
6.1229 -
6.1230 - _isBeingEvaluated = true;
6.1231 - try {
6.1232 - // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
6.1233 - // Then, during evaluation, we cross off any that are in fact still being used.
6.1234 - var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
6.1235 -
6.1236 - ko.dependencyDetection.begin(function(subscribable) {
6.1237 - var inOld;
6.1238 - if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
6.1239 - disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
6.1240 - else
6.1241 - addSubscriptionToDependency(subscribable); // Brand new subscription - add it
6.1242 - });
6.1243 -
6.1244 - var newValue = readFunction.call(evaluatorFunctionTarget);
6.1245 -
6.1246 - // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
6.1247 - for (var i = disposalCandidates.length - 1; i >= 0; i--) {
6.1248 - if (disposalCandidates[i])
6.1249 - _subscriptionsToDependencies.splice(i, 1)[0].dispose();
6.1250 - }
6.1251 - _hasBeenEvaluated = true;
6.1252 -
6.1253 - dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
6.1254 - _latestValue = newValue;
6.1255 - if (DEBUG) dependentObservable._latestValue = _latestValue;
6.1256 - } finally {
6.1257 - ko.dependencyDetection.end();
6.1258 - }
6.1259 -
6.1260 - dependentObservable["notifySubscribers"](_latestValue);
6.1261 - _isBeingEvaluated = false;
6.1262 - if (!_subscriptionsToDependencies.length)
6.1263 - dispose();
6.1264 - }
6.1265 -
6.1266 - function dependentObservable() {
6.1267 - if (arguments.length > 0) {
6.1268 - if (typeof writeFunction === "function") {
6.1269 - // Writing a value
6.1270 - writeFunction.apply(evaluatorFunctionTarget, arguments);
6.1271 - } else {
6.1272 - throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
6.1273 - }
6.1274 - return this; // Permits chained assignments
6.1275 - } else {
6.1276 - // Reading the value
6.1277 - if (!_hasBeenEvaluated)
6.1278 - evaluateImmediate();
6.1279 - ko.dependencyDetection.registerDependency(dependentObservable);
6.1280 - return _latestValue;
6.1281 - }
6.1282 - }
6.1283 -
6.1284 - function peek() {
6.1285 - if (!_hasBeenEvaluated)
6.1286 - evaluateImmediate();
6.1287 - return _latestValue;
6.1288 - }
6.1289 -
6.1290 - function isActive() {
6.1291 - return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
6.1292 - }
6.1293 -
6.1294 - // By here, "options" is always non-null
6.1295 - var writeFunction = options["write"],
6.1296 - disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
6.1297 - disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
6.1298 - dispose = disposeAllSubscriptionsToDependencies,
6.1299 - _subscriptionsToDependencies = [],
6.1300 - evaluationTimeoutInstance = null;
6.1301 -
6.1302 - if (!evaluatorFunctionTarget)
6.1303 - evaluatorFunctionTarget = options["owner"];
6.1304 -
6.1305 - dependentObservable.peek = peek;
6.1306 - dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
6.1307 - dependentObservable.hasWriteFunction = typeof options["write"] === "function";
6.1308 - dependentObservable.dispose = function () { dispose(); };
6.1309 - dependentObservable.isActive = isActive;
6.1310 - dependentObservable.valueHasMutated = function() {
6.1311 - _hasBeenEvaluated = false;
6.1312 - evaluateImmediate();
6.1313 - };
6.1314 -
6.1315 - ko.subscribable.call(dependentObservable);
6.1316 - ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
6.1317 -
6.1318 - ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
6.1319 - ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
6.1320 - ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
6.1321 - ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
6.1322 -
6.1323 - // Evaluate, unless deferEvaluation is true
6.1324 - if (options['deferEvaluation'] !== true)
6.1325 - evaluateImmediate();
6.1326 -
6.1327 - // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
6.1328 - // But skip if isActive is false (there will never be any dependencies to dispose).
6.1329 - // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
6.1330 - // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
6.1331 - if (disposeWhenNodeIsRemoved && isActive()) {
6.1332 - dispose = function() {
6.1333 - ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
6.1334 - disposeAllSubscriptionsToDependencies();
6.1335 - };
6.1336 - ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
6.1337 - var existingDisposeWhenFunction = disposeWhen;
6.1338 - disposeWhen = function () {
6.1339 - return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
6.1340 - }
6.1341 - }
6.1342 -
6.1343 - return dependentObservable;
6.1344 -};
6.1345 -
6.1346 -ko.isComputed = function(instance) {
6.1347 - return ko.hasPrototype(instance, ko.dependentObservable);
6.1348 -};
6.1349 -
6.1350 -var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
6.1351 -ko.dependentObservable[protoProp] = ko.observable;
6.1352 -
6.1353 -ko.dependentObservable['fn'] = {};
6.1354 -ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
6.1355 -
6.1356 -ko.exportSymbol('dependentObservable', ko.dependentObservable);
6.1357 -ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
6.1358 -ko.exportSymbol('isComputed', ko.isComputed);
6.1359 -
6.1360 -(function() {
6.1361 - var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
6.1362 -
6.1363 - ko.toJS = function(rootObject) {
6.1364 - if (arguments.length == 0)
6.1365 - throw new Error("When calling ko.toJS, pass the object you want to convert.");
6.1366 -
6.1367 - // We just unwrap everything at every level in the object graph
6.1368 - return mapJsObjectGraph(rootObject, function(valueToMap) {
6.1369 - // Loop because an observable's value might in turn be another observable wrapper
6.1370 - for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
6.1371 - valueToMap = valueToMap();
6.1372 - return valueToMap;
6.1373 - });
6.1374 - };
6.1375 -
6.1376 - ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
6.1377 - var plainJavaScriptObject = ko.toJS(rootObject);
6.1378 - return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
6.1379 - };
6.1380 -
6.1381 - function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
6.1382 - visitedObjects = visitedObjects || new objectLookup();
6.1383 -
6.1384 - rootObject = mapInputCallback(rootObject);
6.1385 - var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
6.1386 - if (!canHaveProperties)
6.1387 - return rootObject;
6.1388 -
6.1389 - var outputProperties = rootObject instanceof Array ? [] : {};
6.1390 - visitedObjects.save(rootObject, outputProperties);
6.1391 -
6.1392 - visitPropertiesOrArrayEntries(rootObject, function(indexer) {
6.1393 - var propertyValue = mapInputCallback(rootObject[indexer]);
6.1394 -
6.1395 - switch (typeof propertyValue) {
6.1396 - case "boolean":
6.1397 - case "number":
6.1398 - case "string":
6.1399 - case "function":
6.1400 - outputProperties[indexer] = propertyValue;
6.1401 - break;
6.1402 - case "object":
6.1403 - case "undefined":
6.1404 - var previouslyMappedValue = visitedObjects.get(propertyValue);
6.1405 - outputProperties[indexer] = (previouslyMappedValue !== undefined)
6.1406 - ? previouslyMappedValue
6.1407 - : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
6.1408 - break;
6.1409 - }
6.1410 - });
6.1411 -
6.1412 - return outputProperties;
6.1413 - }
6.1414 -
6.1415 - function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
6.1416 - if (rootObject instanceof Array) {
6.1417 - for (var i = 0; i < rootObject.length; i++)
6.1418 - visitorCallback(i);
6.1419 -
6.1420 - // For arrays, also respect toJSON property for custom mappings (fixes #278)
6.1421 - if (typeof rootObject['toJSON'] == 'function')
6.1422 - visitorCallback('toJSON');
6.1423 - } else {
6.1424 - for (var propertyName in rootObject)
6.1425 - visitorCallback(propertyName);
6.1426 - }
6.1427 - };
6.1428 -
6.1429 - function objectLookup() {
6.1430 - var keys = [];
6.1431 - var values = [];
6.1432 - this.save = function(key, value) {
6.1433 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
6.1434 - if (existingIndex >= 0)
6.1435 - values[existingIndex] = value;
6.1436 - else {
6.1437 - keys.push(key);
6.1438 - values.push(value);
6.1439 - }
6.1440 - };
6.1441 - this.get = function(key) {
6.1442 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
6.1443 - return (existingIndex >= 0) ? values[existingIndex] : undefined;
6.1444 - };
6.1445 - };
6.1446 -})();
6.1447 -
6.1448 -ko.exportSymbol('toJS', ko.toJS);
6.1449 -ko.exportSymbol('toJSON', ko.toJSON);
6.1450 -(function () {
6.1451 - var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
6.1452 -
6.1453 - // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
6.1454 - // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
6.1455 - // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
6.1456 - ko.selectExtensions = {
6.1457 - readValue : function(element) {
6.1458 - switch (ko.utils.tagNameLower(element)) {
6.1459 - case 'option':
6.1460 - if (element[hasDomDataExpandoProperty] === true)
6.1461 - return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
6.1462 - return ko.utils.ieVersion <= 7
6.1463 - ? (element.getAttributeNode('value').specified ? element.value : element.text)
6.1464 - : element.value;
6.1465 - case 'select':
6.1466 - return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
6.1467 - default:
6.1468 - return element.value;
6.1469 - }
6.1470 - },
6.1471 -
6.1472 - writeValue: function(element, value) {
6.1473 - switch (ko.utils.tagNameLower(element)) {
6.1474 - case 'option':
6.1475 - switch(typeof value) {
6.1476 - case "string":
6.1477 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
6.1478 - if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
6.1479 - delete element[hasDomDataExpandoProperty];
6.1480 - }
6.1481 - element.value = value;
6.1482 - break;
6.1483 - default:
6.1484 - // Store arbitrary object using DomData
6.1485 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
6.1486 - element[hasDomDataExpandoProperty] = true;
6.1487 -
6.1488 - // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
6.1489 - element.value = typeof value === "number" ? value : "";
6.1490 - break;
6.1491 - }
6.1492 - break;
6.1493 - case 'select':
6.1494 - for (var i = element.options.length - 1; i >= 0; i--) {
6.1495 - if (ko.selectExtensions.readValue(element.options[i]) == value) {
6.1496 - element.selectedIndex = i;
6.1497 - break;
6.1498 - }
6.1499 - }
6.1500 - break;
6.1501 - default:
6.1502 - if ((value === null) || (value === undefined))
6.1503 - value = "";
6.1504 - element.value = value;
6.1505 - break;
6.1506 - }
6.1507 - }
6.1508 - };
6.1509 -})();
6.1510 -
6.1511 -ko.exportSymbol('selectExtensions', ko.selectExtensions);
6.1512 -ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
6.1513 -ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
6.1514 -ko.expressionRewriting = (function () {
6.1515 - var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
6.1516 - var javaScriptReservedWords = ["true", "false"];
6.1517 -
6.1518 - // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
6.1519 - // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
6.1520 - var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
6.1521 -
6.1522 - function restoreTokens(string, tokens) {
6.1523 - var prevValue = null;
6.1524 - while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
6.1525 - prevValue = string;
6.1526 - string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
6.1527 - return tokens[tokenIndex];
6.1528 - });
6.1529 - }
6.1530 - return string;
6.1531 - }
6.1532 -
6.1533 - function getWriteableValue(expression) {
6.1534 - if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
6.1535 - return false;
6.1536 - var match = expression.match(javaScriptAssignmentTarget);
6.1537 - return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
6.1538 - }
6.1539 -
6.1540 - function ensureQuoted(key) {
6.1541 - var trimmedKey = ko.utils.stringTrim(key);
6.1542 - switch (trimmedKey.length && trimmedKey.charAt(0)) {
6.1543 - case "'":
6.1544 - case '"':
6.1545 - return key;
6.1546 - default:
6.1547 - return "'" + trimmedKey + "'";
6.1548 - }
6.1549 - }
6.1550 -
6.1551 - return {
6.1552 - bindingRewriteValidators: [],
6.1553 -
6.1554 - parseObjectLiteral: function(objectLiteralString) {
6.1555 - // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
6.1556 - // that is sufficient just to split an object literal string into a set of top-level key-value pairs
6.1557 -
6.1558 - var str = ko.utils.stringTrim(objectLiteralString);
6.1559 - if (str.length < 3)
6.1560 - return [];
6.1561 - if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
6.1562 - str = str.substring(1, str.length - 1);
6.1563 -
6.1564 - // Pull out any string literals and regex literals
6.1565 - var tokens = [];
6.1566 - var tokenStart = null, tokenEndChar;
6.1567 - for (var position = 0; position < str.length; position++) {
6.1568 - var c = str.charAt(position);
6.1569 - if (tokenStart === null) {
6.1570 - switch (c) {
6.1571 - case '"':
6.1572 - case "'":
6.1573 - case "/":
6.1574 - tokenStart = position;
6.1575 - tokenEndChar = c;
6.1576 - break;
6.1577 - }
6.1578 - } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
6.1579 - var token = str.substring(tokenStart, position + 1);
6.1580 - tokens.push(token);
6.1581 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
6.1582 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
6.1583 - position -= (token.length - replacement.length);
6.1584 - tokenStart = null;
6.1585 - }
6.1586 - }
6.1587 -
6.1588 - // Next pull out balanced paren, brace, and bracket blocks
6.1589 - tokenStart = null;
6.1590 - tokenEndChar = null;
6.1591 - var tokenDepth = 0, tokenStartChar = null;
6.1592 - for (var position = 0; position < str.length; position++) {
6.1593 - var c = str.charAt(position);
6.1594 - if (tokenStart === null) {
6.1595 - switch (c) {
6.1596 - case "{": tokenStart = position; tokenStartChar = c;
6.1597 - tokenEndChar = "}";
6.1598 - break;
6.1599 - case "(": tokenStart = position; tokenStartChar = c;
6.1600 - tokenEndChar = ")";
6.1601 - break;
6.1602 - case "[": tokenStart = position; tokenStartChar = c;
6.1603 - tokenEndChar = "]";
6.1604 - break;
6.1605 - }
6.1606 - }
6.1607 -
6.1608 - if (c === tokenStartChar)
6.1609 - tokenDepth++;
6.1610 - else if (c === tokenEndChar) {
6.1611 - tokenDepth--;
6.1612 - if (tokenDepth === 0) {
6.1613 - var token = str.substring(tokenStart, position + 1);
6.1614 - tokens.push(token);
6.1615 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
6.1616 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
6.1617 - position -= (token.length - replacement.length);
6.1618 - tokenStart = null;
6.1619 - }
6.1620 - }
6.1621 - }
6.1622 -
6.1623 - // Now we can safely split on commas to get the key/value pairs
6.1624 - var result = [];
6.1625 - var keyValuePairs = str.split(",");
6.1626 - for (var i = 0, j = keyValuePairs.length; i < j; i++) {
6.1627 - var pair = keyValuePairs[i];
6.1628 - var colonPos = pair.indexOf(":");
6.1629 - if ((colonPos > 0) && (colonPos < pair.length - 1)) {
6.1630 - var key = pair.substring(0, colonPos);
6.1631 - var value = pair.substring(colonPos + 1);
6.1632 - result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
6.1633 - } else {
6.1634 - result.push({ 'unknown': restoreTokens(pair, tokens) });
6.1635 - }
6.1636 - }
6.1637 - return result;
6.1638 - },
6.1639 -
6.1640 - preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
6.1641 - var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
6.1642 - ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
6.1643 - : objectLiteralStringOrKeyValueArray;
6.1644 - var resultStrings = [], propertyAccessorResultStrings = [];
6.1645 -
6.1646 - var keyValueEntry;
6.1647 - for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
6.1648 - if (resultStrings.length > 0)
6.1649 - resultStrings.push(",");
6.1650 -
6.1651 - if (keyValueEntry['key']) {
6.1652 - var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
6.1653 - resultStrings.push(quotedKey);
6.1654 - resultStrings.push(":");
6.1655 - resultStrings.push(val);
6.1656 -
6.1657 - if (val = getWriteableValue(ko.utils.stringTrim(val))) {
6.1658 - if (propertyAccessorResultStrings.length > 0)
6.1659 - propertyAccessorResultStrings.push(", ");
6.1660 - propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
6.1661 - }
6.1662 - } else if (keyValueEntry['unknown']) {
6.1663 - resultStrings.push(keyValueEntry['unknown']);
6.1664 - }
6.1665 - }
6.1666 -
6.1667 - var combinedResult = resultStrings.join("");
6.1668 - if (propertyAccessorResultStrings.length > 0) {
6.1669 - var allPropertyAccessors = propertyAccessorResultStrings.join("");
6.1670 - combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
6.1671 - }
6.1672 -
6.1673 - return combinedResult;
6.1674 - },
6.1675 -
6.1676 - keyValueArrayContainsKey: function(keyValueArray, key) {
6.1677 - for (var i = 0; i < keyValueArray.length; i++)
6.1678 - if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
6.1679 - return true;
6.1680 - return false;
6.1681 - },
6.1682 -
6.1683 - // Internal, private KO utility for updating model properties from within bindings
6.1684 - // property: If the property being updated is (or might be) an observable, pass it here
6.1685 - // If it turns out to be a writable observable, it will be written to directly
6.1686 - // allBindingsAccessor: All bindings in the current execution context.
6.1687 - // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
6.1688 - // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
6.1689 - // value: The value to be written
6.1690 - // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
6.1691 - // it is !== existing value on that writable observable
6.1692 - writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
6.1693 - if (!property || !ko.isWriteableObservable(property)) {
6.1694 - var propWriters = allBindingsAccessor()['_ko_property_writers'];
6.1695 - if (propWriters && propWriters[key])
6.1696 - propWriters[key](value);
6.1697 - } else if (!checkIfDifferent || property.peek() !== value) {
6.1698 - property(value);
6.1699 - }
6.1700 - }
6.1701 - };
6.1702 -})();
6.1703 -
6.1704 -ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
6.1705 -ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
6.1706 -ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
6.1707 -ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
6.1708 -
6.1709 -// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
6.1710 -// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
6.1711 -ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
6.1712 -ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
6.1713 - // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
6.1714 - // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
6.1715 - // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
6.1716 - // of that virtual hierarchy
6.1717 - //
6.1718 - // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
6.1719 - // without having to scatter special cases all over the binding and templating code.
6.1720 -
6.1721 - // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
6.1722 - // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
6.1723 - // So, use node.text where available, and node.nodeValue elsewhere
6.1724 - var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
6.1725 -
6.1726 - var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
6.1727 - var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
6.1728 - var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
6.1729 -
6.1730 - function isStartComment(node) {
6.1731 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
6.1732 - }
6.1733 -
6.1734 - function isEndComment(node) {
6.1735 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
6.1736 - }
6.1737 -
6.1738 - function getVirtualChildren(startComment, allowUnbalanced) {
6.1739 - var currentNode = startComment;
6.1740 - var depth = 1;
6.1741 - var children = [];
6.1742 - while (currentNode = currentNode.nextSibling) {
6.1743 - if (isEndComment(currentNode)) {
6.1744 - depth--;
6.1745 - if (depth === 0)
6.1746 - return children;
6.1747 - }
6.1748 -
6.1749 - children.push(currentNode);
6.1750 -
6.1751 - if (isStartComment(currentNode))
6.1752 - depth++;
6.1753 - }
6.1754 - if (!allowUnbalanced)
6.1755 - throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
6.1756 - return null;
6.1757 - }
6.1758 -
6.1759 - function getMatchingEndComment(startComment, allowUnbalanced) {
6.1760 - var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
6.1761 - if (allVirtualChildren) {
6.1762 - if (allVirtualChildren.length > 0)
6.1763 - return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
6.1764 - return startComment.nextSibling;
6.1765 - } else
6.1766 - return null; // Must have no matching end comment, and allowUnbalanced is true
6.1767 - }
6.1768 -
6.1769 - function getUnbalancedChildTags(node) {
6.1770 - // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
6.1771 - // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
6.1772 - var childNode = node.firstChild, captureRemaining = null;
6.1773 - if (childNode) {
6.1774 - do {
6.1775 - if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
6.1776 - captureRemaining.push(childNode);
6.1777 - else if (isStartComment(childNode)) {
6.1778 - var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
6.1779 - if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
6.1780 - childNode = matchingEndComment;
6.1781 - else
6.1782 - captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
6.1783 - } else if (isEndComment(childNode)) {
6.1784 - captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
6.1785 - }
6.1786 - } while (childNode = childNode.nextSibling);
6.1787 - }
6.1788 - return captureRemaining;
6.1789 - }
6.1790 -
6.1791 - ko.virtualElements = {
6.1792 - allowedBindings: {},
6.1793 -
6.1794 - childNodes: function(node) {
6.1795 - return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
6.1796 - },
6.1797 -
6.1798 - emptyNode: function(node) {
6.1799 - if (!isStartComment(node))
6.1800 - ko.utils.emptyDomNode(node);
6.1801 - else {
6.1802 - var virtualChildren = ko.virtualElements.childNodes(node);
6.1803 - for (var i = 0, j = virtualChildren.length; i < j; i++)
6.1804 - ko.removeNode(virtualChildren[i]);
6.1805 - }
6.1806 - },
6.1807 -
6.1808 - setDomNodeChildren: function(node, childNodes) {
6.1809 - if (!isStartComment(node))
6.1810 - ko.utils.setDomNodeChildren(node, childNodes);
6.1811 - else {
6.1812 - ko.virtualElements.emptyNode(node);
6.1813 - var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
6.1814 - for (var i = 0, j = childNodes.length; i < j; i++)
6.1815 - endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
6.1816 - }
6.1817 - },
6.1818 -
6.1819 - prepend: function(containerNode, nodeToPrepend) {
6.1820 - if (!isStartComment(containerNode)) {
6.1821 - if (containerNode.firstChild)
6.1822 - containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
6.1823 - else
6.1824 - containerNode.appendChild(nodeToPrepend);
6.1825 - } else {
6.1826 - // Start comments must always have a parent and at least one following sibling (the end comment)
6.1827 - containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
6.1828 - }
6.1829 - },
6.1830 -
6.1831 - insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
6.1832 - if (!insertAfterNode) {
6.1833 - ko.virtualElements.prepend(containerNode, nodeToInsert);
6.1834 - } else if (!isStartComment(containerNode)) {
6.1835 - // Insert after insertion point
6.1836 - if (insertAfterNode.nextSibling)
6.1837 - containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
6.1838 - else
6.1839 - containerNode.appendChild(nodeToInsert);
6.1840 - } else {
6.1841 - // Children of start comments must always have a parent and at least one following sibling (the end comment)
6.1842 - containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
6.1843 - }
6.1844 - },
6.1845 -
6.1846 - firstChild: function(node) {
6.1847 - if (!isStartComment(node))
6.1848 - return node.firstChild;
6.1849 - if (!node.nextSibling || isEndComment(node.nextSibling))
6.1850 - return null;
6.1851 - return node.nextSibling;
6.1852 - },
6.1853 -
6.1854 - nextSibling: function(node) {
6.1855 - if (isStartComment(node))
6.1856 - node = getMatchingEndComment(node);
6.1857 - if (node.nextSibling && isEndComment(node.nextSibling))
6.1858 - return null;
6.1859 - return node.nextSibling;
6.1860 - },
6.1861 -
6.1862 - virtualNodeBindingValue: function(node) {
6.1863 - var regexMatch = isStartComment(node);
6.1864 - return regexMatch ? regexMatch[1] : null;
6.1865 - },
6.1866 -
6.1867 - normaliseVirtualElementDomStructure: function(elementVerified) {
6.1868 - // Workaround for https://github.com/SteveSanderson/knockout/issues/155
6.1869 - // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
6.1870 - // that are direct descendants of <ul> into the preceding <li>)
6.1871 - if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
6.1872 - return;
6.1873 -
6.1874 - // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
6.1875 - // must be intended to appear *after* that child, so move them there.
6.1876 - var childNode = elementVerified.firstChild;
6.1877 - if (childNode) {
6.1878 - do {
6.1879 - if (childNode.nodeType === 1) {
6.1880 - var unbalancedTags = getUnbalancedChildTags(childNode);
6.1881 - if (unbalancedTags) {
6.1882 - // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
6.1883 - var nodeToInsertBefore = childNode.nextSibling;
6.1884 - for (var i = 0; i < unbalancedTags.length; i++) {
6.1885 - if (nodeToInsertBefore)
6.1886 - elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
6.1887 - else
6.1888 - elementVerified.appendChild(unbalancedTags[i]);
6.1889 - }
6.1890 - }
6.1891 - }
6.1892 - } while (childNode = childNode.nextSibling);
6.1893 - }
6.1894 - }
6.1895 - };
6.1896 -})();
6.1897 -ko.exportSymbol('virtualElements', ko.virtualElements);
6.1898 -ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
6.1899 -ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
6.1900 -//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
6.1901 -ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
6.1902 -//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
6.1903 -ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
6.1904 -ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
6.1905 -(function() {
6.1906 - var defaultBindingAttributeName = "data-bind";
6.1907 -
6.1908 - ko.bindingProvider = function() {
6.1909 - this.bindingCache = {};
6.1910 - };
6.1911 -
6.1912 - ko.utils.extend(ko.bindingProvider.prototype, {
6.1913 - 'nodeHasBindings': function(node) {
6.1914 - switch (node.nodeType) {
6.1915 - case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
6.1916 - case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
6.1917 - default: return false;
6.1918 - }
6.1919 - },
6.1920 -
6.1921 - 'getBindings': function(node, bindingContext) {
6.1922 - var bindingsString = this['getBindingsString'](node, bindingContext);
6.1923 - return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
6.1924 - },
6.1925 -
6.1926 - // The following function is only used internally by this default provider.
6.1927 - // It's not part of the interface definition for a general binding provider.
6.1928 - 'getBindingsString': function(node, bindingContext) {
6.1929 - switch (node.nodeType) {
6.1930 - case 1: return node.getAttribute(defaultBindingAttributeName); // Element
6.1931 - case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
6.1932 - default: return null;
6.1933 - }
6.1934 - },
6.1935 -
6.1936 - // The following function is only used internally by this default provider.
6.1937 - // It's not part of the interface definition for a general binding provider.
6.1938 - 'parseBindingsString': function(bindingsString, bindingContext, node) {
6.1939 - try {
6.1940 - var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
6.1941 - return bindingFunction(bindingContext, node);
6.1942 - } catch (ex) {
6.1943 - throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
6.1944 - }
6.1945 - }
6.1946 - });
6.1947 -
6.1948 - ko.bindingProvider['instance'] = new ko.bindingProvider();
6.1949 -
6.1950 - function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
6.1951 - var cacheKey = bindingsString;
6.1952 - return cache[cacheKey]
6.1953 - || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
6.1954 - }
6.1955 -
6.1956 - function createBindingsStringEvaluator(bindingsString) {
6.1957 - // Build the source for a function that evaluates "expression"
6.1958 - // For each scope variable, add an extra level of "with" nesting
6.1959 - // Example result: with(sc1) { with(sc0) { return (expression) } }
6.1960 - var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
6.1961 - functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
6.1962 - return new Function("$context", "$element", functionBody);
6.1963 - }
6.1964 -})();
6.1965 -
6.1966 -ko.exportSymbol('bindingProvider', ko.bindingProvider);
6.1967 -(function () {
6.1968 - ko.bindingHandlers = {};
6.1969 -
6.1970 - ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
6.1971 - if (parentBindingContext) {
6.1972 - ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
6.1973 - this['$parentContext'] = parentBindingContext;
6.1974 - this['$parent'] = parentBindingContext['$data'];
6.1975 - this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
6.1976 - this['$parents'].unshift(this['$parent']);
6.1977 - } else {
6.1978 - this['$parents'] = [];
6.1979 - this['$root'] = dataItem;
6.1980 - // Export 'ko' in the binding context so it will be available in bindings and templates
6.1981 - // even if 'ko' isn't exported as a global, such as when using an AMD loader.
6.1982 - // See https://github.com/SteveSanderson/knockout/issues/490
6.1983 - this['ko'] = ko;
6.1984 - }
6.1985 - this['$data'] = dataItem;
6.1986 - if (dataItemAlias)
6.1987 - this[dataItemAlias] = dataItem;
6.1988 - }
6.1989 - ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
6.1990 - return new ko.bindingContext(dataItem, this, dataItemAlias);
6.1991 - };
6.1992 - ko.bindingContext.prototype['extend'] = function(properties) {
6.1993 - var clone = ko.utils.extend(new ko.bindingContext(), this);
6.1994 - return ko.utils.extend(clone, properties);
6.1995 - };
6.1996 -
6.1997 - function validateThatBindingIsAllowedForVirtualElements(bindingName) {
6.1998 - var validator = ko.virtualElements.allowedBindings[bindingName];
6.1999 - if (!validator)
6.2000 - throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
6.2001 - }
6.2002 -
6.2003 - function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
6.2004 - var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
6.2005 - while (currentChild = nextInQueue) {
6.2006 - // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
6.2007 - nextInQueue = ko.virtualElements.nextSibling(currentChild);
6.2008 - applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
6.2009 - }
6.2010 - }
6.2011 -
6.2012 - function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
6.2013 - var shouldBindDescendants = true;
6.2014 -
6.2015 - // Perf optimisation: Apply bindings only if...
6.2016 - // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
6.2017 - // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
6.2018 - // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
6.2019 - var isElement = (nodeVerified.nodeType === 1);
6.2020 - if (isElement) // Workaround IE <= 8 HTML parsing weirdness
6.2021 - ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
6.2022 -
6.2023 - var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
6.2024 - || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
6.2025 - if (shouldApplyBindings)
6.2026 - shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
6.2027 -
6.2028 - if (shouldBindDescendants) {
6.2029 - // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
6.2030 - // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
6.2031 - // hence bindingContextsMayDifferFromDomParentElement is false
6.2032 - // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
6.2033 - // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
6.2034 - // hence bindingContextsMayDifferFromDomParentElement is true
6.2035 - applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
6.2036 - }
6.2037 - }
6.2038 -
6.2039 - function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
6.2040 - // Need to be sure that inits are only run once, and updates never run until all the inits have been run
6.2041 - var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
6.2042 -
6.2043 - // Each time the dependentObservable is evaluated (after data changes),
6.2044 - // the binding attribute is reparsed so that it can pick out the correct
6.2045 - // model properties in the context of the changed data.
6.2046 - // DOM event callbacks need to be able to access this changed data,
6.2047 - // so we need a single parsedBindings variable (shared by all callbacks
6.2048 - // associated with this node's bindings) that all the closures can access.
6.2049 - var parsedBindings;
6.2050 - function makeValueAccessor(bindingKey) {
6.2051 - return function () { return parsedBindings[bindingKey] }
6.2052 - }
6.2053 - function parsedBindingsAccessor() {
6.2054 - return parsedBindings;
6.2055 - }
6.2056 -
6.2057 - var bindingHandlerThatControlsDescendantBindings;
6.2058 - ko.dependentObservable(
6.2059 - function () {
6.2060 - // Ensure we have a nonnull binding context to work with
6.2061 - var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
6.2062 - ? viewModelOrBindingContext
6.2063 - : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
6.2064 - var viewModel = bindingContextInstance['$data'];
6.2065 -
6.2066 - // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
6.2067 - // we can easily recover it just by scanning up the node's ancestors in the DOM
6.2068 - // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
6.2069 - if (bindingContextMayDifferFromDomParentElement)
6.2070 - ko.storedBindingContextForNode(node, bindingContextInstance);
6.2071 -
6.2072 - // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
6.2073 - var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
6.2074 - parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
6.2075 -
6.2076 - if (parsedBindings) {
6.2077 - // First run all the inits, so bindings can register for notification on changes
6.2078 - if (initPhase === 0) {
6.2079 - initPhase = 1;
6.2080 - for (var bindingKey in parsedBindings) {
6.2081 - var binding = ko.bindingHandlers[bindingKey];
6.2082 - if (binding && node.nodeType === 8)
6.2083 - validateThatBindingIsAllowedForVirtualElements(bindingKey);
6.2084 -
6.2085 - if (binding && typeof binding["init"] == "function") {
6.2086 - var handlerInitFn = binding["init"];
6.2087 - var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
6.2088 -
6.2089 - // If this binding handler claims to control descendant bindings, make a note of this
6.2090 - if (initResult && initResult['controlsDescendantBindings']) {
6.2091 - if (bindingHandlerThatControlsDescendantBindings !== undefined)
6.2092 - throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
6.2093 - bindingHandlerThatControlsDescendantBindings = bindingKey;
6.2094 - }
6.2095 - }
6.2096 - }
6.2097 - initPhase = 2;
6.2098 - }
6.2099 -
6.2100 - // ... then run all the updates, which might trigger changes even on the first evaluation
6.2101 - if (initPhase === 2) {
6.2102 - for (var bindingKey in parsedBindings) {
6.2103 - var binding = ko.bindingHandlers[bindingKey];
6.2104 - if (binding && typeof binding["update"] == "function") {
6.2105 - var handlerUpdateFn = binding["update"];
6.2106 - handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
6.2107 - }
6.2108 - }
6.2109 - }
6.2110 - }
6.2111 - },
6.2112 - null,
6.2113 - { disposeWhenNodeIsRemoved : node }
6.2114 - );
6.2115 -
6.2116 - return {
6.2117 - shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
6.2118 - };
6.2119 - };
6.2120 -
6.2121 - var storedBindingContextDomDataKey = "__ko_bindingContext__";
6.2122 - ko.storedBindingContextForNode = function (node, bindingContext) {
6.2123 - if (arguments.length == 2)
6.2124 - ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
6.2125 - else
6.2126 - return ko.utils.domData.get(node, storedBindingContextDomDataKey);
6.2127 - }
6.2128 -
6.2129 - ko.applyBindingsToNode = function (node, bindings, viewModel) {
6.2130 - if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
6.2131 - ko.virtualElements.normaliseVirtualElementDomStructure(node);
6.2132 - return applyBindingsToNodeInternal(node, bindings, viewModel, true);
6.2133 - };
6.2134 -
6.2135 - ko.applyBindingsToDescendants = function(viewModel, rootNode) {
6.2136 - if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
6.2137 - applyBindingsToDescendantsInternal(viewModel, rootNode, true);
6.2138 - };
6.2139 -
6.2140 - ko.applyBindings = function (viewModel, rootNode) {
6.2141 - if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
6.2142 - throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
6.2143 - rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
6.2144 -
6.2145 - applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
6.2146 - };
6.2147 -
6.2148 - // Retrieving binding context from arbitrary nodes
6.2149 - ko.contextFor = function(node) {
6.2150 - // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
6.2151 - switch (node.nodeType) {
6.2152 - case 1:
6.2153 - case 8:
6.2154 - var context = ko.storedBindingContextForNode(node);
6.2155 - if (context) return context;
6.2156 - if (node.parentNode) return ko.contextFor(node.parentNode);
6.2157 - break;
6.2158 - }
6.2159 - return undefined;
6.2160 - };
6.2161 - ko.dataFor = function(node) {
6.2162 - var context = ko.contextFor(node);
6.2163 - return context ? context['$data'] : undefined;
6.2164 - };
6.2165 -
6.2166 - ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
6.2167 - ko.exportSymbol('applyBindings', ko.applyBindings);
6.2168 - ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
6.2169 - ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
6.2170 - ko.exportSymbol('contextFor', ko.contextFor);
6.2171 - ko.exportSymbol('dataFor', ko.dataFor);
6.2172 -})();
6.2173 -var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
6.2174 -ko.bindingHandlers['attr'] = {
6.2175 - 'update': function(element, valueAccessor, allBindingsAccessor) {
6.2176 - var value = ko.utils.unwrapObservable(valueAccessor()) || {};
6.2177 - for (var attrName in value) {
6.2178 - if (typeof attrName == "string") {
6.2179 - var attrValue = ko.utils.unwrapObservable(value[attrName]);
6.2180 -
6.2181 - // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
6.2182 - // when someProp is a "no value"-like value (strictly null, false, or undefined)
6.2183 - // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
6.2184 - var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
6.2185 - if (toRemove)
6.2186 - element.removeAttribute(attrName);
6.2187 -
6.2188 - // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
6.2189 - // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
6.2190 - // but instead of figuring out the mode, we'll just set the attribute through the Javascript
6.2191 - // property for IE <= 8.
6.2192 - if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
6.2193 - attrName = attrHtmlToJavascriptMap[attrName];
6.2194 - if (toRemove)
6.2195 - element.removeAttribute(attrName);
6.2196 - else
6.2197 - element[attrName] = attrValue;
6.2198 - } else if (!toRemove) {
6.2199 - try {
6.2200 - element.setAttribute(attrName, attrValue.toString());
6.2201 - } catch (err) {
6.2202 - // ignore for now
6.2203 - if (console) {
6.2204 - console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
6.2205 - }
6.2206 - }
6.2207 - }
6.2208 -
6.2209 - // Treat "name" specially - although you can think of it as an attribute, it also needs
6.2210 - // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
6.2211 - // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
6.2212 - // entirely, and there's no strong reason to allow for such casing in HTML.
6.2213 - if (attrName === "name") {
6.2214 - ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
6.2215 - }
6.2216 - }
6.2217 - }
6.2218 - }
6.2219 -};
6.2220 -ko.bindingHandlers['checked'] = {
6.2221 - 'init': function (element, valueAccessor, allBindingsAccessor) {
6.2222 - var updateHandler = function() {
6.2223 - var valueToWrite;
6.2224 - if (element.type == "checkbox") {
6.2225 - valueToWrite = element.checked;
6.2226 - } else if ((element.type == "radio") && (element.checked)) {
6.2227 - valueToWrite = element.value;
6.2228 - } else {
6.2229 - return; // "checked" binding only responds to checkboxes and selected radio buttons
6.2230 - }
6.2231 -
6.2232 - var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
6.2233 - if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
6.2234 - // For checkboxes bound to an array, we add/remove the checkbox value to that array
6.2235 - // This works for both observable and non-observable arrays
6.2236 - var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
6.2237 - if (element.checked && (existingEntryIndex < 0))
6.2238 - modelValue.push(element.value);
6.2239 - else if ((!element.checked) && (existingEntryIndex >= 0))
6.2240 - modelValue.splice(existingEntryIndex, 1);
6.2241 - } else {
6.2242 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
6.2243 - }
6.2244 - };
6.2245 - ko.utils.registerEventHandler(element, "click", updateHandler);
6.2246 -
6.2247 - // IE 6 won't allow radio buttons to be selected unless they have a name
6.2248 - if ((element.type == "radio") && !element.name)
6.2249 - ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
6.2250 - },
6.2251 - 'update': function (element, valueAccessor) {
6.2252 - var value = ko.utils.unwrapObservable(valueAccessor());
6.2253 -
6.2254 - if (element.type == "checkbox") {
6.2255 - if (value instanceof Array) {
6.2256 - // When bound to an array, the checkbox being checked represents its value being present in that array
6.2257 - element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
6.2258 - } else {
6.2259 - // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
6.2260 - element.checked = value;
6.2261 - }
6.2262 - } else if (element.type == "radio") {
6.2263 - element.checked = (element.value == value);
6.2264 - }
6.2265 - }
6.2266 -};
6.2267 -var classesWrittenByBindingKey = '__ko__cssValue';
6.2268 -ko.bindingHandlers['css'] = {
6.2269 - 'update': function (element, valueAccessor) {
6.2270 - var value = ko.utils.unwrapObservable(valueAccessor());
6.2271 - if (typeof value == "object") {
6.2272 - for (var className in value) {
6.2273 - var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
6.2274 - ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
6.2275 - }
6.2276 - } else {
6.2277 - value = String(value || ''); // Make sure we don't try to store or set a non-string value
6.2278 - ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
6.2279 - element[classesWrittenByBindingKey] = value;
6.2280 - ko.utils.toggleDomNodeCssClass(element, value, true);
6.2281 - }
6.2282 - }
6.2283 -};
6.2284 -ko.bindingHandlers['enable'] = {
6.2285 - 'update': function (element, valueAccessor) {
6.2286 - var value = ko.utils.unwrapObservable(valueAccessor());
6.2287 - if (value && element.disabled)
6.2288 - element.removeAttribute("disabled");
6.2289 - else if ((!value) && (!element.disabled))
6.2290 - element.disabled = true;
6.2291 - }
6.2292 -};
6.2293 -
6.2294 -ko.bindingHandlers['disable'] = {
6.2295 - 'update': function (element, valueAccessor) {
6.2296 - ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
6.2297 - }
6.2298 -};
6.2299 -// For certain common events (currently just 'click'), allow a simplified data-binding syntax
6.2300 -// e.g. click:handler instead of the usual full-length event:{click:handler}
6.2301 -function makeEventHandlerShortcut(eventName) {
6.2302 - ko.bindingHandlers[eventName] = {
6.2303 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
6.2304 - var newValueAccessor = function () {
6.2305 - var result = {};
6.2306 - result[eventName] = valueAccessor();
6.2307 - return result;
6.2308 - };
6.2309 - return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
6.2310 - }
6.2311 - }
6.2312 -}
6.2313 -
6.2314 -ko.bindingHandlers['event'] = {
6.2315 - 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
6.2316 - var eventsToHandle = valueAccessor() || {};
6.2317 - for(var eventNameOutsideClosure in eventsToHandle) {
6.2318 - (function() {
6.2319 - var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
6.2320 - if (typeof eventName == "string") {
6.2321 - ko.utils.registerEventHandler(element, eventName, function (event) {
6.2322 - var handlerReturnValue;
6.2323 - var handlerFunction = valueAccessor()[eventName];
6.2324 - if (!handlerFunction)
6.2325 - return;
6.2326 - var allBindings = allBindingsAccessor();
6.2327 -
6.2328 - try {
6.2329 - // Take all the event args, and prefix with the viewmodel
6.2330 - var argsForHandler = ko.utils.makeArray(arguments);
6.2331 - argsForHandler.unshift(viewModel);
6.2332 - handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
6.2333 - } finally {
6.2334 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
6.2335 - if (event.preventDefault)
6.2336 - event.preventDefault();
6.2337 - else
6.2338 - event.returnValue = false;
6.2339 - }
6.2340 - }
6.2341 -
6.2342 - var bubble = allBindings[eventName + 'Bubble'] !== false;
6.2343 - if (!bubble) {
6.2344 - event.cancelBubble = true;
6.2345 - if (event.stopPropagation)
6.2346 - event.stopPropagation();
6.2347 - }
6.2348 - });
6.2349 - }
6.2350 - })();
6.2351 - }
6.2352 - }
6.2353 -};
6.2354 -// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
6.2355 -// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
6.2356 -ko.bindingHandlers['foreach'] = {
6.2357 - makeTemplateValueAccessor: function(valueAccessor) {
6.2358 - return function() {
6.2359 - var modelValue = valueAccessor(),
6.2360 - unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
6.2361 -
6.2362 - // If unwrappedValue is the array, pass in the wrapped value on its own
6.2363 - // The value will be unwrapped and tracked within the template binding
6.2364 - // (See https://github.com/SteveSanderson/knockout/issues/523)
6.2365 - if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
6.2366 - return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
6.2367 -
6.2368 - // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
6.2369 - ko.utils.unwrapObservable(modelValue);
6.2370 - return {
6.2371 - 'foreach': unwrappedValue['data'],
6.2372 - 'as': unwrappedValue['as'],
6.2373 - 'includeDestroyed': unwrappedValue['includeDestroyed'],
6.2374 - 'afterAdd': unwrappedValue['afterAdd'],
6.2375 - 'beforeRemove': unwrappedValue['beforeRemove'],
6.2376 - 'afterRender': unwrappedValue['afterRender'],
6.2377 - 'beforeMove': unwrappedValue['beforeMove'],
6.2378 - 'afterMove': unwrappedValue['afterMove'],
6.2379 - 'templateEngine': ko.nativeTemplateEngine.instance
6.2380 - };
6.2381 - };
6.2382 - },
6.2383 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.2384 - return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
6.2385 - },
6.2386 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.2387 - return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
6.2388 - }
6.2389 -};
6.2390 -ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
6.2391 -ko.virtualElements.allowedBindings['foreach'] = true;
6.2392 -var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
6.2393 -ko.bindingHandlers['hasfocus'] = {
6.2394 - 'init': function(element, valueAccessor, allBindingsAccessor) {
6.2395 - var handleElementFocusChange = function(isFocused) {
6.2396 - // Where possible, ignore which event was raised and determine focus state using activeElement,
6.2397 - // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
6.2398 - // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
6.2399 - // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
6.2400 - // from calling 'blur()' on the element when it loses focus.
6.2401 - // Discussion at https://github.com/SteveSanderson/knockout/pull/352
6.2402 - element[hasfocusUpdatingProperty] = true;
6.2403 - var ownerDoc = element.ownerDocument;
6.2404 - if ("activeElement" in ownerDoc) {
6.2405 - isFocused = (ownerDoc.activeElement === element);
6.2406 - }
6.2407 - var modelValue = valueAccessor();
6.2408 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
6.2409 - element[hasfocusUpdatingProperty] = false;
6.2410 - };
6.2411 - var handleElementFocusIn = handleElementFocusChange.bind(null, true);
6.2412 - var handleElementFocusOut = handleElementFocusChange.bind(null, false);
6.2413 -
6.2414 - ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
6.2415 - ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
6.2416 - ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
6.2417 - ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
6.2418 - },
6.2419 - 'update': function(element, valueAccessor) {
6.2420 - var value = ko.utils.unwrapObservable(valueAccessor());
6.2421 - if (!element[hasfocusUpdatingProperty]) {
6.2422 - value ? element.focus() : element.blur();
6.2423 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
6.2424 - }
6.2425 - }
6.2426 -};
6.2427 -ko.bindingHandlers['html'] = {
6.2428 - 'init': function() {
6.2429 - // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
6.2430 - return { 'controlsDescendantBindings': true };
6.2431 - },
6.2432 - 'update': function (element, valueAccessor) {
6.2433 - // setHtml will unwrap the value if needed
6.2434 - ko.utils.setHtml(element, valueAccessor());
6.2435 - }
6.2436 -};
6.2437 -var withIfDomDataKey = '__ko_withIfBindingData';
6.2438 -// Makes a binding like with or if
6.2439 -function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
6.2440 - ko.bindingHandlers[bindingKey] = {
6.2441 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.2442 - ko.utils.domData.set(element, withIfDomDataKey, {});
6.2443 - return { 'controlsDescendantBindings': true };
6.2444 - },
6.2445 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.2446 - var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
6.2447 - dataValue = ko.utils.unwrapObservable(valueAccessor()),
6.2448 - shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
6.2449 - isFirstRender = !withIfData.savedNodes,
6.2450 - needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
6.2451 -
6.2452 - if (needsRefresh) {
6.2453 - if (isFirstRender) {
6.2454 - withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
6.2455 - }
6.2456 -
6.2457 - if (shouldDisplay) {
6.2458 - if (!isFirstRender) {
6.2459 - ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
6.2460 - }
6.2461 - ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
6.2462 - } else {
6.2463 - ko.virtualElements.emptyNode(element);
6.2464 - }
6.2465 -
6.2466 - withIfData.didDisplayOnLastUpdate = shouldDisplay;
6.2467 - }
6.2468 - }
6.2469 - };
6.2470 - ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
6.2471 - ko.virtualElements.allowedBindings[bindingKey] = true;
6.2472 -}
6.2473 -
6.2474 -// Construct the actual binding handlers
6.2475 -makeWithIfBinding('if');
6.2476 -makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
6.2477 -makeWithIfBinding('with', true /* isWith */, false /* isNot */,
6.2478 - function(bindingContext, dataValue) {
6.2479 - return bindingContext['createChildContext'](dataValue);
6.2480 - }
6.2481 -);
6.2482 -function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
6.2483 - if (preferModelValue) {
6.2484 - if (modelValue !== ko.selectExtensions.readValue(element))
6.2485 - ko.selectExtensions.writeValue(element, modelValue);
6.2486 - }
6.2487 -
6.2488 - // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
6.2489 - // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
6.2490 - // change the model value to match the dropdown.
6.2491 - if (modelValue !== ko.selectExtensions.readValue(element))
6.2492 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
6.2493 -};
6.2494 -
6.2495 -ko.bindingHandlers['options'] = {
6.2496 - 'update': function (element, valueAccessor, allBindingsAccessor) {
6.2497 - if (ko.utils.tagNameLower(element) !== "select")
6.2498 - throw new Error("options binding applies only to SELECT elements");
6.2499 -
6.2500 - var selectWasPreviouslyEmpty = element.length == 0;
6.2501 - var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
6.2502 - return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
6.2503 - }), function (node) {
6.2504 - return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
6.2505 - });
6.2506 - var previousScrollTop = element.scrollTop;
6.2507 -
6.2508 - var value = ko.utils.unwrapObservable(valueAccessor());
6.2509 - var selectedValue = element.value;
6.2510 -
6.2511 - // Remove all existing <option>s.
6.2512 - // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
6.2513 - while (element.length > 0) {
6.2514 - ko.cleanNode(element.options[0]);
6.2515 - element.remove(0);
6.2516 - }
6.2517 -
6.2518 - if (value) {
6.2519 - var allBindings = allBindingsAccessor(),
6.2520 - includeDestroyed = allBindings['optionsIncludeDestroyed'];
6.2521 -
6.2522 - if (typeof value.length != "number")
6.2523 - value = [value];
6.2524 - if (allBindings['optionsCaption']) {
6.2525 - var option = document.createElement("option");
6.2526 - ko.utils.setHtml(option, allBindings['optionsCaption']);
6.2527 - ko.selectExtensions.writeValue(option, undefined);
6.2528 - element.appendChild(option);
6.2529 - }
6.2530 -
6.2531 - for (var i = 0, j = value.length; i < j; i++) {
6.2532 - // Skip destroyed items
6.2533 - var arrayEntry = value[i];
6.2534 - if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
6.2535 - continue;
6.2536 -
6.2537 - var option = document.createElement("option");
6.2538 -
6.2539 - function applyToObject(object, predicate, defaultValue) {
6.2540 - var predicateType = typeof predicate;
6.2541 - if (predicateType == "function") // Given a function; run it against the data value
6.2542 - return predicate(object);
6.2543 - else if (predicateType == "string") // Given a string; treat it as a property name on the data value
6.2544 - return object[predicate];
6.2545 - else // Given no optionsText arg; use the data value itself
6.2546 - return defaultValue;
6.2547 - }
6.2548 -
6.2549 - // Apply a value to the option element
6.2550 - var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
6.2551 - ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
6.2552 -
6.2553 - // Apply some text to the option element
6.2554 - var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
6.2555 - ko.utils.setTextContent(option, optionText);
6.2556 -
6.2557 - element.appendChild(option);
6.2558 - }
6.2559 -
6.2560 - // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
6.2561 - // That's why we first added them without selection. Now it's time to set the selection.
6.2562 - var newOptions = element.getElementsByTagName("option");
6.2563 - var countSelectionsRetained = 0;
6.2564 - for (var i = 0, j = newOptions.length; i < j; i++) {
6.2565 - if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
6.2566 - ko.utils.setOptionNodeSelectionState(newOptions[i], true);
6.2567 - countSelectionsRetained++;
6.2568 - }
6.2569 - }
6.2570 -
6.2571 - element.scrollTop = previousScrollTop;
6.2572 -
6.2573 - if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
6.2574 - // Ensure consistency between model value and selected option.
6.2575 - // If the dropdown is being populated for the first time here (or was otherwise previously empty),
6.2576 - // the dropdown selection state is meaningless, so we preserve the model value.
6.2577 - ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
6.2578 - }
6.2579 -
6.2580 - // Workaround for IE9 bug
6.2581 - ko.utils.ensureSelectElementIsRenderedCorrectly(element);
6.2582 - }
6.2583 - }
6.2584 -};
6.2585 -ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
6.2586 -ko.bindingHandlers['selectedOptions'] = {
6.2587 - 'init': function (element, valueAccessor, allBindingsAccessor) {
6.2588 - ko.utils.registerEventHandler(element, "change", function () {
6.2589 - var value = valueAccessor(), valueToWrite = [];
6.2590 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
6.2591 - if (node.selected)
6.2592 - valueToWrite.push(ko.selectExtensions.readValue(node));
6.2593 - });
6.2594 - ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
6.2595 - });
6.2596 - },
6.2597 - 'update': function (element, valueAccessor) {
6.2598 - if (ko.utils.tagNameLower(element) != "select")
6.2599 - throw new Error("values binding applies only to SELECT elements");
6.2600 -
6.2601 - var newValue = ko.utils.unwrapObservable(valueAccessor());
6.2602 - if (newValue && typeof newValue.length == "number") {
6.2603 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
6.2604 - var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
6.2605 - ko.utils.setOptionNodeSelectionState(node, isSelected);
6.2606 - });
6.2607 - }
6.2608 - }
6.2609 -};
6.2610 -ko.bindingHandlers['style'] = {
6.2611 - 'update': function (element, valueAccessor) {
6.2612 - var value = ko.utils.unwrapObservable(valueAccessor() || {});
6.2613 - for (var styleName in value) {
6.2614 - if (typeof styleName == "string") {
6.2615 - var styleValue = ko.utils.unwrapObservable(value[styleName]);
6.2616 - element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
6.2617 - }
6.2618 - }
6.2619 - }
6.2620 -};
6.2621 -ko.bindingHandlers['submit'] = {
6.2622 - 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
6.2623 - if (typeof valueAccessor() != "function")
6.2624 - throw new Error("The value for a submit binding must be a function");
6.2625 - ko.utils.registerEventHandler(element, "submit", function (event) {
6.2626 - var handlerReturnValue;
6.2627 - var value = valueAccessor();
6.2628 - try { handlerReturnValue = value.call(viewModel, element); }
6.2629 - finally {
6.2630 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
6.2631 - if (event.preventDefault)
6.2632 - event.preventDefault();
6.2633 - else
6.2634 - event.returnValue = false;
6.2635 - }
6.2636 - }
6.2637 - });
6.2638 - }
6.2639 -};
6.2640 -ko.bindingHandlers['text'] = {
6.2641 - 'update': function (element, valueAccessor) {
6.2642 - ko.utils.setTextContent(element, valueAccessor());
6.2643 - }
6.2644 -};
6.2645 -ko.virtualElements.allowedBindings['text'] = true;
6.2646 -ko.bindingHandlers['uniqueName'] = {
6.2647 - 'init': function (element, valueAccessor) {
6.2648 - if (valueAccessor()) {
6.2649 - var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
6.2650 - ko.utils.setElementName(element, name);
6.2651 - }
6.2652 - }
6.2653 -};
6.2654 -ko.bindingHandlers['uniqueName'].currentIndex = 0;
6.2655 -ko.bindingHandlers['value'] = {
6.2656 - 'init': function (element, valueAccessor, allBindingsAccessor) {
6.2657 - // Always catch "change" event; possibly other events too if asked
6.2658 - var eventsToCatch = ["change"];
6.2659 - var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
6.2660 - var propertyChangedFired = false;
6.2661 - if (requestedEventsToCatch) {
6.2662 - if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
6.2663 - requestedEventsToCatch = [requestedEventsToCatch];
6.2664 - ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
6.2665 - eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
6.2666 - }
6.2667 -
6.2668 - var valueUpdateHandler = function() {
6.2669 - propertyChangedFired = false;
6.2670 - var modelValue = valueAccessor();
6.2671 - var elementValue = ko.selectExtensions.readValue(element);
6.2672 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
6.2673 - }
6.2674 -
6.2675 - // Workaround for https://github.com/SteveSanderson/knockout/issues/122
6.2676 - // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
6.2677 - var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
6.2678 - && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
6.2679 - if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
6.2680 - ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
6.2681 - ko.utils.registerEventHandler(element, "blur", function() {
6.2682 - if (propertyChangedFired) {
6.2683 - valueUpdateHandler();
6.2684 - }
6.2685 - });
6.2686 - }
6.2687 -
6.2688 - ko.utils.arrayForEach(eventsToCatch, function(eventName) {
6.2689 - // The syntax "after<eventname>" means "run the handler asynchronously after the event"
6.2690 - // This is useful, for example, to catch "keydown" events after the browser has updated the control
6.2691 - // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
6.2692 - var handler = valueUpdateHandler;
6.2693 - if (ko.utils.stringStartsWith(eventName, "after")) {
6.2694 - handler = function() { setTimeout(valueUpdateHandler, 0) };
6.2695 - eventName = eventName.substring("after".length);
6.2696 - }
6.2697 - ko.utils.registerEventHandler(element, eventName, handler);
6.2698 - });
6.2699 - },
6.2700 - 'update': function (element, valueAccessor) {
6.2701 - var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
6.2702 - var newValue = ko.utils.unwrapObservable(valueAccessor());
6.2703 - var elementValue = ko.selectExtensions.readValue(element);
6.2704 - var valueHasChanged = (newValue != elementValue);
6.2705 -
6.2706 - // JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
6.2707 - // We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
6.2708 - if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
6.2709 - valueHasChanged = true;
6.2710 -
6.2711 - if (valueHasChanged) {
6.2712 - var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
6.2713 - applyValueAction();
6.2714 -
6.2715 - // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
6.2716 - // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
6.2717 - // to apply the value as well.
6.2718 - var alsoApplyAsynchronously = valueIsSelectOption;
6.2719 - if (alsoApplyAsynchronously)
6.2720 - setTimeout(applyValueAction, 0);
6.2721 - }
6.2722 -
6.2723 - // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
6.2724 - // because you're not allowed to have a model value that disagrees with a visible UI selection.
6.2725 - if (valueIsSelectOption && (element.length > 0))
6.2726 - ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
6.2727 - }
6.2728 -};
6.2729 -ko.bindingHandlers['visible'] = {
6.2730 - 'update': function (element, valueAccessor) {
6.2731 - var value = ko.utils.unwrapObservable(valueAccessor());
6.2732 - var isCurrentlyVisible = !(element.style.display == "none");
6.2733 - if (value && !isCurrentlyVisible)
6.2734 - element.style.display = "";
6.2735 - else if ((!value) && isCurrentlyVisible)
6.2736 - element.style.display = "none";
6.2737 - }
6.2738 -};
6.2739 -// 'click' is just a shorthand for the usual full-length event:{click:handler}
6.2740 -makeEventHandlerShortcut('click');
6.2741 -// If you want to make a custom template engine,
6.2742 -//
6.2743 -// [1] Inherit from this class (like ko.nativeTemplateEngine does)
6.2744 -// [2] Override 'renderTemplateSource', supplying a function with this signature:
6.2745 -//
6.2746 -// function (templateSource, bindingContext, options) {
6.2747 -// // - templateSource.text() is the text of the template you should render
6.2748 -// // - bindingContext.$data is the data you should pass into the template
6.2749 -// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
6.2750 -// // and bindingContext.$root available in the template too
6.2751 -// // - options gives you access to any other properties set on "data-bind: { template: options }"
6.2752 -// //
6.2753 -// // Return value: an array of DOM nodes
6.2754 -// }
6.2755 -//
6.2756 -// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
6.2757 -//
6.2758 -// function (script) {
6.2759 -// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
6.2760 -// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
6.2761 -// }
6.2762 -//
6.2763 -// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
6.2764 -// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
6.2765 -// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
6.2766 -
6.2767 -ko.templateEngine = function () { };
6.2768 -
6.2769 -ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
6.2770 - throw new Error("Override renderTemplateSource");
6.2771 -};
6.2772 -
6.2773 -ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
6.2774 - throw new Error("Override createJavaScriptEvaluatorBlock");
6.2775 -};
6.2776 -
6.2777 -ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
6.2778 - // Named template
6.2779 - if (typeof template == "string") {
6.2780 - templateDocument = templateDocument || document;
6.2781 - var elem = templateDocument.getElementById(template);
6.2782 - if (!elem)
6.2783 - throw new Error("Cannot find template with ID " + template);
6.2784 - return new ko.templateSources.domElement(elem);
6.2785 - } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
6.2786 - // Anonymous template
6.2787 - return new ko.templateSources.anonymousTemplate(template);
6.2788 - } else
6.2789 - throw new Error("Unknown template type: " + template);
6.2790 -};
6.2791 -
6.2792 -ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
6.2793 - var templateSource = this['makeTemplateSource'](template, templateDocument);
6.2794 - return this['renderTemplateSource'](templateSource, bindingContext, options);
6.2795 -};
6.2796 -
6.2797 -ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
6.2798 - // Skip rewriting if requested
6.2799 - if (this['allowTemplateRewriting'] === false)
6.2800 - return true;
6.2801 - return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
6.2802 -};
6.2803 -
6.2804 -ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
6.2805 - var templateSource = this['makeTemplateSource'](template, templateDocument);
6.2806 - var rewritten = rewriterCallback(templateSource['text']());
6.2807 - templateSource['text'](rewritten);
6.2808 - templateSource['data']("isRewritten", true);
6.2809 -};
6.2810 -
6.2811 -ko.exportSymbol('templateEngine', ko.templateEngine);
6.2812 -
6.2813 -ko.templateRewriting = (function () {
6.2814 - var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
6.2815 - var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
6.2816 -
6.2817 - function validateDataBindValuesForRewriting(keyValueArray) {
6.2818 - var allValidators = ko.expressionRewriting.bindingRewriteValidators;
6.2819 - for (var i = 0; i < keyValueArray.length; i++) {
6.2820 - var key = keyValueArray[i]['key'];
6.2821 - if (allValidators.hasOwnProperty(key)) {
6.2822 - var validator = allValidators[key];
6.2823 -
6.2824 - if (typeof validator === "function") {
6.2825 - var possibleErrorMessage = validator(keyValueArray[i]['value']);
6.2826 - if (possibleErrorMessage)
6.2827 - throw new Error(possibleErrorMessage);
6.2828 - } else if (!validator) {
6.2829 - throw new Error("This template engine does not support the '" + key + "' binding within its templates");
6.2830 - }
6.2831 - }
6.2832 - }
6.2833 - }
6.2834 -
6.2835 - function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
6.2836 - var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
6.2837 - validateDataBindValuesForRewriting(dataBindKeyValueArray);
6.2838 - var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
6.2839 -
6.2840 - // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
6.2841 - // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
6.2842 - // extra indirection.
6.2843 - var applyBindingsToNextSiblingScript =
6.2844 - "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
6.2845 - return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
6.2846 - }
6.2847 -
6.2848 - return {
6.2849 - ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
6.2850 - if (!templateEngine['isTemplateRewritten'](template, templateDocument))
6.2851 - templateEngine['rewriteTemplate'](template, function (htmlString) {
6.2852 - return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
6.2853 - }, templateDocument);
6.2854 - },
6.2855 -
6.2856 - memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
6.2857 - return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
6.2858 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
6.2859 - }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
6.2860 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
6.2861 - });
6.2862 - },
6.2863 -
6.2864 - applyMemoizedBindingsToNextSibling: function (bindings) {
6.2865 - return ko.memoization.memoize(function (domNode, bindingContext) {
6.2866 - if (domNode.nextSibling)
6.2867 - ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
6.2868 - });
6.2869 - }
6.2870 - }
6.2871 -})();
6.2872 -
6.2873 -
6.2874 -// Exported only because it has to be referenced by string lookup from within rewritten template
6.2875 -ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
6.2876 -(function() {
6.2877 - // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
6.2878 - // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
6.2879 - //
6.2880 - // Two are provided by default:
6.2881 - // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
6.2882 - // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
6.2883 - // without reading/writing the actual element text content, since it will be overwritten
6.2884 - // with the rendered template output.
6.2885 - // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
6.2886 - // Template sources need to have the following functions:
6.2887 - // text() - returns the template text from your storage location
6.2888 - // text(value) - writes the supplied template text to your storage location
6.2889 - // data(key) - reads values stored using data(key, value) - see below
6.2890 - // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
6.2891 - //
6.2892 - // Optionally, template sources can also have the following functions:
6.2893 - // nodes() - returns a DOM element containing the nodes of this template, where available
6.2894 - // nodes(value) - writes the given DOM element to your storage location
6.2895 - // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
6.2896 - // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
6.2897 - //
6.2898 - // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
6.2899 - // using and overriding "makeTemplateSource" to return an instance of your custom template source.
6.2900 -
6.2901 - ko.templateSources = {};
6.2902 -
6.2903 - // ---- ko.templateSources.domElement -----
6.2904 -
6.2905 - ko.templateSources.domElement = function(element) {
6.2906 - this.domElement = element;
6.2907 - }
6.2908 -
6.2909 - ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
6.2910 - var tagNameLower = ko.utils.tagNameLower(this.domElement),
6.2911 - elemContentsProperty = tagNameLower === "script" ? "text"
6.2912 - : tagNameLower === "textarea" ? "value"
6.2913 - : "innerHTML";
6.2914 -
6.2915 - if (arguments.length == 0) {
6.2916 - return this.domElement[elemContentsProperty];
6.2917 - } else {
6.2918 - var valueToWrite = arguments[0];
6.2919 - if (elemContentsProperty === "innerHTML")
6.2920 - ko.utils.setHtml(this.domElement, valueToWrite);
6.2921 - else
6.2922 - this.domElement[elemContentsProperty] = valueToWrite;
6.2923 - }
6.2924 - };
6.2925 -
6.2926 - ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
6.2927 - if (arguments.length === 1) {
6.2928 - return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
6.2929 - } else {
6.2930 - ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
6.2931 - }
6.2932 - };
6.2933 -
6.2934 - // ---- ko.templateSources.anonymousTemplate -----
6.2935 - // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
6.2936 - // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
6.2937 - // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
6.2938 -
6.2939 - var anonymousTemplatesDomDataKey = "__ko_anon_template__";
6.2940 - ko.templateSources.anonymousTemplate = function(element) {
6.2941 - this.domElement = element;
6.2942 - }
6.2943 - ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
6.2944 - ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
6.2945 - if (arguments.length == 0) {
6.2946 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
6.2947 - if (templateData.textData === undefined && templateData.containerData)
6.2948 - templateData.textData = templateData.containerData.innerHTML;
6.2949 - return templateData.textData;
6.2950 - } else {
6.2951 - var valueToWrite = arguments[0];
6.2952 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
6.2953 - }
6.2954 - };
6.2955 - ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
6.2956 - if (arguments.length == 0) {
6.2957 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
6.2958 - return templateData.containerData;
6.2959 - } else {
6.2960 - var valueToWrite = arguments[0];
6.2961 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
6.2962 - }
6.2963 - };
6.2964 -
6.2965 - ko.exportSymbol('templateSources', ko.templateSources);
6.2966 - ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
6.2967 - ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
6.2968 -})();
6.2969 -(function () {
6.2970 - var _templateEngine;
6.2971 - ko.setTemplateEngine = function (templateEngine) {
6.2972 - if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
6.2973 - throw new Error("templateEngine must inherit from ko.templateEngine");
6.2974 - _templateEngine = templateEngine;
6.2975 - }
6.2976 -
6.2977 - function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
6.2978 - var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
6.2979 - while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
6.2980 - nextInQueue = ko.virtualElements.nextSibling(node);
6.2981 - if (node.nodeType === 1 || node.nodeType === 8)
6.2982 - action(node);
6.2983 - }
6.2984 - }
6.2985 -
6.2986 - function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
6.2987 - // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
6.2988 - // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
6.2989 - // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
6.2990 - // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
6.2991 - // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
6.2992 -
6.2993 - if (continuousNodeArray.length) {
6.2994 - var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
6.2995 -
6.2996 - // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
6.2997 - // whereas a regular applyBindings won't introduce new memoized nodes
6.2998 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
6.2999 - ko.applyBindings(bindingContext, node);
6.3000 - });
6.3001 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
6.3002 - ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
6.3003 - });
6.3004 - }
6.3005 - }
6.3006 -
6.3007 - function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
6.3008 - return nodeOrNodeArray.nodeType ? nodeOrNodeArray
6.3009 - : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
6.3010 - : null;
6.3011 - }
6.3012 -
6.3013 - function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
6.3014 - options = options || {};
6.3015 - var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
6.3016 - var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
6.3017 - var templateEngineToUse = (options['templateEngine'] || _templateEngine);
6.3018 - ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
6.3019 - var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
6.3020 -
6.3021 - // Loosely check result is an array of DOM nodes
6.3022 - if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
6.3023 - throw new Error("Template engine must return an array of DOM nodes");
6.3024 -
6.3025 - var haveAddedNodesToParent = false;
6.3026 - switch (renderMode) {
6.3027 - case "replaceChildren":
6.3028 - ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
6.3029 - haveAddedNodesToParent = true;
6.3030 - break;
6.3031 - case "replaceNode":
6.3032 - ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
6.3033 - haveAddedNodesToParent = true;
6.3034 - break;
6.3035 - case "ignoreTargetNode": break;
6.3036 - default:
6.3037 - throw new Error("Unknown renderMode: " + renderMode);
6.3038 - }
6.3039 -
6.3040 - if (haveAddedNodesToParent) {
6.3041 - activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
6.3042 - if (options['afterRender'])
6.3043 - ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
6.3044 - }
6.3045 -
6.3046 - return renderedNodesArray;
6.3047 - }
6.3048 -
6.3049 - ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
6.3050 - options = options || {};
6.3051 - if ((options['templateEngine'] || _templateEngine) == undefined)
6.3052 - throw new Error("Set a template engine before calling renderTemplate");
6.3053 - renderMode = renderMode || "replaceChildren";
6.3054 -
6.3055 - if (targetNodeOrNodeArray) {
6.3056 - var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
6.3057 -
6.3058 - var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
6.3059 - var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
6.3060 -
6.3061 - return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
6.3062 - function () {
6.3063 - // Ensure we've got a proper binding context to work with
6.3064 - var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
6.3065 - ? dataOrBindingContext
6.3066 - : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
6.3067 -
6.3068 - // Support selecting template as a function of the data being rendered
6.3069 - var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
6.3070 -
6.3071 - var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
6.3072 - if (renderMode == "replaceNode") {
6.3073 - targetNodeOrNodeArray = renderedNodesArray;
6.3074 - firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
6.3075 - }
6.3076 - },
6.3077 - null,
6.3078 - { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
6.3079 - );
6.3080 - } else {
6.3081 - // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
6.3082 - return ko.memoization.memoize(function (domNode) {
6.3083 - ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
6.3084 - });
6.3085 - }
6.3086 - };
6.3087 -
6.3088 - ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
6.3089 - // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
6.3090 - // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
6.3091 - var arrayItemContext;
6.3092 -
6.3093 - // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
6.3094 - var executeTemplateForArrayItem = function (arrayValue, index) {
6.3095 - // Support selecting template as a function of the data being rendered
6.3096 - arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
6.3097 - arrayItemContext['$index'] = index;
6.3098 - var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
6.3099 - return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
6.3100 - }
6.3101 -
6.3102 - // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
6.3103 - var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
6.3104 - activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
6.3105 - if (options['afterRender'])
6.3106 - options['afterRender'](addedNodesArray, arrayValue);
6.3107 - };
6.3108 -
6.3109 - return ko.dependentObservable(function () {
6.3110 - var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
6.3111 - if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
6.3112 - unwrappedArray = [unwrappedArray];
6.3113 -
6.3114 - // Filter out any entries marked as destroyed
6.3115 - var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
6.3116 - return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
6.3117 - });
6.3118 -
6.3119 - // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
6.3120 - // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
6.3121 - ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
6.3122 -
6.3123 - }, null, { disposeWhenNodeIsRemoved: targetNode });
6.3124 - };
6.3125 -
6.3126 - var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
6.3127 - function disposeOldComputedAndStoreNewOne(element, newComputed) {
6.3128 - var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
6.3129 - if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
6.3130 - oldComputed.dispose();
6.3131 - ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
6.3132 - }
6.3133 -
6.3134 - ko.bindingHandlers['template'] = {
6.3135 - 'init': function(element, valueAccessor) {
6.3136 - // Support anonymous templates
6.3137 - var bindingValue = ko.utils.unwrapObservable(valueAccessor());
6.3138 - if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
6.3139 - // It's an anonymous template - store the element contents, then clear the element
6.3140 - var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
6.3141 - container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
6.3142 - new ko.templateSources.anonymousTemplate(element)['nodes'](container);
6.3143 - }
6.3144 - return { 'controlsDescendantBindings': true };
6.3145 - },
6.3146 - 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.3147 - var templateName = ko.utils.unwrapObservable(valueAccessor()),
6.3148 - options = {},
6.3149 - shouldDisplay = true,
6.3150 - dataValue,
6.3151 - templateComputed = null;
6.3152 -
6.3153 - if (typeof templateName != "string") {
6.3154 - options = templateName;
6.3155 - templateName = options['name'];
6.3156 -
6.3157 - // Support "if"/"ifnot" conditions
6.3158 - if ('if' in options)
6.3159 - shouldDisplay = ko.utils.unwrapObservable(options['if']);
6.3160 - if (shouldDisplay && 'ifnot' in options)
6.3161 - shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
6.3162 -
6.3163 - dataValue = ko.utils.unwrapObservable(options['data']);
6.3164 - }
6.3165 -
6.3166 - if ('foreach' in options) {
6.3167 - // Render once for each data point (treating data set as empty if shouldDisplay==false)
6.3168 - var dataArray = (shouldDisplay && options['foreach']) || [];
6.3169 - templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
6.3170 - } else if (!shouldDisplay) {
6.3171 - ko.virtualElements.emptyNode(element);
6.3172 - } else {
6.3173 - // Render once for this single data point (or use the viewModel if no data was provided)
6.3174 - var innerBindingContext = ('data' in options) ?
6.3175 - bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
6.3176 - bindingContext; // Given no explicit 'data' value, we retain the same binding context
6.3177 - templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
6.3178 - }
6.3179 -
6.3180 - // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
6.3181 - disposeOldComputedAndStoreNewOne(element, templateComputed);
6.3182 - }
6.3183 - };
6.3184 -
6.3185 - // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
6.3186 - ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
6.3187 - var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
6.3188 -
6.3189 - if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
6.3190 - return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
6.3191 -
6.3192 - if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
6.3193 - return null; // Named templates can be rewritten, so return "no error"
6.3194 - return "This template engine does not support anonymous templates nested within its templates";
6.3195 - };
6.3196 -
6.3197 - ko.virtualElements.allowedBindings['template'] = true;
6.3198 -})();
6.3199 -
6.3200 -ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
6.3201 -ko.exportSymbol('renderTemplate', ko.renderTemplate);
6.3202 -
6.3203 -ko.utils.compareArrays = (function () {
6.3204 - var statusNotInOld = 'added', statusNotInNew = 'deleted';
6.3205 -
6.3206 - // Simple calculation based on Levenshtein distance.
6.3207 - function compareArrays(oldArray, newArray, dontLimitMoves) {
6.3208 - oldArray = oldArray || [];
6.3209 - newArray = newArray || [];
6.3210 -
6.3211 - if (oldArray.length <= newArray.length)
6.3212 - return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
6.3213 - else
6.3214 - return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
6.3215 - }
6.3216 -
6.3217 - function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
6.3218 - var myMin = Math.min,
6.3219 - myMax = Math.max,
6.3220 - editDistanceMatrix = [],
6.3221 - smlIndex, smlIndexMax = smlArray.length,
6.3222 - bigIndex, bigIndexMax = bigArray.length,
6.3223 - compareRange = (bigIndexMax - smlIndexMax) || 1,
6.3224 - maxDistance = smlIndexMax + bigIndexMax + 1,
6.3225 - thisRow, lastRow,
6.3226 - bigIndexMaxForRow, bigIndexMinForRow;
6.3227 -
6.3228 - for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
6.3229 - lastRow = thisRow;
6.3230 - editDistanceMatrix.push(thisRow = []);
6.3231 - bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
6.3232 - bigIndexMinForRow = myMax(0, smlIndex - 1);
6.3233 - for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
6.3234 - if (!bigIndex)
6.3235 - thisRow[bigIndex] = smlIndex + 1;
6.3236 - else if (!smlIndex) // Top row - transform empty array into new array via additions
6.3237 - thisRow[bigIndex] = bigIndex + 1;
6.3238 - else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
6.3239 - thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
6.3240 - else {
6.3241 - var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
6.3242 - var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
6.3243 - thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
6.3244 - }
6.3245 - }
6.3246 - }
6.3247 -
6.3248 - var editScript = [], meMinusOne, notInSml = [], notInBig = [];
6.3249 - for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
6.3250 - meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
6.3251 - if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
6.3252 - notInSml.push(editScript[editScript.length] = { // added
6.3253 - 'status': statusNotInSml,
6.3254 - 'value': bigArray[--bigIndex],
6.3255 - 'index': bigIndex });
6.3256 - } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
6.3257 - notInBig.push(editScript[editScript.length] = { // deleted
6.3258 - 'status': statusNotInBig,
6.3259 - 'value': smlArray[--smlIndex],
6.3260 - 'index': smlIndex });
6.3261 - } else {
6.3262 - editScript.push({
6.3263 - 'status': "retained",
6.3264 - 'value': bigArray[--bigIndex] });
6.3265 - --smlIndex;
6.3266 - }
6.3267 - }
6.3268 -
6.3269 - if (notInSml.length && notInBig.length) {
6.3270 - // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
6.3271 - // smlIndexMax keeps the time complexity of this algorithm linear.
6.3272 - var limitFailedCompares = smlIndexMax * 10, failedCompares,
6.3273 - a, d, notInSmlItem, notInBigItem;
6.3274 - // Go through the items that have been added and deleted and try to find matches between them.
6.3275 - for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
6.3276 - for (d = 0; notInBigItem = notInBig[d]; d++) {
6.3277 - if (notInSmlItem['value'] === notInBigItem['value']) {
6.3278 - notInSmlItem['moved'] = notInBigItem['index'];
6.3279 - notInBigItem['moved'] = notInSmlItem['index'];
6.3280 - notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
6.3281 - failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
6.3282 - break;
6.3283 - }
6.3284 - }
6.3285 - failedCompares += d;
6.3286 - }
6.3287 - }
6.3288 - return editScript.reverse();
6.3289 - }
6.3290 -
6.3291 - return compareArrays;
6.3292 -})();
6.3293 -
6.3294 -ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
6.3295 -
6.3296 -(function () {
6.3297 - // Objective:
6.3298 - // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
6.3299 - // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
6.3300 - // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
6.3301 - // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
6.3302 - // previously mapped - retain those nodes, and just insert/delete other ones
6.3303 -
6.3304 - // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
6.3305 - // You can use this, for example, to activate bindings on those nodes.
6.3306 -
6.3307 - function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
6.3308 - // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
6.3309 - // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
6.3310 - // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
6.3311 - // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
6.3312 - // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
6.3313 - //
6.3314 - // Rules:
6.3315 - // [A] Any leading nodes that aren't in the document any more should be ignored
6.3316 - // These most likely correspond to memoization nodes that were already removed during binding
6.3317 - // See https://github.com/SteveSanderson/knockout/pull/440
6.3318 - // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
6.3319 - // have already been removed, and include any nodes that have been inserted among the previous collection
6.3320 -
6.3321 - // Rule [A]
6.3322 - while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
6.3323 - contiguousNodeArray.splice(0, 1);
6.3324 -
6.3325 - // Rule [B]
6.3326 - if (contiguousNodeArray.length > 1) {
6.3327 - // Build up the actual new contiguous node set
6.3328 - var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
6.3329 - while (current !== last) {
6.3330 - current = current.nextSibling;
6.3331 - if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
6.3332 - return;
6.3333 - newContiguousSet.push(current);
6.3334 - }
6.3335 -
6.3336 - // ... then mutate the input array to match this.
6.3337 - // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
6.3338 - Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
6.3339 - }
6.3340 - return contiguousNodeArray;
6.3341 - }
6.3342 -
6.3343 - function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
6.3344 - // Map this array value inside a dependentObservable so we re-map when any dependency changes
6.3345 - var mappedNodes = [];
6.3346 - var dependentObservable = ko.dependentObservable(function() {
6.3347 - var newMappedNodes = mapping(valueToMap, index) || [];
6.3348 -
6.3349 - // On subsequent evaluations, just replace the previously-inserted DOM nodes
6.3350 - if (mappedNodes.length > 0) {
6.3351 - ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
6.3352 - if (callbackAfterAddingNodes)
6.3353 - ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
6.3354 - }
6.3355 -
6.3356 - // Replace the contents of the mappedNodes array, thereby updating the record
6.3357 - // of which nodes would be deleted if valueToMap was itself later removed
6.3358 - mappedNodes.splice(0, mappedNodes.length);
6.3359 - ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
6.3360 - }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
6.3361 - return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
6.3362 - }
6.3363 -
6.3364 - var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
6.3365 -
6.3366 - ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
6.3367 - // Compare the provided array against the previous one
6.3368 - array = array || [];
6.3369 - options = options || {};
6.3370 - var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
6.3371 - var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
6.3372 - var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
6.3373 - var editScript = ko.utils.compareArrays(lastArray, array);
6.3374 -
6.3375 - // Build the new mapping result
6.3376 - var newMappingResult = [];
6.3377 - var lastMappingResultIndex = 0;
6.3378 - var newMappingResultIndex = 0;
6.3379 -
6.3380 - var nodesToDelete = [];
6.3381 - var itemsToProcess = [];
6.3382 - var itemsForBeforeRemoveCallbacks = [];
6.3383 - var itemsForMoveCallbacks = [];
6.3384 - var itemsForAfterAddCallbacks = [];
6.3385 - var mapData;
6.3386 -
6.3387 - function itemMovedOrRetained(editScriptIndex, oldPosition) {
6.3388 - mapData = lastMappingResult[oldPosition];
6.3389 - if (newMappingResultIndex !== oldPosition)
6.3390 - itemsForMoveCallbacks[editScriptIndex] = mapData;
6.3391 - // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
6.3392 - mapData.indexObservable(newMappingResultIndex++);
6.3393 - fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
6.3394 - newMappingResult.push(mapData);
6.3395 - itemsToProcess.push(mapData);
6.3396 - }
6.3397 -
6.3398 - function callCallback(callback, items) {
6.3399 - if (callback) {
6.3400 - for (var i = 0, n = items.length; i < n; i++) {
6.3401 - if (items[i]) {
6.3402 - ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
6.3403 - callback(node, i, items[i].arrayEntry);
6.3404 - });
6.3405 - }
6.3406 - }
6.3407 - }
6.3408 - }
6.3409 -
6.3410 - for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
6.3411 - movedIndex = editScriptItem['moved'];
6.3412 - switch (editScriptItem['status']) {
6.3413 - case "deleted":
6.3414 - if (movedIndex === undefined) {
6.3415 - mapData = lastMappingResult[lastMappingResultIndex];
6.3416 -
6.3417 - // Stop tracking changes to the mapping for these nodes
6.3418 - if (mapData.dependentObservable)
6.3419 - mapData.dependentObservable.dispose();
6.3420 -
6.3421 - // Queue these nodes for later removal
6.3422 - nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
6.3423 - if (options['beforeRemove']) {
6.3424 - itemsForBeforeRemoveCallbacks[i] = mapData;
6.3425 - itemsToProcess.push(mapData);
6.3426 - }
6.3427 - }
6.3428 - lastMappingResultIndex++;
6.3429 - break;
6.3430 -
6.3431 - case "retained":
6.3432 - itemMovedOrRetained(i, lastMappingResultIndex++);
6.3433 - break;
6.3434 -
6.3435 - case "added":
6.3436 - if (movedIndex !== undefined) {
6.3437 - itemMovedOrRetained(i, movedIndex);
6.3438 - } else {
6.3439 - mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
6.3440 - newMappingResult.push(mapData);
6.3441 - itemsToProcess.push(mapData);
6.3442 - if (!isFirstExecution)
6.3443 - itemsForAfterAddCallbacks[i] = mapData;
6.3444 - }
6.3445 - break;
6.3446 - }
6.3447 - }
6.3448 -
6.3449 - // Call beforeMove first before any changes have been made to the DOM
6.3450 - callCallback(options['beforeMove'], itemsForMoveCallbacks);
6.3451 -
6.3452 - // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
6.3453 - ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
6.3454 -
6.3455 - // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
6.3456 - for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
6.3457 - // Get nodes for newly added items
6.3458 - if (!mapData.mappedNodes)
6.3459 - ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
6.3460 -
6.3461 - // Put nodes in the right place if they aren't there already
6.3462 - for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
6.3463 - if (node !== nextNode)
6.3464 - ko.virtualElements.insertAfter(domNode, node, lastNode);
6.3465 - }
6.3466 -
6.3467 - // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
6.3468 - if (!mapData.initialized && callbackAfterAddingNodes) {
6.3469 - callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
6.3470 - mapData.initialized = true;
6.3471 - }
6.3472 - }
6.3473 -
6.3474 - // If there's a beforeRemove callback, call it after reordering.
6.3475 - // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
6.3476 - // some sort of animation, which is why we first reorder the nodes that will be removed. If the
6.3477 - // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
6.3478 - // Perhaps we'll make that change in the future if this scenario becomes more common.
6.3479 - callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
6.3480 -
6.3481 - // Finally call afterMove and afterAdd callbacks
6.3482 - callCallback(options['afterMove'], itemsForMoveCallbacks);
6.3483 - callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
6.3484 -
6.3485 - // Store a copy of the array items we just considered so we can difference it next time
6.3486 - ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
6.3487 - }
6.3488 -})();
6.3489 -
6.3490 -ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
6.3491 -ko.nativeTemplateEngine = function () {
6.3492 - this['allowTemplateRewriting'] = false;
6.3493 -}
6.3494 -
6.3495 -ko.nativeTemplateEngine.prototype = new ko.templateEngine();
6.3496 -ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
6.3497 - var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
6.3498 - templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
6.3499 - templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
6.3500 -
6.3501 - if (templateNodes) {
6.3502 - return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
6.3503 - } else {
6.3504 - var templateText = templateSource['text']();
6.3505 - return ko.utils.parseHtmlFragment(templateText);
6.3506 - }
6.3507 -};
6.3508 -
6.3509 -ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
6.3510 -ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
6.3511 -
6.3512 -ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
6.3513 -(function() {
6.3514 - ko.jqueryTmplTemplateEngine = function () {
6.3515 - // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
6.3516 - // doesn't expose a version number, so we have to infer it.
6.3517 - // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
6.3518 - // which KO internally refers to as version "2", so older versions are no longer detected.
6.3519 - var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
6.3520 - if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
6.3521 - return 0;
6.3522 - // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
6.3523 - try {
6.3524 - if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
6.3525 - // Since 1.0.0pre, custom tags should append markup to an array called "__"
6.3526 - return 2; // Final version of jquery.tmpl
6.3527 - }
6.3528 - } catch(ex) { /* Apparently not the version we were looking for */ }
6.3529 -
6.3530 - return 1; // Any older version that we don't support
6.3531 - })();
6.3532 -
6.3533 - function ensureHasReferencedJQueryTemplates() {
6.3534 - if (jQueryTmplVersion < 2)
6.3535 - throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
6.3536 - }
6.3537 -
6.3538 - function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
6.3539 - return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
6.3540 - }
6.3541 -
6.3542 - this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
6.3543 - options = options || {};
6.3544 - ensureHasReferencedJQueryTemplates();
6.3545 -
6.3546 - // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
6.3547 - var precompiled = templateSource['data']('precompiled');
6.3548 - if (!precompiled) {
6.3549 - var templateText = templateSource['text']() || "";
6.3550 - // Wrap in "with($whatever.koBindingContext) { ... }"
6.3551 - templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
6.3552 -
6.3553 - precompiled = jQuery['template'](null, templateText);
6.3554 - templateSource['data']('precompiled', precompiled);
6.3555 - }
6.3556 -
6.3557 - var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
6.3558 - var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
6.3559 -
6.3560 - var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
6.3561 - resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
6.3562 -
6.3563 - jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
6.3564 - return resultNodes;
6.3565 - };
6.3566 -
6.3567 - this['createJavaScriptEvaluatorBlock'] = function(script) {
6.3568 - return "{{ko_code ((function() { return " + script + " })()) }}";
6.3569 - };
6.3570 -
6.3571 - this['addTemplate'] = function(templateName, templateMarkup) {
6.3572 - document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
6.3573 - };
6.3574 -
6.3575 - if (jQueryTmplVersion > 0) {
6.3576 - jQuery['tmpl']['tag']['ko_code'] = {
6.3577 - open: "__.push($1 || '');"
6.3578 - };
6.3579 - jQuery['tmpl']['tag']['ko_with'] = {
6.3580 - open: "with($1) {",
6.3581 - close: "} "
6.3582 - };
6.3583 - }
6.3584 - };
6.3585 -
6.3586 - ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
6.3587 -
6.3588 - // Use this one by default *only if jquery.tmpl is referenced*
6.3589 - var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
6.3590 - if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
6.3591 - ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
6.3592 -
6.3593 - ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
6.3594 -})();
6.3595 -});
6.3596 -})(window,document,navigator,window["jQuery"]);
6.3597 -})();
6.3598 \ No newline at end of file
7.1 --- a/ko-fx/src/test/java/org/netbeans/html/kofx/DynamicHTTP.java Thu Jan 09 11:53:46 2014 +0100
7.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
7.3 @@ -1,259 +0,0 @@
7.4 -/**
7.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
7.6 - *
7.7 - * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
7.8 - *
7.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7.10 - * Other names may be trademarks of their respective owners.
7.11 - *
7.12 - * The contents of this file are subject to the terms of either the GNU
7.13 - * General Public License Version 2 only ("GPL") or the Common
7.14 - * Development and Distribution License("CDDL") (collectively, the
7.15 - * "License"). You may not use this file except in compliance with the
7.16 - * License. You can obtain a copy of the License at
7.17 - * http://www.netbeans.org/cddl-gplv2.html
7.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
7.19 - * specific language governing permissions and limitations under the
7.20 - * License. When distributing the software, include this License Header
7.21 - * Notice in each file and include the License file at
7.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
7.23 - * particular file as subject to the "Classpath" exception as provided
7.24 - * by Oracle in the GPL Version 2 section of the License file that
7.25 - * accompanied this code. If applicable, add the following below the
7.26 - * License Header, with the fields enclosed by brackets [] replaced by
7.27 - * your own identifying information:
7.28 - * "Portions Copyrighted [year] [name of copyright owner]"
7.29 - *
7.30 - * Contributor(s):
7.31 - *
7.32 - * The Original Software is NetBeans. The Initial Developer of the Original
7.33 - * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
7.34 - *
7.35 - * If you wish your version of this file to be governed by only the CDDL
7.36 - * or only the GPL Version 2, indicate your decision by adding
7.37 - * "[Contributor] elects to include this software in this distribution
7.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
7.39 - * single choice of license, a recipient has the option to distribute
7.40 - * your version of this file under either the CDDL, the GPL Version 2 or
7.41 - * to extend the choice of license to its licensees as provided above.
7.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
7.43 - * Version 2 license, then the option applies only if the new code is
7.44 - * made subject to such option by the copyright holder.
7.45 - */
7.46 -package org.netbeans.html.kofx;
7.47 -
7.48 -import java.io.ByteArrayInputStream;
7.49 -import java.io.ByteArrayOutputStream;
7.50 -import java.io.IOException;
7.51 -import java.io.InputStream;
7.52 -import java.io.OutputStream;
7.53 -import java.io.Reader;
7.54 -import java.net.URI;
7.55 -import java.net.URISyntaxException;
7.56 -import java.util.ArrayList;
7.57 -import java.util.List;
7.58 -import java.util.logging.Level;
7.59 -import java.util.logging.Logger;
7.60 -import org.glassfish.grizzly.PortRange;
7.61 -import org.glassfish.grizzly.http.server.HttpHandler;
7.62 -import org.glassfish.grizzly.http.server.HttpServer;
7.63 -import org.glassfish.grizzly.http.server.NetworkListener;
7.64 -import org.glassfish.grizzly.http.server.Request;
7.65 -import org.glassfish.grizzly.http.server.Response;
7.66 -import org.glassfish.grizzly.http.server.ServerConfiguration;
7.67 -import org.glassfish.grizzly.websockets.WebSocket;
7.68 -import org.glassfish.grizzly.websockets.WebSocketAddOn;
7.69 -import org.glassfish.grizzly.websockets.WebSocketApplication;
7.70 -import org.glassfish.grizzly.websockets.WebSocketEngine;
7.71 -
7.72 -/**
7.73 - *
7.74 - * @author Jaroslav Tulach <jtulach@netbeans.org>
7.75 - */
7.76 -final class DynamicHTTP extends HttpHandler {
7.77 - private static final Logger LOG = Logger.getLogger(DynamicHTTP.class.getName());
7.78 - private static int resourcesCount;
7.79 - private static List<Resource> resources;
7.80 - private static ServerConfiguration conf;
7.81 - private static HttpServer server;
7.82 -
7.83 - private DynamicHTTP() {
7.84 - }
7.85 -
7.86 - static URI initServer() throws Exception {
7.87 - server = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
7.88 - final WebSocketAddOn addon = new WebSocketAddOn();
7.89 - for (NetworkListener listener : server.getListeners()) {
7.90 - listener.registerAddOn(addon);
7.91 - }
7.92 - resources = new ArrayList<Resource>();
7.93 -
7.94 - conf = server.getServerConfiguration();
7.95 - final DynamicHTTP dh = new DynamicHTTP();
7.96 -
7.97 - conf.addHttpHandler(dh, "/");
7.98 -
7.99 - server.start();
7.100 -
7.101 - return pageURL("http", server, "/test.html");
7.102 - }
7.103 -
7.104 - @Override
7.105 - public void service(Request request, Response response) throws Exception {
7.106 - if ("/test.html".equals(request.getRequestURI())) {
7.107 - response.setContentType("text/html");
7.108 - final InputStream is = DynamicHTTP.class.getResourceAsStream("test.html");
7.109 - copyStream(is, response.getOutputStream(), null);
7.110 - return;
7.111 - }
7.112 - if ("/dynamic".equals(request.getRequestURI())) {
7.113 - String mimeType = request.getParameter("mimeType");
7.114 - List<String> params = new ArrayList<String>();
7.115 - boolean webSocket = false;
7.116 - for (int i = 0;; i++) {
7.117 - String p = request.getParameter("param" + i);
7.118 - if (p == null) {
7.119 - break;
7.120 - }
7.121 - if ("protocol:ws".equals(p)) {
7.122 - webSocket = true;
7.123 - continue;
7.124 - }
7.125 - params.add(p);
7.126 - }
7.127 - final String cnt = request.getParameter("content");
7.128 - String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
7.129 - ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
7.130 - URI url;
7.131 - final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
7.132 - if (webSocket) {
7.133 - url = registerWebSocket(res);
7.134 - } else {
7.135 - url = registerResource(res);
7.136 - }
7.137 - response.getWriter().write(url.toString());
7.138 - response.getWriter().write("\n");
7.139 - return;
7.140 - }
7.141 -
7.142 - for (Resource r : resources) {
7.143 - if (r.httpPath.equals(request.getRequestURI())) {
7.144 - response.setContentType(r.httpType);
7.145 - r.httpContent.reset();
7.146 - String[] params = null;
7.147 - if (r.parameters.length != 0) {
7.148 - params = new String[r.parameters.length];
7.149 - for (int i = 0; i < r.parameters.length; i++) {
7.150 - params[i] = request.getParameter(r.parameters[i]);
7.151 - if (params[i] == null) {
7.152 - if ("http.method".equals(r.parameters[i])) {
7.153 - params[i] = request.getMethod().toString();
7.154 - } else if ("http.requestBody".equals(r.parameters[i])) {
7.155 - Reader rdr = request.getReader();
7.156 - StringBuilder sb = new StringBuilder();
7.157 - for (;;) {
7.158 - int ch = rdr.read();
7.159 - if (ch == -1) {
7.160 - break;
7.161 - }
7.162 - sb.append((char) ch);
7.163 - }
7.164 - params[i] = sb.toString();
7.165 - }
7.166 - }
7.167 - if (params[i] == null) {
7.168 - params[i] = "null";
7.169 - }
7.170 - }
7.171 - }
7.172 -
7.173 - copyStream(r.httpContent, response.getOutputStream(), null, params);
7.174 - }
7.175 - }
7.176 - }
7.177 -
7.178 - private URI registerWebSocket(Resource r) {
7.179 - WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
7.180 - return pageURL("ws", server, r.httpPath);
7.181 - }
7.182 -
7.183 - private URI registerResource(Resource r) {
7.184 - if (!resources.contains(r)) {
7.185 - resources.add(r);
7.186 - conf.addHttpHandler(this, r.httpPath);
7.187 - }
7.188 - return pageURL("http", server, r.httpPath);
7.189 - }
7.190 -
7.191 - private static URI pageURL(String proto, HttpServer server, final String page) {
7.192 - NetworkListener listener = server.getListeners().iterator().next();
7.193 - int port = listener.getPort();
7.194 - try {
7.195 - return new URI(proto + "://localhost:" + port + page);
7.196 - } catch (URISyntaxException ex) {
7.197 - throw new IllegalStateException(ex);
7.198 - }
7.199 - }
7.200 -
7.201 - static final class Resource {
7.202 -
7.203 - final InputStream httpContent;
7.204 - final String httpType;
7.205 - final String httpPath;
7.206 - final String[] parameters;
7.207 -
7.208 - Resource(InputStream httpContent, String httpType, String httpPath,
7.209 - String[] parameters) {
7.210 - httpContent.mark(Integer.MAX_VALUE);
7.211 - this.httpContent = httpContent;
7.212 - this.httpType = httpType;
7.213 - this.httpPath = httpPath;
7.214 - this.parameters = parameters;
7.215 - }
7.216 - }
7.217 -
7.218 - static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
7.219 - for (;;) {
7.220 - int ch = is.read();
7.221 - if (ch == -1) {
7.222 - break;
7.223 - }
7.224 - if (ch == '$' && params.length > 0) {
7.225 - int cnt = is.read() - '0';
7.226 - if (baseURL != null && cnt == 'U' - '0') {
7.227 - os.write(baseURL.getBytes("UTF-8"));
7.228 - } else {
7.229 - if (cnt >= 0 && cnt < params.length) {
7.230 - os.write(params[cnt].getBytes("UTF-8"));
7.231 - } else {
7.232 - os.write('$');
7.233 - os.write(cnt + '0');
7.234 - }
7.235 - }
7.236 - } else {
7.237 - os.write(ch);
7.238 - }
7.239 - }
7.240 - }
7.241 -
7.242 - private static class WS extends WebSocketApplication {
7.243 - private final Resource r;
7.244 -
7.245 - private WS(Resource r) {
7.246 - this.r = r;
7.247 - }
7.248 -
7.249 - @Override
7.250 - public void onMessage(WebSocket socket, String text) {
7.251 - try {
7.252 - r.httpContent.reset();
7.253 - ByteArrayOutputStream out = new ByteArrayOutputStream();
7.254 - copyStream(r.httpContent, out, null, text);
7.255 - String s = new String(out.toByteArray(), "UTF-8");
7.256 - socket.send(s);
7.257 - } catch (IOException ex) {
7.258 - LOG.log(Level.WARNING, "Error processing message " + text, ex);
7.259 - }
7.260 - }
7.261 - }
7.262 -}
8.1 --- a/ko-fx/src/test/java/org/netbeans/html/kofx/KOFx.java Thu Jan 09 11:53:46 2014 +0100
8.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
8.3 @@ -1,118 +0,0 @@
8.4 -/**
8.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
8.6 - *
8.7 - * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
8.8 - *
8.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
8.10 - * Other names may be trademarks of their respective owners.
8.11 - *
8.12 - * The contents of this file are subject to the terms of either the GNU
8.13 - * General Public License Version 2 only ("GPL") or the Common
8.14 - * Development and Distribution License("CDDL") (collectively, the
8.15 - * "License"). You may not use this file except in compliance with the
8.16 - * License. You can obtain a copy of the License at
8.17 - * http://www.netbeans.org/cddl-gplv2.html
8.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
8.19 - * specific language governing permissions and limitations under the
8.20 - * License. When distributing the software, include this License Header
8.21 - * Notice in each file and include the License file at
8.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
8.23 - * particular file as subject to the "Classpath" exception as provided
8.24 - * by Oracle in the GPL Version 2 section of the License file that
8.25 - * accompanied this code. If applicable, add the following below the
8.26 - * License Header, with the fields enclosed by brackets [] replaced by
8.27 - * your own identifying information:
8.28 - * "Portions Copyrighted [year] [name of copyright owner]"
8.29 - *
8.30 - * Contributor(s):
8.31 - *
8.32 - * The Original Software is NetBeans. The Initial Developer of the Original
8.33 - * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
8.34 - *
8.35 - * If you wish your version of this file to be governed by only the CDDL
8.36 - * or only the GPL Version 2, indicate your decision by adding
8.37 - * "[Contributor] elects to include this software in this distribution
8.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
8.39 - * single choice of license, a recipient has the option to distribute
8.40 - * your version of this file under either the CDDL, the GPL Version 2 or
8.41 - * to extend the choice of license to its licensees as provided above.
8.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
8.43 - * Version 2 license, then the option applies only if the new code is
8.44 - * made subject to such option by the copyright holder.
8.45 - */
8.46 -package org.netbeans.html.kofx;
8.47 -
8.48 -import java.io.Closeable;
8.49 -import java.lang.reflect.InvocationTargetException;
8.50 -import java.lang.reflect.Method;
8.51 -import javafx.application.Platform;
8.52 -import org.apidesign.html.boot.spi.Fn;
8.53 -import org.testng.ITest;
8.54 -import org.testng.annotations.Test;
8.55 -
8.56 -/**
8.57 - *
8.58 - * @author Jaroslav Tulach <jtulach@netbeans.org>
8.59 - */
8.60 -public final class KOFx implements ITest, Runnable {
8.61 - private final Fn.Presenter p;
8.62 - private final Method m;
8.63 - private Object result;
8.64 - private Object inst;
8.65 - private int count;
8.66 -
8.67 - KOFx(Fn.Presenter p, Method m) {
8.68 - this.p = p;
8.69 - this.m = m;
8.70 - }
8.71 -
8.72 - @Override
8.73 - public String getTestName() {
8.74 - return m.getName();
8.75 - }
8.76 -
8.77 - @Test
8.78 - public synchronized void executeTest() throws Exception {
8.79 - if (result == null) {
8.80 - Platform.runLater(this);
8.81 - wait();
8.82 - }
8.83 - if (result instanceof Exception) {
8.84 - throw (Exception)result;
8.85 - }
8.86 - if (result instanceof Error) {
8.87 - throw (Error)result;
8.88 - }
8.89 - }
8.90 -
8.91 - @Override
8.92 - public synchronized void run() {
8.93 - boolean notify = true;
8.94 - try (Closeable a = Fn.activate(p)) {
8.95 - if (inst == null) {
8.96 - inst = m.getDeclaringClass().newInstance();
8.97 - }
8.98 - result = m.invoke(inst);
8.99 - if (result == null) {
8.100 - result = this;
8.101 - }
8.102 - } catch (InvocationTargetException ex) {
8.103 - Throwable r = ex.getTargetException();
8.104 - if (r instanceof InterruptedException) {
8.105 - if (count++ < 10000) {
8.106 - notify = false;
8.107 - Platform.runLater(this);
8.108 - return;
8.109 - }
8.110 - }
8.111 - result = r;
8.112 - } catch (Exception ex) {
8.113 - result = ex;
8.114 - } finally {
8.115 - if (notify) {
8.116 - notifyAll();
8.117 - }
8.118 - }
8.119 - }
8.120 -
8.121 -}
9.1 --- a/ko-fx/src/test/java/org/netbeans/html/kofx/KnockoutFXTest.java Thu Jan 09 11:53:46 2014 +0100
9.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
9.3 @@ -1,229 +0,0 @@
9.4 -/**
9.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
9.6 - *
9.7 - * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
9.8 - *
9.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
9.10 - * Other names may be trademarks of their respective owners.
9.11 - *
9.12 - * The contents of this file are subject to the terms of either the GNU
9.13 - * General Public License Version 2 only ("GPL") or the Common
9.14 - * Development and Distribution License("CDDL") (collectively, the
9.15 - * "License"). You may not use this file except in compliance with the
9.16 - * License. You can obtain a copy of the License at
9.17 - * http://www.netbeans.org/cddl-gplv2.html
9.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
9.19 - * specific language governing permissions and limitations under the
9.20 - * License. When distributing the software, include this License Header
9.21 - * Notice in each file and include the License file at
9.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
9.23 - * particular file as subject to the "Classpath" exception as provided
9.24 - * by Oracle in the GPL Version 2 section of the License file that
9.25 - * accompanied this code. If applicable, add the following below the
9.26 - * License Header, with the fields enclosed by brackets [] replaced by
9.27 - * your own identifying information:
9.28 - * "Portions Copyrighted [year] [name of copyright owner]"
9.29 - *
9.30 - * Contributor(s):
9.31 - *
9.32 - * The Original Software is NetBeans. The Initial Developer of the Original
9.33 - * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
9.34 - *
9.35 - * If you wish your version of this file to be governed by only the CDDL
9.36 - * or only the GPL Version 2, indicate your decision by adding
9.37 - * "[Contributor] elects to include this software in this distribution
9.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
9.39 - * single choice of license, a recipient has the option to distribute
9.40 - * your version of this file under either the CDDL, the GPL Version 2 or
9.41 - * to extend the choice of license to its licensees as provided above.
9.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
9.43 - * Version 2 license, then the option applies only if the new code is
9.44 - * made subject to such option by the copyright holder.
9.45 - */
9.46 -package org.netbeans.html.kofx;
9.47 -
9.48 -import java.io.BufferedReader;
9.49 -import java.io.IOException;
9.50 -import java.io.InputStreamReader;
9.51 -import java.lang.annotation.Annotation;
9.52 -import java.lang.reflect.Method;
9.53 -import java.net.URI;
9.54 -import java.net.URISyntaxException;
9.55 -import java.net.URL;
9.56 -import java.net.URLConnection;
9.57 -import java.util.ArrayList;
9.58 -import java.util.List;
9.59 -import java.util.Map;
9.60 -import java.util.concurrent.Executors;
9.61 -import net.java.html.BrwsrCtx;
9.62 -import net.java.html.boot.BrowserBuilder;
9.63 -import net.java.html.js.JavaScriptBody;
9.64 -import org.netbeans.html.boot.impl.FnContext;
9.65 -import org.apidesign.html.boot.spi.Fn;
9.66 -import org.apidesign.html.context.spi.Contexts;
9.67 -import org.apidesign.html.json.spi.Technology;
9.68 -import org.apidesign.html.json.spi.Transfer;
9.69 -import org.apidesign.html.json.spi.WSTransfer;
9.70 -import org.apidesign.html.json.tck.KOTest;
9.71 -import org.apidesign.html.json.tck.KnockoutTCK;
9.72 -import org.json.JSONException;
9.73 -import org.json.JSONObject;
9.74 -import org.openide.util.lookup.ServiceProvider;
9.75 -import org.testng.annotations.Factory;
9.76 -import static org.testng.Assert.*;
9.77 -
9.78 -/**
9.79 - *
9.80 - * @author Jaroslav Tulach <jtulach@netbeans.org>
9.81 - */
9.82 -@ServiceProvider(service = KnockoutTCK.class)
9.83 -public final class KnockoutFXTest extends KnockoutTCK {
9.84 - private static Class<?> browserClass;
9.85 - private static Fn.Presenter browserContext;
9.86 -
9.87 - public KnockoutFXTest() {
9.88 - }
9.89 -
9.90 - @Factory public static Object[] compatibilityTests() throws Exception {
9.91 - Class[] arr = testClasses();
9.92 - for (int i = 0; i < arr.length; i++) {
9.93 - assertEquals(
9.94 - arr[i].getClassLoader(),
9.95 - KnockoutFXTest.class.getClassLoader(),
9.96 - "All classes loaded by the same classloader"
9.97 - );
9.98 - }
9.99 -
9.100 - URI uri = DynamicHTTP.initServer();
9.101 -
9.102 - final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(KnockoutFXTest.class).
9.103 - loadPage(uri.toString()).
9.104 - invoke("initialized");
9.105 -
9.106 - Executors.newSingleThreadExecutor().submit(new Runnable() {
9.107 - @Override
9.108 - public void run() {
9.109 - bb.showAndWait();
9.110 - }
9.111 - });
9.112 -
9.113 - ClassLoader l = getClassLoader();
9.114 - List<Object> res = new ArrayList<Object>();
9.115 - for (int i = 0; i < arr.length; i++) {
9.116 - Class<?> c = Class.forName(arr[i].getName(), true, l);
9.117 - seekKOTests(c, res);
9.118 - }
9.119 - Class<?> c = Class.forName(LessCallbacksCheck.class.getName(), true, l);
9.120 - seekKOTests(c, res);
9.121 - return res.toArray();
9.122 - }
9.123 -
9.124 - private static void seekKOTests(Class<?> c, List<Object> res) throws SecurityException, ClassNotFoundException {
9.125 - Class<? extends Annotation> koTest =
9.126 - c.getClassLoader().loadClass(KOTest.class.getName()).
9.127 - asSubclass(Annotation.class);
9.128 - for (Method m : c.getMethods()) {
9.129 - if (m.getAnnotation(koTest) != null) {
9.130 - res.add(new KOFx(browserContext, m));
9.131 - }
9.132 - }
9.133 - }
9.134 -
9.135 - static synchronized ClassLoader getClassLoader() throws InterruptedException {
9.136 - while (browserClass == null) {
9.137 - KnockoutFXTest.class.wait();
9.138 - }
9.139 - return browserClass.getClassLoader();
9.140 - }
9.141 -
9.142 - public static synchronized void initialized(Class<?> browserCls) throws Exception {
9.143 - browserClass = browserCls;
9.144 - browserContext = FnContext.currentPresenter();
9.145 - KnockoutFXTest.class.notifyAll();
9.146 - }
9.147 -
9.148 - public static void initialized() throws Exception {
9.149 - Class<?> classpathClass = ClassLoader.getSystemClassLoader().loadClass(KnockoutFXTest.class.getName());
9.150 - Method m = classpathClass.getMethod("initialized", Class.class);
9.151 - m.invoke(null, KnockoutFXTest.class);
9.152 - browserContext = FnContext.currentPresenter();
9.153 - }
9.154 -
9.155 - @Override
9.156 - public BrwsrCtx createContext() {
9.157 - FXContext fx = new FXContext(browserContext);
9.158 - Contexts.Builder cb = Contexts.newBuilder().
9.159 - register(Technology.class, fx, 10).
9.160 - register(Transfer.class, fx, 10);
9.161 - if (fx.areWebSocketsSupported()) {
9.162 - cb.register(WSTransfer.class, fx, 10);
9.163 - }
9.164 - return cb.build();
9.165 - }
9.166 -
9.167 - @Override
9.168 - public Object createJSON(Map<String, Object> values) {
9.169 - JSONObject json = new JSONObject();
9.170 - for (Map.Entry<String, Object> entry : values.entrySet()) {
9.171 - try {
9.172 - json.put(entry.getKey(), entry.getValue());
9.173 - } catch (JSONException ex) {
9.174 - throw new IllegalStateException(ex);
9.175 - }
9.176 - }
9.177 - return json;
9.178 - }
9.179 -
9.180 - @Override
9.181 - @JavaScriptBody(args = { "s", "args" }, body = ""
9.182 - + "var f = new Function(s); "
9.183 - + "return f.apply(null, args);"
9.184 - )
9.185 - public native Object executeScript(String script, Object[] arguments);
9.186 -
9.187 - @JavaScriptBody(args = { }, body =
9.188 - "var h;"
9.189 - + "if (!!window && !!window.location && !!window.location.href)\n"
9.190 - + " h = window.location.href;\n"
9.191 - + "else "
9.192 - + " h = null;"
9.193 - + "return h;\n"
9.194 - )
9.195 - private static native String findBaseURL();
9.196 -
9.197 - @Override
9.198 - public URI prepareURL(String content, String mimeType, String[] parameters) {
9.199 - try {
9.200 - final URL baseURL = new URL(findBaseURL());
9.201 - StringBuilder sb = new StringBuilder();
9.202 - sb.append("/dynamic?mimeType=").append(mimeType);
9.203 - for (int i = 0; i < parameters.length; i++) {
9.204 - sb.append("¶m" + i).append("=").append(parameters[i]);
9.205 - }
9.206 - String mangle = content.replace("\n", "%0a")
9.207 - .replace("\"", "\\\"").replace(" ", "%20");
9.208 - sb.append("&content=").append(mangle);
9.209 -
9.210 - URL query = new URL(baseURL, sb.toString());
9.211 - URLConnection c = query.openConnection();
9.212 - BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
9.213 - URI connectTo = new URI(br.readLine());
9.214 - return connectTo;
9.215 - } catch (IOException ex) {
9.216 - throw new IllegalStateException(ex);
9.217 - } catch (URISyntaxException ex) {
9.218 - throw new IllegalStateException(ex);
9.219 - }
9.220 - }
9.221 -
9.222 - @Override
9.223 - public boolean canFailWebSocketTest() {
9.224 - try {
9.225 - Class.forName("java.util.function.Function");
9.226 - return false;
9.227 - } catch (ClassNotFoundException ex) {
9.228 - // running on JDK7, FX WebView WebSocket impl does not work
9.229 - return true;
9.230 - }
9.231 - }
9.232 -}
10.1 --- a/ko-fx/src/test/java/org/netbeans/html/kofx/LessCallbacksCheck.java Thu Jan 09 11:53:46 2014 +0100
10.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
10.3 @@ -1,82 +0,0 @@
10.4 -/**
10.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
10.6 - *
10.7 - * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
10.8 - *
10.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
10.10 - * Other names may be trademarks of their respective owners.
10.11 - *
10.12 - * The contents of this file are subject to the terms of either the GNU
10.13 - * General Public License Version 2 only ("GPL") or the Common
10.14 - * Development and Distribution License("CDDL") (collectively, the
10.15 - * "License"). You may not use this file except in compliance with the
10.16 - * License. You can obtain a copy of the License at
10.17 - * http://www.netbeans.org/cddl-gplv2.html
10.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
10.19 - * specific language governing permissions and limitations under the
10.20 - * License. When distributing the software, include this License Header
10.21 - * Notice in each file and include the License file at
10.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
10.23 - * particular file as subject to the "Classpath" exception as provided
10.24 - * by Oracle in the GPL Version 2 section of the License file that
10.25 - * accompanied this code. If applicable, add the following below the
10.26 - * License Header, with the fields enclosed by brackets [] replaced by
10.27 - * your own identifying information:
10.28 - * "Portions Copyrighted [year] [name of copyright owner]"
10.29 - *
10.30 - * Contributor(s):
10.31 - *
10.32 - * The Original Software is NetBeans. The Initial Developer of the Original
10.33 - * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
10.34 - *
10.35 - * If you wish your version of this file to be governed by only the CDDL
10.36 - * or only the GPL Version 2, indicate your decision by adding
10.37 - * "[Contributor] elects to include this software in this distribution
10.38 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
10.39 - * single choice of license, a recipient has the option to distribute
10.40 - * your version of this file under either the CDDL, the GPL Version 2 or
10.41 - * to extend the choice of license to its licensees as provided above.
10.42 - * However, if you add GPL Version 2 code and therefore, elected the GPL
10.43 - * Version 2 license, then the option applies only if the new code is
10.44 - * made subject to such option by the copyright holder.
10.45 - */
10.46 -package org.netbeans.html.kofx;
10.47 -
10.48 -import java.io.PrintWriter;
10.49 -import java.io.StringWriter;
10.50 -import net.java.html.json.ComputedProperty;
10.51 -import net.java.html.json.Model;
10.52 -import net.java.html.json.Property;
10.53 -import org.apidesign.html.json.tck.KOTest;
10.54 -
10.55 -/**
10.56 - *
10.57 - * @author Jaroslav Tulach <jtulach@netbeans.org>
10.58 - */
10.59 -@Model(className = "LessCalls", properties = {
10.60 - @Property(name = "value", type = int.class)
10.61 -})
10.62 -public class LessCallbacksCheck {
10.63 - private static StringWriter sw;
10.64 -
10.65 - @ComputedProperty static int plusOne(int value) {
10.66 - if (sw == null) {
10.67 - sw = new StringWriter();
10.68 - }
10.69 - new Exception("Who calls me?").printStackTrace(
10.70 - new PrintWriter(sw)
10.71 - );
10.72 - return value + 1;
10.73 - }
10.74 -
10.75 - @KOTest public void dontCallForInitialValueBackToJavaVM() {
10.76 - LessCalls m = new LessCalls(10).applyBindings();
10.77 - assert m.getPlusOne() == 11 : "Expecting 11: " + m.getPlusOne();
10.78 -
10.79 - assert sw != null : "StringWriter should be initialized: " + sw;
10.80 -
10.81 - if (sw.toString().contains("$JsCallbacks$")) {
10.82 - assert false : "Don't call for initial value via JsCallbacks:\n" + sw;
10.83 - }
10.84 - }
10.85 -}
11.1 --- a/ko-fx/src/test/resources/org/netbeans/html/kofx/test.html Thu Jan 09 11:53:46 2014 +0100
11.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
11.3 @@ -1,56 +0,0 @@
11.4 -<!--
11.5 -
11.6 - DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
11.7 -
11.8 - Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
11.9 -
11.10 - Oracle and Java are registered trademarks of Oracle and/or its affiliates.
11.11 - Other names may be trademarks of their respective owners.
11.12 -
11.13 - The contents of this file are subject to the terms of either the GNU
11.14 - General Public License Version 2 only ("GPL") or the Common
11.15 - Development and Distribution License("CDDL") (collectively, the
11.16 - "License"). You may not use this file except in compliance with the
11.17 - License. You can obtain a copy of the License at
11.18 - http://www.netbeans.org/cddl-gplv2.html
11.19 - or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
11.20 - specific language governing permissions and limitations under the
11.21 - License. When distributing the software, include this License Header
11.22 - Notice in each file and include the License file at
11.23 - nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
11.24 - particular file as subject to the "Classpath" exception as provided
11.25 - by Oracle in the GPL Version 2 section of the License file that
11.26 - accompanied this code. If applicable, add the following below the
11.27 - License Header, with the fields enclosed by brackets [] replaced by
11.28 - your own identifying information:
11.29 - "Portions Copyrighted [year] [name of copyright owner]"
11.30 -
11.31 - Contributor(s):
11.32 -
11.33 - The Original Software is NetBeans. The Initial Developer of the Original
11.34 - Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
11.35 -
11.36 - If you wish your version of this file to be governed by only the CDDL
11.37 - or only the GPL Version 2, indicate your decision by adding
11.38 - "[Contributor] elects to include this software in this distribution
11.39 - under the [CDDL or GPL Version 2] license." If you do not indicate a
11.40 - single choice of license, a recipient has the option to distribute
11.41 - your version of this file under either the CDDL, the GPL Version 2 or
11.42 - to extend the choice of license to its licensees as provided above.
11.43 - However, if you add GPL Version 2 code and therefore, elected the GPL
11.44 - Version 2 license, then the option applies only if the new code is
11.45 - made subject to such option by the copyright holder.
11.46 -
11.47 --->
11.48 -<!DOCTYPE html>
11.49 -<html>
11.50 - <head>
11.51 - <title>Knockout.fx Execution Harness</title>
11.52 - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
11.53 - <meta name="viewport" content="width=device-width">
11.54 - </head>
11.55 - <body>
11.56 - <h1>Knockout.fx Execution Harness</h1>
11.57 - </body>
11.58 - <script></script>
11.59 -</html>
12.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
12.2 +++ b/ko4j/pom.xml Thu Jan 09 15:03:34 2014 +0100
12.3 @@ -0,0 +1,115 @@
12.4 +<?xml version="1.0"?>
12.5 +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
12.6 + <modelVersion>4.0.0</modelVersion>
12.7 + <parent>
12.8 + <groupId>org.netbeans.html</groupId>
12.9 + <artifactId>pom</artifactId>
12.10 + <version>0.7-SNAPSHOT</version>
12.11 + </parent>
12.12 + <groupId>org.netbeans.html</groupId>
12.13 + <artifactId>ko4j</artifactId>
12.14 + <version>0.7-SNAPSHOT</version>
12.15 + <packaging>bundle</packaging>
12.16 + <name>Knockout.js for Java</name>
12.17 + <url>http://maven.apache.org</url>
12.18 + <properties>
12.19 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
12.20 + <bundleSymbolicName>org.netbeans.html.ko4j</bundleSymbolicName>
12.21 + </properties>
12.22 + <build>
12.23 + <plugins>
12.24 + <plugin>
12.25 + <groupId>org.apache.felix</groupId>
12.26 + <artifactId>maven-bundle-plugin</artifactId>
12.27 + </plugin>
12.28 + <plugin>
12.29 + <groupId>org.apache.maven.plugins</groupId>
12.30 + <artifactId>maven-javadoc-plugin</artifactId>
12.31 + <configuration>
12.32 + <skip>false</skip>
12.33 + </configuration>
12.34 + </plugin>
12.35 + <plugin>
12.36 + <groupId>org.apache.maven.plugins</groupId>
12.37 + <artifactId>maven-compiler-plugin</artifactId>
12.38 + <version>2.3.2</version>
12.39 + <configuration>
12.40 + <source>1.7</source>
12.41 + <target>1.7</target>
12.42 + </configuration>
12.43 + </plugin>
12.44 + </plugins>
12.45 + </build>
12.46 + <dependencies>
12.47 + <dependency>
12.48 + <groupId>com.oracle</groupId>
12.49 + <artifactId>javafx</artifactId>
12.50 + <version>2.2</version>
12.51 + <scope>system</scope>
12.52 + <systemPath>${jfxrt.jar}</systemPath>
12.53 + </dependency>
12.54 + <dependency>
12.55 + <groupId>de.twentyeleven.skysail</groupId>
12.56 + <artifactId>org.json-osgi</artifactId>
12.57 + </dependency>
12.58 + <dependency>
12.59 + <groupId>org.netbeans.html</groupId>
12.60 + <artifactId>net.java.html.json</artifactId>
12.61 + <version>${project.version}</version>
12.62 + </dependency>
12.63 + <dependency>
12.64 + <groupId>org.testng</groupId>
12.65 + <artifactId>testng</artifactId>
12.66 + <scope>test</scope>
12.67 + </dependency>
12.68 + <dependency>
12.69 + <groupId>${project.groupId}</groupId>
12.70 + <artifactId>net.java.html.json.tck</artifactId>
12.71 + <version>${project.version}</version>
12.72 + <scope>test</scope>
12.73 + </dependency>
12.74 + <dependency>
12.75 + <groupId>org.netbeans.api</groupId>
12.76 + <artifactId>org-openide-util-lookup</artifactId>
12.77 + <scope>provided</scope>
12.78 + </dependency>
12.79 + <dependency>
12.80 + <groupId>org.netbeans.html</groupId>
12.81 + <artifactId>net.java.html.boot</artifactId>
12.82 + <version>${project.version}</version>
12.83 + <type>jar</type>
12.84 + </dependency>
12.85 + <dependency>
12.86 + <groupId>${project.groupId}</groupId>
12.87 + <artifactId>net.java.html.boot.fx</artifactId>
12.88 + <version>${project.version}</version>
12.89 + <scope>test</scope>
12.90 + </dependency>
12.91 + <dependency>
12.92 + <groupId>org.glassfish.grizzly</groupId>
12.93 + <artifactId>grizzly-http-server</artifactId>
12.94 + <version>2.3.3</version>
12.95 + <scope>test</scope>
12.96 + </dependency>
12.97 + <dependency>
12.98 + <groupId>org.glassfish.grizzly</groupId>
12.99 + <artifactId>grizzly-websockets-server</artifactId>
12.100 + <version>2.3.3</version>
12.101 + <scope>test</scope>
12.102 + <type>jar</type>
12.103 + </dependency>
12.104 + <dependency>
12.105 + <groupId>org.glassfish.grizzly</groupId>
12.106 + <artifactId>grizzly-http-servlet</artifactId>
12.107 + <version>2.3.3</version>
12.108 + <scope>test</scope>
12.109 + </dependency>
12.110 + <dependency>
12.111 + <groupId>javax.servlet</groupId>
12.112 + <artifactId>javax.servlet-api</artifactId>
12.113 + <scope>test</scope>
12.114 + <version>3.1.0</version>
12.115 + </dependency>
12.116 + </dependencies>
12.117 + <description>Binds net.java.html.json APIs together with knockout.js</description>
12.118 +</project>
13.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
13.2 +++ b/ko4j/src/main/java/org/netbeans/html/ko4j/FXContext.java Thu Jan 09 15:03:34 2014 +0100
13.3 @@ -0,0 +1,203 @@
13.4 +/**
13.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
13.6 + *
13.7 + * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
13.8 + *
13.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
13.10 + * Other names may be trademarks of their respective owners.
13.11 + *
13.12 + * The contents of this file are subject to the terms of either the GNU
13.13 + * General Public License Version 2 only ("GPL") or the Common
13.14 + * Development and Distribution License("CDDL") (collectively, the
13.15 + * "License"). You may not use this file except in compliance with the
13.16 + * License. You can obtain a copy of the License at
13.17 + * http://www.netbeans.org/cddl-gplv2.html
13.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
13.19 + * specific language governing permissions and limitations under the
13.20 + * License. When distributing the software, include this License Header
13.21 + * Notice in each file and include the License file at
13.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
13.23 + * particular file as subject to the "Classpath" exception as provided
13.24 + * by Oracle in the GPL Version 2 section of the License file that
13.25 + * accompanied this code. If applicable, add the following below the
13.26 + * License Header, with the fields enclosed by brackets [] replaced by
13.27 + * your own identifying information:
13.28 + * "Portions Copyrighted [year] [name of copyright owner]"
13.29 + *
13.30 + * Contributor(s):
13.31 + *
13.32 + * The Original Software is NetBeans. The Initial Developer of the Original
13.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
13.34 + *
13.35 + * If you wish your version of this file to be governed by only the CDDL
13.36 + * or only the GPL Version 2, indicate your decision by adding
13.37 + * "[Contributor] elects to include this software in this distribution
13.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
13.39 + * single choice of license, a recipient has the option to distribute
13.40 + * your version of this file under either the CDDL, the GPL Version 2 or
13.41 + * to extend the choice of license to its licensees as provided above.
13.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
13.43 + * Version 2 license, then the option applies only if the new code is
13.44 + * made subject to such option by the copyright holder.
13.45 + */
13.46 +package org.netbeans.html.ko4j;
13.47 +
13.48 +import java.io.Closeable;
13.49 +import java.io.IOException;
13.50 +import java.io.InputStream;
13.51 +import java.util.concurrent.Executor;
13.52 +import java.util.logging.Logger;
13.53 +import net.java.html.js.JavaScriptBody;
13.54 +import org.apidesign.html.boot.spi.Fn;
13.55 +import org.apidesign.html.json.spi.FunctionBinding;
13.56 +import org.apidesign.html.json.spi.JSONCall;
13.57 +import org.apidesign.html.json.spi.PropertyBinding;
13.58 +import org.apidesign.html.json.spi.Technology;
13.59 +import org.apidesign.html.json.spi.Transfer;
13.60 +import org.apidesign.html.json.spi.WSTransfer;
13.61 +
13.62 +/** This is an implementation package - just
13.63 + * include its JAR on classpath and use official {@link Context} API
13.64 + * to access the functionality.
13.65 + * <p>
13.66 + *
13.67 + * @author Jaroslav Tulach <jtulach@netbeans.org>
13.68 + */
13.69 +final class FXContext
13.70 +implements Technology.BatchInit<Object>, Transfer, WSTransfer<LoadWS> {
13.71 + static final Logger LOG = Logger.getLogger(FXContext.class.getName());
13.72 + private static Boolean javaScriptEnabled;
13.73 + private final Fn.Presenter browserContext;
13.74 +
13.75 + public FXContext(Fn.Presenter browserContext) {
13.76 + this.browserContext = browserContext;
13.77 + }
13.78 +
13.79 + @JavaScriptBody(args = {}, body = "return true;")
13.80 + private static boolean isJavaScriptEnabledJs() {
13.81 + return false;
13.82 + }
13.83 +
13.84 + static boolean isJavaScriptEnabled() {
13.85 + if (javaScriptEnabled != null) {
13.86 + return javaScriptEnabled;
13.87 + }
13.88 + return javaScriptEnabled = isJavaScriptEnabledJs();
13.89 + }
13.90 +
13.91 + final boolean areWebSocketsSupported() {
13.92 + return LoadWS.isSupported();
13.93 + }
13.94 +
13.95 +
13.96 + @Override
13.97 + public Object wrapModel(Object model, PropertyBinding[] propArr, FunctionBinding[] funcArr) {
13.98 + String[] propNames = new String[propArr.length];
13.99 + boolean[] propReadOnly = new boolean[propArr.length];
13.100 + Object[] propValues = new Object[propArr.length];
13.101 + for (int i = 0; i < propNames.length; i++) {
13.102 + propNames[i] = propArr[i].getPropertyName();
13.103 + propReadOnly[i] = propArr[i].isReadOnly();
13.104 + propValues[i] = propArr[i].getValue();
13.105 + }
13.106 + String[] funcNames = new String[funcArr.length];
13.107 + for (int i = 0; i < funcNames.length; i++) {
13.108 + funcNames[i] = funcArr[i].getFunctionName();
13.109 + }
13.110 + Object ret = Knockout.wrapModel(model,
13.111 + propNames, propReadOnly, propValues, propArr,
13.112 + funcNames, funcArr
13.113 + );
13.114 + return ret;
13.115 + }
13.116 +
13.117 + @Override
13.118 + public Object wrapModel(Object model) {
13.119 + throw new UnsupportedOperationException();
13.120 + }
13.121 +
13.122 + @Override
13.123 + public void bind(PropertyBinding b, Object model, Object data) {
13.124 + throw new UnsupportedOperationException();
13.125 + }
13.126 +
13.127 + @Override
13.128 + public void valueHasMutated(Object data, String propertyName) {
13.129 + Knockout.valueHasMutated(data, propertyName);
13.130 + }
13.131 +
13.132 + @Override
13.133 + public void expose(FunctionBinding fb, Object model, Object d) {
13.134 + throw new UnsupportedOperationException();
13.135 + }
13.136 +
13.137 + @Override
13.138 + public void applyBindings(Object data) {
13.139 + Knockout.applyBindings(data);
13.140 + }
13.141 +
13.142 + @Override
13.143 + public Object wrapArray(Object[] arr) {
13.144 + return arr;
13.145 + }
13.146 +
13.147 + @Override
13.148 + public void extract(Object obj, String[] props, Object[] values) {
13.149 + LoadJSON.extractJSON(obj, props, values);
13.150 + }
13.151 +
13.152 + @Override
13.153 + public void loadJSON(final JSONCall call) {
13.154 + LoadJSON.loadJSON(call);
13.155 + }
13.156 +
13.157 + @Override
13.158 + public <M> M toModel(Class<M> modelClass, Object data) {
13.159 + return modelClass.cast(Knockout.toModel(data));
13.160 + }
13.161 +
13.162 + @Override
13.163 + public Object toJSON(InputStream is) throws IOException {
13.164 + return LoadJSON.parse(is);
13.165 + }
13.166 +
13.167 + @Override
13.168 + public void runSafe(final Runnable r) {
13.169 + class Wrap implements Runnable {
13.170 + @Override public void run() {
13.171 + Closeable c = Fn.activate(browserContext);
13.172 + try {
13.173 + r.run();
13.174 + } finally {
13.175 + try {
13.176 + c.close();
13.177 + } catch (IOException ex) {
13.178 + // cannot be thrown
13.179 + }
13.180 + }
13.181 + }
13.182 + }
13.183 + Wrap w = new Wrap();
13.184 + if (browserContext instanceof Executor) {
13.185 + ((Executor)browserContext).execute(w);
13.186 + } else {
13.187 + w.run();
13.188 + }
13.189 + }
13.190 +
13.191 + @Override
13.192 + public LoadWS open(String url, JSONCall onReply) {
13.193 + return new LoadWS(onReply, url);
13.194 + }
13.195 +
13.196 + @Override
13.197 + public void send(LoadWS socket, JSONCall data) {
13.198 + socket.send(data);
13.199 + }
13.200 +
13.201 + @Override
13.202 + public void close(LoadWS socket) {
13.203 + socket.close();
13.204 + }
13.205 +
13.206 +}
14.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
14.2 +++ b/ko4j/src/main/java/org/netbeans/html/ko4j/KO4J.java Thu Jan 09 15:03:34 2014 +0100
14.3 @@ -0,0 +1,74 @@
14.4 +/*
14.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
14.6 + *
14.7 + * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
14.8 + *
14.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
14.10 + * Other names may be trademarks of their respective owners.
14.11 + *
14.12 + * The contents of this file are subject to the terms of either the GNU
14.13 + * General Public License Version 2 only ("GPL") or the Common
14.14 + * Development and Distribution License("CDDL") (collectively, the
14.15 + * "License"). You may not use this file except in compliance with the
14.16 + * License. You can obtain a copy of the License at
14.17 + * http://www.netbeans.org/cddl-gplv2.html
14.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
14.19 + * specific language governing permissions and limitations under the
14.20 + * License. When distributing the software, include this License Header
14.21 + * Notice in each file and include the License file at
14.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
14.23 + * particular file as subject to the "Classpath" exception as provided
14.24 + * by Oracle in the GPL Version 2 section of the License file that
14.25 + * accompanied this code. If applicable, add the following below the
14.26 + * License Header, with the fields enclosed by brackets [] replaced by
14.27 + * your own identifying information:
14.28 + * "Portions Copyrighted [year] [name of copyright owner]"
14.29 + *
14.30 + * If you wish your version of this file to be governed by only the CDDL
14.31 + * or only the GPL Version 2, indicate your decision by adding
14.32 + * "[Contributor] elects to include this software in this distribution
14.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
14.34 + * single choice of license, a recipient has the option to distribute
14.35 + * your version of this file under either the CDDL, the GPL Version 2 or
14.36 + * to extend the choice of license to its licensees as provided above.
14.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
14.38 + * Version 2 license, then the option applies only if the new code is
14.39 + * made subject to such option by the copyright holder.
14.40 + *
14.41 + * Contributor(s):
14.42 + *
14.43 + * Portions Copyrighted 2014 Sun Microsystems, Inc.
14.44 + */
14.45 +
14.46 +package org.netbeans.html.ko4j;
14.47 +
14.48 +import net.java.html.json.Model;
14.49 +import org.apidesign.html.boot.spi.Fn;
14.50 +import org.apidesign.html.context.spi.Contexts;
14.51 +import org.apidesign.html.json.spi.Technology;
14.52 +import org.apidesign.html.json.spi.Transfer;
14.53 +import org.apidesign.html.json.spi.WSTransfer;
14.54 +import org.openide.util.lookup.ServiceProvider;
14.55 +
14.56 +/** Support for <a href="http://knockoutjs.com">knockout.js</a>
14.57 + * and its Java binding via {@link Model model classes}.
14.58 + * Registers {@link ContextProvider}, so {@link ServiceLoader} can find it.
14.59 + *
14.60 + * @author Jaroslav Tulach <jtulach@netbeans.org>
14.61 + */
14.62 +@ServiceProvider(service = Contexts.Provider.class)
14.63 +public final class KO4J implements Contexts.Provider {
14.64 +
14.65 + @Override
14.66 + public void fillContext(Contexts.Builder context, Class<?> requestor) {
14.67 + if (FXContext.isJavaScriptEnabled()) {
14.68 + FXContext c = new FXContext(Fn.activePresenter());
14.69 + context.register(Technology.class, c, 100);
14.70 + context.register(Transfer.class, c, 100);
14.71 + if (c.areWebSocketsSupported()) {
14.72 + context.register(WSTransfer.class, c, 100);
14.73 + }
14.74 + }
14.75 + }
14.76 +
14.77 +}
15.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
15.2 +++ b/ko4j/src/main/java/org/netbeans/html/ko4j/Knockout.java Thu Jan 09 15:03:34 2014 +0100
15.3 @@ -0,0 +1,134 @@
15.4 +/**
15.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
15.6 + *
15.7 + * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
15.8 + *
15.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
15.10 + * Other names may be trademarks of their respective owners.
15.11 + *
15.12 + * The contents of this file are subject to the terms of either the GNU
15.13 + * General Public License Version 2 only ("GPL") or the Common
15.14 + * Development and Distribution License("CDDL") (collectively, the
15.15 + * "License"). You may not use this file except in compliance with the
15.16 + * License. You can obtain a copy of the License at
15.17 + * http://www.netbeans.org/cddl-gplv2.html
15.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
15.19 + * specific language governing permissions and limitations under the
15.20 + * License. When distributing the software, include this License Header
15.21 + * Notice in each file and include the License file at
15.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
15.23 + * particular file as subject to the "Classpath" exception as provided
15.24 + * by Oracle in the GPL Version 2 section of the License file that
15.25 + * accompanied this code. If applicable, add the following below the
15.26 + * License Header, with the fields enclosed by brackets [] replaced by
15.27 + * your own identifying information:
15.28 + * "Portions Copyrighted [year] [name of copyright owner]"
15.29 + *
15.30 + * Contributor(s):
15.31 + *
15.32 + * The Original Software is NetBeans. The Initial Developer of the Original
15.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
15.34 + *
15.35 + * If you wish your version of this file to be governed by only the CDDL
15.36 + * or only the GPL Version 2, indicate your decision by adding
15.37 + * "[Contributor] elects to include this software in this distribution
15.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
15.39 + * single choice of license, a recipient has the option to distribute
15.40 + * your version of this file under either the CDDL, the GPL Version 2 or
15.41 + * to extend the choice of license to its licensees as provided above.
15.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
15.43 + * Version 2 license, then the option applies only if the new code is
15.44 + * made subject to such option by the copyright holder.
15.45 + */
15.46 +package org.netbeans.html.ko4j;
15.47 +
15.48 +import net.java.html.js.JavaScriptBody;
15.49 +import net.java.html.js.JavaScriptResource;
15.50 +import net.java.html.json.Model;
15.51 +import org.apidesign.html.json.spi.FunctionBinding;
15.52 +import org.apidesign.html.json.spi.PropertyBinding;
15.53 +
15.54 +/** This is an implementation package - just
15.55 + * include its JAR on classpath and use official {@link Context} API
15.56 + * to access the functionality.
15.57 + * <p>
15.58 + * Provides binding between {@link Model models} and knockout.js running
15.59 + * inside a JavaFX WebView.
15.60 + *
15.61 + * @author Jaroslav Tulach <jtulach@netbeans.org>
15.62 + */
15.63 +@JavaScriptResource("knockout-2.2.1.js")
15.64 +final class Knockout {
15.65 + static {
15.66 + loadKnockout();
15.67 + }
15.68 +
15.69 + @JavaScriptBody(args = { }, body = "")
15.70 + private static native void loadKnockout();
15.71 +
15.72 + @JavaScriptBody(args = { "model", "prop" }, body =
15.73 + "if (model) {\n"
15.74 + + " var koProp = model[prop];\n"
15.75 + + " if (koProp && koProp['valueHasMutated']) {\n"
15.76 + + " koProp['valueHasMutated']();\n"
15.77 + + " }\n"
15.78 + + "}\n"
15.79 + )
15.80 + public native static void valueHasMutated(Object model, String prop);
15.81 +
15.82 + @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);\n")
15.83 + native static void applyBindings(Object bindings);
15.84 +
15.85 + @JavaScriptBody(
15.86 + javacall = true,
15.87 + args = {"model", "propNames", "propReadOnly", "propValues", "propArr", "funcNames", "funcArr"},
15.88 + body
15.89 + = "var ret = {};\n"
15.90 + + "ret['ko-fx.model'] = model;\n"
15.91 + + "function koComputed(name, readOnly, value, prop) {\n"
15.92 + + " function realGetter() {\n"
15.93 + + " try {\n"
15.94 + + " var v = prop.@org.apidesign.html.json.spi.PropertyBinding::getValue()();\n"
15.95 + + " return v;\n"
15.96 + + " } catch (e) {\n"
15.97 + + " alert(\"Cannot call getValue on \" + model + \" prop: \" + name + \" error: \" + e);\n"
15.98 + + " }\n"
15.99 + + " }\n"
15.100 + + " var activeGetter = function() { return value; };\n"
15.101 + + " var bnd = {\n"
15.102 + + " read: function() {\n"
15.103 + + " var r = activeGetter();\n"
15.104 + + " activeGetter = realGetter;\n"
15.105 + + " return r == null ? null : r.valueOf();\n"
15.106 + + " },\n"
15.107 + + " owner: ret\n"
15.108 + + " };\n"
15.109 + + " if (!readOnly) {\n"
15.110 + + " bnd.write = function(val) {\n"
15.111 + + " prop.@org.apidesign.html.json.spi.PropertyBinding::setValue(Ljava/lang/Object;)(val);\n"
15.112 + + " };\n"
15.113 + + " };\n"
15.114 + + " ret[name] = ko.computed(bnd);\n"
15.115 + + "}\n"
15.116 + + "for (var i = 0; i < propNames.length; i++) {\n"
15.117 + + " koComputed(propNames[i], propReadOnly[i], propValues[i], propArr[i]);\n"
15.118 + + "}\n"
15.119 + + "function koExpose(name, func) {\n"
15.120 + + " ret[name] = function(data, ev) {\n"
15.121 + + " func.@org.apidesign.html.json.spi.FunctionBinding::call(Ljava/lang/Object;Ljava/lang/Object;)(data, ev);\n"
15.122 + + " };\n"
15.123 + + "}\n"
15.124 + + "for (var i = 0; i < funcNames.length; i++) {\n"
15.125 + + " koExpose(funcNames[i], funcArr[i]);\n"
15.126 + + "}\n"
15.127 + + "return ret;\n"
15.128 + )
15.129 + static native Object wrapModel(
15.130 + Object model,
15.131 + String[] propNames, boolean[] propReadOnly, Object propValues, PropertyBinding[] propArr,
15.132 + String[] funcNames, FunctionBinding[] funcArr
15.133 + );
15.134 +
15.135 + @JavaScriptBody(args = { "o" }, body = "return o['ko-fx.model'] ? o['ko-fx.model'] : o;")
15.136 + static native Object toModel(Object wrapper);
15.137 +}
16.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
16.2 +++ b/ko4j/src/main/java/org/netbeans/html/ko4j/LoadJSON.java Thu Jan 09 15:03:34 2014 +0100
16.3 @@ -0,0 +1,267 @@
16.4 +/**
16.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
16.6 + *
16.7 + * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
16.8 + *
16.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
16.10 + * Other names may be trademarks of their respective owners.
16.11 + *
16.12 + * The contents of this file are subject to the terms of either the GNU
16.13 + * General Public License Version 2 only ("GPL") or the Common
16.14 + * Development and Distribution License("CDDL") (collectively, the
16.15 + * "License"). You may not use this file except in compliance with the
16.16 + * License. You can obtain a copy of the License at
16.17 + * http://www.netbeans.org/cddl-gplv2.html
16.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16.19 + * specific language governing permissions and limitations under the
16.20 + * License. When distributing the software, include this License Header
16.21 + * Notice in each file and include the License file at
16.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
16.23 + * particular file as subject to the "Classpath" exception as provided
16.24 + * by Oracle in the GPL Version 2 section of the License file that
16.25 + * accompanied this code. If applicable, add the following below the
16.26 + * License Header, with the fields enclosed by brackets [] replaced by
16.27 + * your own identifying information:
16.28 + * "Portions Copyrighted [year] [name of copyright owner]"
16.29 + *
16.30 + * Contributor(s):
16.31 + *
16.32 + * The Original Software is NetBeans. The Initial Developer of the Original
16.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
16.34 + *
16.35 + * If you wish your version of this file to be governed by only the CDDL
16.36 + * or only the GPL Version 2, indicate your decision by adding
16.37 + * "[Contributor] elects to include this software in this distribution
16.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
16.39 + * single choice of license, a recipient has the option to distribute
16.40 + * your version of this file under either the CDDL, the GPL Version 2 or
16.41 + * to extend the choice of license to its licensees as provided above.
16.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
16.43 + * Version 2 license, then the option applies only if the new code is
16.44 + * made subject to such option by the copyright holder.
16.45 + */
16.46 +package org.netbeans.html.ko4j;
16.47 +
16.48 +import java.io.IOException;
16.49 +import java.io.InputStream;
16.50 +import java.io.InputStreamReader;
16.51 +import java.io.OutputStream;
16.52 +import java.io.PushbackInputStream;
16.53 +import java.io.Reader;
16.54 +import java.net.HttpURLConnection;
16.55 +import java.net.MalformedURLException;
16.56 +import java.net.URL;
16.57 +import java.net.URLConnection;
16.58 +import java.util.Iterator;
16.59 +import java.util.concurrent.Executor;
16.60 +import java.util.concurrent.Executors;
16.61 +import java.util.concurrent.ThreadFactory;
16.62 +import java.util.logging.Level;
16.63 +import java.util.logging.Logger;
16.64 +import javafx.application.Platform;
16.65 +import net.java.html.js.JavaScriptBody;
16.66 +import netscape.javascript.JSObject;
16.67 +import org.apidesign.html.json.spi.JSONCall;
16.68 +import org.json.JSONArray;
16.69 +import org.json.JSONException;
16.70 +import org.json.JSONObject;
16.71 +import org.json.JSONTokener;
16.72 +
16.73 +/** This is an implementation package - just
16.74 + * include its JAR on classpath and use official {@link Context} API
16.75 + * to access the functionality.
16.76 + *
16.77 + * @author Jaroslav Tulach <jtulach@netbeans.org>
16.78 + */
16.79 +final class LoadJSON implements Runnable {
16.80 + private static final Logger LOG = FXContext.LOG;
16.81 + private static final Executor REQ = Executors.newCachedThreadPool(new ThreadFactory() {
16.82 + @Override
16.83 + public Thread newThread(Runnable runnable) {
16.84 + Thread thread = Executors.defaultThreadFactory().newThread(runnable);
16.85 + thread.setDaemon(true);
16.86 + return thread;
16.87 + }
16.88 + });
16.89 +
16.90 + private final JSONCall call;
16.91 + private final URL base;
16.92 + private Throwable error;
16.93 + private Object json;
16.94 +
16.95 +
16.96 + private LoadJSON(JSONCall call) {
16.97 + this.call = call;
16.98 + URL b;
16.99 + try {
16.100 + b = new URL(findBaseURL());
16.101 + } catch (MalformedURLException ex) {
16.102 + LOG.log(Level.SEVERE, "Can't find base url for " + call.composeURL("dummy"), ex);
16.103 + b = null;
16.104 + }
16.105 + this.base = b;
16.106 + }
16.107 +
16.108 + public static void loadJSON(JSONCall call) {
16.109 + assert !"WebSocket".equals(call.getMethod());
16.110 + REQ.execute(new LoadJSON((call)));
16.111 + }
16.112 +
16.113 + @Override
16.114 + public void run() {
16.115 + if (Platform.isFxApplicationThread()) {
16.116 + if (error != null) {
16.117 + call.notifyError(error);
16.118 + } else {
16.119 + call.notifySuccess(json);
16.120 + }
16.121 + return;
16.122 + }
16.123 + final String url;
16.124 + if (call.isJSONP()) {
16.125 + url = call.composeURL("dummy");
16.126 + } else {
16.127 + url = call.composeURL(null);
16.128 + }
16.129 + try {
16.130 + final URL u = new URL(base, url.replace(" ", "%20"));
16.131 + URLConnection conn = u.openConnection();
16.132 + if (conn instanceof HttpURLConnection) {
16.133 + HttpURLConnection huc = (HttpURLConnection) conn;
16.134 + if (call.getMethod() != null) {
16.135 + huc.setRequestMethod(call.getMethod());
16.136 + }
16.137 + if (call.isDoOutput()) {
16.138 + huc.setDoOutput(true);
16.139 + final OutputStream os = huc.getOutputStream();
16.140 + call.writeData(os);
16.141 + os.flush();
16.142 + }
16.143 + }
16.144 + final PushbackInputStream is = new PushbackInputStream(
16.145 + conn.getInputStream(), 1
16.146 + );
16.147 + boolean array = false;
16.148 + boolean string = false;
16.149 + if (call.isJSONP()) {
16.150 + for (;;) {
16.151 + int ch = is.read();
16.152 + if (ch == -1) {
16.153 + break;
16.154 + }
16.155 + if (ch == '[') {
16.156 + is.unread(ch);
16.157 + array = true;
16.158 + break;
16.159 + }
16.160 + if (ch == '{') {
16.161 + is.unread(ch);
16.162 + break;
16.163 + }
16.164 + }
16.165 + } else {
16.166 + int ch = is.read();
16.167 + if (ch == -1) {
16.168 + string = true;
16.169 + } else {
16.170 + array = ch == '[';
16.171 + is.unread(ch);
16.172 + if (!array && ch != '{') {
16.173 + string = true;
16.174 + }
16.175 + }
16.176 + }
16.177 + try {
16.178 + if (string) {
16.179 + throw new JSONException("");
16.180 + }
16.181 + Reader r = new InputStreamReader(is, "UTF-8");
16.182 +
16.183 + JSONTokener tok = new JSONTokener(r);
16.184 + Object obj;
16.185 + obj = array ? new JSONArray(tok) : new JSONObject(tok);
16.186 + json = convertToArray(obj);
16.187 + } catch (JSONException ex) {
16.188 + Reader r = new InputStreamReader(is, "UTF-8");
16.189 + StringBuilder sb = new StringBuilder();
16.190 + for (;;) {
16.191 + int ch = r.read();
16.192 + if (ch == -1) {
16.193 + break;
16.194 + }
16.195 + sb.append((char)ch);
16.196 + }
16.197 + json = sb.toString();
16.198 + }
16.199 + } catch (IOException ex) {
16.200 + error = ex;
16.201 + } finally {
16.202 + Platform.runLater(this);
16.203 + }
16.204 + }
16.205 +
16.206 + static Object convertToArray(Object o) throws JSONException {
16.207 + if (o instanceof JSONArray) {
16.208 + JSONArray ja = (JSONArray)o;
16.209 + Object[] arr = new Object[ja.length()];
16.210 + for (int i = 0; i < arr.length; i++) {
16.211 + arr[i] = convertToArray(ja.get(i));
16.212 + }
16.213 + return arr;
16.214 + } else if (o instanceof JSONObject) {
16.215 + JSONObject obj = (JSONObject)o;
16.216 + Iterator it = obj.keys();
16.217 + while (it.hasNext()) {
16.218 + String key = (String)it.next();
16.219 + obj.put(key, convertToArray(obj.get(key)));
16.220 + }
16.221 + return obj;
16.222 + } else {
16.223 + return o;
16.224 + }
16.225 + }
16.226 +
16.227 + public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
16.228 + if (jsonObject instanceof JSONObject) {
16.229 + JSONObject obj = (JSONObject)jsonObject;
16.230 + for (int i = 0; i < props.length; i++) {
16.231 + try {
16.232 + values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
16.233 + } catch (JSONException ex) {
16.234 + LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
16.235 + }
16.236 + }
16.237 + }
16.238 + if (jsonObject instanceof JSObject) {
16.239 + JSObject obj = (JSObject)jsonObject;
16.240 + for (int i = 0; i < props.length; i++) {
16.241 + Object val = obj.getMember(props[i]);
16.242 + values[i] = isDefined(val) ? val : null;
16.243 + }
16.244 + }
16.245 + }
16.246 +
16.247 + public static Object parse(InputStream is) throws IOException {
16.248 + try {
16.249 + InputStreamReader r = new InputStreamReader(is, "UTF-8");
16.250 + JSONTokener t = new JSONTokener(r);
16.251 + return new JSONObject(t);
16.252 + } catch (JSONException ex) {
16.253 + throw new IOException(ex);
16.254 + }
16.255 + }
16.256 +
16.257 + @JavaScriptBody(args = { }, body =
16.258 + "var h;"
16.259 + + "if (!!window && !!window.location && !!window.location.href)\n"
16.260 + + " h = window.location.href;\n"
16.261 + + "else "
16.262 + + " h = null;"
16.263 + + "return h;\n"
16.264 + )
16.265 + private static native String findBaseURL();
16.266 +
16.267 + private static boolean isDefined(Object val) {
16.268 + return !"undefined".equals(val);
16.269 + }
16.270 +}
17.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
17.2 +++ b/ko4j/src/main/java/org/netbeans/html/ko4j/LoadWS.java Thu Jan 09 15:03:34 2014 +0100
17.3 @@ -0,0 +1,149 @@
17.4 +/**
17.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
17.6 + *
17.7 + * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
17.8 + *
17.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
17.10 + * Other names may be trademarks of their respective owners.
17.11 + *
17.12 + * The contents of this file are subject to the terms of either the GNU
17.13 + * General Public License Version 2 only ("GPL") or the Common
17.14 + * Development and Distribution License("CDDL") (collectively, the
17.15 + * "License"). You may not use this file except in compliance with the
17.16 + * License. You can obtain a copy of the License at
17.17 + * http://www.netbeans.org/cddl-gplv2.html
17.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
17.19 + * specific language governing permissions and limitations under the
17.20 + * License. When distributing the software, include this License Header
17.21 + * Notice in each file and include the License file at
17.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
17.23 + * particular file as subject to the "Classpath" exception as provided
17.24 + * by Oracle in the GPL Version 2 section of the License file that
17.25 + * accompanied this code. If applicable, add the following below the
17.26 + * License Header, with the fields enclosed by brackets [] replaced by
17.27 + * your own identifying information:
17.28 + * "Portions Copyrighted [year] [name of copyright owner]"
17.29 + *
17.30 + * Contributor(s):
17.31 + *
17.32 + * The Original Software is NetBeans. The Initial Developer of the Original
17.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
17.34 + *
17.35 + * If you wish your version of this file to be governed by only the CDDL
17.36 + * or only the GPL Version 2, indicate your decision by adding
17.37 + * "[Contributor] elects to include this software in this distribution
17.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
17.39 + * single choice of license, a recipient has the option to distribute
17.40 + * your version of this file under either the CDDL, the GPL Version 2 or
17.41 + * to extend the choice of license to its licensees as provided above.
17.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
17.43 + * Version 2 license, then the option applies only if the new code is
17.44 + * made subject to such option by the copyright holder.
17.45 + */
17.46 +package org.netbeans.html.ko4j;
17.47 +
17.48 +import net.java.html.js.JavaScriptBody;
17.49 +import org.apidesign.html.json.spi.JSONCall;
17.50 +import org.json.JSONArray;
17.51 +import org.json.JSONException;
17.52 +import org.json.JSONObject;
17.53 +import org.json.JSONTokener;
17.54 +
17.55 +/** Communication with WebSockets for WebView 1.8.
17.56 + *
17.57 + * @author Jaroslav Tulach <jtulach@netbeans.org>
17.58 + */
17.59 +final class LoadWS {
17.60 + private static final boolean SUPPORTED = isWebSocket();
17.61 + private final Object ws;
17.62 + private final JSONCall call;
17.63 +
17.64 + LoadWS(JSONCall first, String url) {
17.65 + call = first;
17.66 + ws = initWebSocket(this, url);
17.67 + if (ws == null) {
17.68 + first.notifyError(new IllegalArgumentException("Wrong URL: " + url));
17.69 + }
17.70 + }
17.71 +
17.72 + static boolean isSupported() {
17.73 + return SUPPORTED;
17.74 + }
17.75 +
17.76 + void send(JSONCall call) {
17.77 + push(call);
17.78 + }
17.79 +
17.80 + private synchronized void push(JSONCall call) {
17.81 + send(ws, call.getMessage());
17.82 + }
17.83 +
17.84 + void onOpen(Object ev) {
17.85 + if (!call.isDoOutput()) {
17.86 + call.notifySuccess(null);
17.87 + }
17.88 + }
17.89 +
17.90 + void onMessage(Object ev, String data) {
17.91 + Object json;
17.92 + try {
17.93 + data = data.trim();
17.94 +
17.95 + JSONTokener tok = new JSONTokener(data);
17.96 + Object obj;
17.97 + obj = data.startsWith("[") ? new JSONArray(tok) : new JSONObject(tok);
17.98 + json = LoadJSON.convertToArray(obj);
17.99 + } catch (JSONException ex) {
17.100 + json = data;
17.101 + }
17.102 + call.notifySuccess(json);
17.103 + }
17.104 +
17.105 + void onError(Object ev) {
17.106 + call.notifyError(new Exception(ev.toString()));
17.107 + }
17.108 +
17.109 + void onClose(boolean wasClean, int code, String reason) {
17.110 + call.notifyError(null);
17.111 + }
17.112 +
17.113 + @JavaScriptBody(args = {}, body = "if (window.WebSocket) return true; else return false;")
17.114 + private static boolean isWebSocket() {
17.115 + return false;
17.116 + }
17.117 +
17.118 + @JavaScriptBody(args = { "back", "url" }, javacall = true, body = ""
17.119 + + "if (window.WebSocket) {"
17.120 + + " try {"
17.121 + + " var ws = new window.WebSocket(url);"
17.122 + + " ws.onopen = function(ev) { back.@org.netbeans.html.ko4j.LoadWS::onOpen(Ljava/lang/Object;)(ev); };"
17.123 + + " ws.onmessage = function(ev) { back.@org.netbeans.html.ko4j.LoadWS::onMessage(Ljava/lang/Object;Ljava/lang/String;)(ev, ev.data); };"
17.124 + + " ws.onerror = function(ev) { back.@org.netbeans.html.ko4j.LoadWS::onError(Ljava/lang/Object;)(ev); };"
17.125 + + " ws.onclose = function(ev) { back.@org.netbeans.html.ko4j.LoadWS::onClose(ZILjava/lang/String;)(ev.wasClean, ev.code, ev.reason); };"
17.126 + + " return ws;"
17.127 + + " } catch (ex) {"
17.128 + + " return null;"
17.129 + + " }"
17.130 + + "} else {"
17.131 + + " return null;"
17.132 + + "}"
17.133 + )
17.134 + private static Object initWebSocket(Object back, String url) {
17.135 + return null;
17.136 + }
17.137 +
17.138 +
17.139 + @JavaScriptBody(args = { "ws", "msg" }, body = ""
17.140 + + "ws.send(msg);"
17.141 + )
17.142 + private void send(Object ws, String msg) {
17.143 + }
17.144 +
17.145 + @JavaScriptBody(args = { "ws" }, body = "ws.close();")
17.146 + private static void close(Object ws) {
17.147 + }
17.148 +
17.149 + void close() {
17.150 + close(ws);
17.151 + }
17.152 +}
18.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
18.2 +++ b/ko4j/src/main/resources/org/netbeans/html/ko4j/knockout-2.2.1.js Thu Jan 09 15:03:34 2014 +0100
18.3 @@ -0,0 +1,3594 @@
18.4 +// Knockout JavaScript library v2.2.1
18.5 +// (c) Steven Sanderson - http://knockoutjs.com/
18.6 +// License: MIT (http://www.opensource.org/licenses/mit-license.php)
18.7 +
18.8 +(function(){
18.9 +var DEBUG=true;
18.10 +(function(window,document,navigator,jQuery,undefined){
18.11 +!function(factory) {
18.12 + // Support three module loading scenarios
18.13 + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
18.14 + // [1] CommonJS/Node.js
18.15 + var target = module['exports'] || exports; // module.exports is for Node.js
18.16 + factory(target);
18.17 + } else if (typeof define === 'function' && define['amd']) {
18.18 + // [2] AMD anonymous module
18.19 + define(['exports'], factory);
18.20 + } else {
18.21 + // [3] No module loader (plain <script> tag) - put directly in global namespace
18.22 + factory(window['ko'] = {});
18.23 + }
18.24 +}(function(koExports){
18.25 +// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
18.26 +// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
18.27 +var ko = typeof koExports !== 'undefined' ? koExports : {};
18.28 +// Google Closure Compiler helpers (used only to make the minified file smaller)
18.29 +ko.exportSymbol = function(koPath, object) {
18.30 + var tokens = koPath.split(".");
18.31 +
18.32 + // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
18.33 + // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
18.34 + var target = ko;
18.35 +
18.36 + for (var i = 0; i < tokens.length - 1; i++)
18.37 + target = target[tokens[i]];
18.38 + target[tokens[tokens.length - 1]] = object;
18.39 +};
18.40 +ko.exportProperty = function(owner, publicName, object) {
18.41 + owner[publicName] = object;
18.42 +};
18.43 +ko.version = "2.2.1";
18.44 +
18.45 +ko.exportSymbol('version', ko.version);
18.46 +ko.utils = new (function () {
18.47 + var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
18.48 +
18.49 + // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
18.50 + var knownEvents = {}, knownEventTypesByEventName = {};
18.51 + var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
18.52 + knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
18.53 + knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
18.54 + for (var eventType in knownEvents) {
18.55 + var knownEventsForType = knownEvents[eventType];
18.56 + if (knownEventsForType.length) {
18.57 + for (var i = 0, j = knownEventsForType.length; i < j; i++)
18.58 + knownEventTypesByEventName[knownEventsForType[i]] = eventType;
18.59 + }
18.60 + }
18.61 + var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
18.62 +
18.63 + // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
18.64 + // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
18.65 + // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
18.66 + // If there is a future need to detect specific versions of IE10+, we will amend this.
18.67 + var ieVersion = (function() {
18.68 + var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
18.69 +
18.70 + // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
18.71 + while (
18.72 + div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
18.73 + iElems[0]
18.74 + );
18.75 + return version > 4 ? version : undefined;
18.76 + }());
18.77 + var isIe6 = ieVersion === 6,
18.78 + isIe7 = ieVersion === 7;
18.79 +
18.80 + function isClickOnCheckableElement(element, eventType) {
18.81 + if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
18.82 + if (eventType.toLowerCase() != "click") return false;
18.83 + var inputType = element.type;
18.84 + return (inputType == "checkbox") || (inputType == "radio");
18.85 + }
18.86 +
18.87 + return {
18.88 + fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
18.89 +
18.90 + arrayForEach: function (array, action) {
18.91 + for (var i = 0, j = array.length; i < j; i++)
18.92 + action(array[i]);
18.93 + },
18.94 +
18.95 + arrayIndexOf: function (array, item) {
18.96 + if (typeof Array.prototype.indexOf == "function")
18.97 + return Array.prototype.indexOf.call(array, item);
18.98 + for (var i = 0, j = array.length; i < j; i++)
18.99 + if (array[i] === item)
18.100 + return i;
18.101 + return -1;
18.102 + },
18.103 +
18.104 + arrayFirst: function (array, predicate, predicateOwner) {
18.105 + for (var i = 0, j = array.length; i < j; i++)
18.106 + if (predicate.call(predicateOwner, array[i]))
18.107 + return array[i];
18.108 + return null;
18.109 + },
18.110 +
18.111 + arrayRemoveItem: function (array, itemToRemove) {
18.112 + var index = ko.utils.arrayIndexOf(array, itemToRemove);
18.113 + if (index >= 0)
18.114 + array.splice(index, 1);
18.115 + },
18.116 +
18.117 + arrayGetDistinctValues: function (array) {
18.118 + array = array || [];
18.119 + var result = [];
18.120 + for (var i = 0, j = array.length; i < j; i++) {
18.121 + if (ko.utils.arrayIndexOf(result, array[i]) < 0)
18.122 + result.push(array[i]);
18.123 + }
18.124 + return result;
18.125 + },
18.126 +
18.127 + arrayMap: function (array, mapping) {
18.128 + array = array || [];
18.129 + var result = [];
18.130 + for (var i = 0, j = array.length; i < j; i++)
18.131 + result.push(mapping(array[i]));
18.132 + return result;
18.133 + },
18.134 +
18.135 + arrayFilter: function (array, predicate) {
18.136 + array = array || [];
18.137 + var result = [];
18.138 + for (var i = 0, j = array.length; i < j; i++)
18.139 + if (predicate(array[i]))
18.140 + result.push(array[i]);
18.141 + return result;
18.142 + },
18.143 +
18.144 + arrayPushAll: function (array, valuesToPush) {
18.145 + if (valuesToPush instanceof Array)
18.146 + array.push.apply(array, valuesToPush);
18.147 + else
18.148 + for (var i = 0, j = valuesToPush.length; i < j; i++)
18.149 + array.push(valuesToPush[i]);
18.150 + return array;
18.151 + },
18.152 +
18.153 + extend: function (target, source) {
18.154 + if (source) {
18.155 + for(var prop in source) {
18.156 + if(source.hasOwnProperty(prop)) {
18.157 + target[prop] = source[prop];
18.158 + }
18.159 + }
18.160 + }
18.161 + return target;
18.162 + },
18.163 +
18.164 + emptyDomNode: function (domNode) {
18.165 + while (domNode.firstChild) {
18.166 + ko.removeNode(domNode.firstChild);
18.167 + }
18.168 + },
18.169 +
18.170 + moveCleanedNodesToContainerElement: function(nodes) {
18.171 + // Ensure it's a real array, as we're about to reparent the nodes and
18.172 + // we don't want the underlying collection to change while we're doing that.
18.173 + var nodesArray = ko.utils.makeArray(nodes);
18.174 +
18.175 + var container = document.createElement('div');
18.176 + for (var i = 0, j = nodesArray.length; i < j; i++) {
18.177 + container.appendChild(ko.cleanNode(nodesArray[i]));
18.178 + }
18.179 + return container;
18.180 + },
18.181 +
18.182 + cloneNodes: function (nodesArray, shouldCleanNodes) {
18.183 + for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
18.184 + var clonedNode = nodesArray[i].cloneNode(true);
18.185 + newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
18.186 + }
18.187 + return newNodesArray;
18.188 + },
18.189 +
18.190 + setDomNodeChildren: function (domNode, childNodes) {
18.191 + ko.utils.emptyDomNode(domNode);
18.192 + if (childNodes) {
18.193 + for (var i = 0, j = childNodes.length; i < j; i++)
18.194 + domNode.appendChild(childNodes[i]);
18.195 + }
18.196 + },
18.197 +
18.198 + replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
18.199 + var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
18.200 + if (nodesToReplaceArray.length > 0) {
18.201 + var insertionPoint = nodesToReplaceArray[0];
18.202 + var parent = insertionPoint.parentNode;
18.203 + for (var i = 0, j = newNodesArray.length; i < j; i++)
18.204 + parent.insertBefore(newNodesArray[i], insertionPoint);
18.205 + for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
18.206 + ko.removeNode(nodesToReplaceArray[i]);
18.207 + }
18.208 + }
18.209 + },
18.210 +
18.211 + setOptionNodeSelectionState: function (optionNode, isSelected) {
18.212 + // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
18.213 + if (ieVersion < 7)
18.214 + optionNode.setAttribute("selected", isSelected);
18.215 + else
18.216 + optionNode.selected = isSelected;
18.217 + },
18.218 +
18.219 + stringTrim: function (string) {
18.220 + return (string || "").replace(stringTrimRegex, "");
18.221 + },
18.222 +
18.223 + stringTokenize: function (string, delimiter) {
18.224 + var result = [];
18.225 + var tokens = (string || "").split(delimiter);
18.226 + for (var i = 0, j = tokens.length; i < j; i++) {
18.227 + var trimmed = ko.utils.stringTrim(tokens[i]);
18.228 + if (trimmed !== "")
18.229 + result.push(trimmed);
18.230 + }
18.231 + return result;
18.232 + },
18.233 +
18.234 + stringStartsWith: function (string, startsWith) {
18.235 + string = string || "";
18.236 + if (startsWith.length > string.length)
18.237 + return false;
18.238 + return string.substring(0, startsWith.length) === startsWith;
18.239 + },
18.240 +
18.241 + domNodeIsContainedBy: function (node, containedByNode) {
18.242 + if (containedByNode.compareDocumentPosition)
18.243 + return (containedByNode.compareDocumentPosition(node) & 16) == 16;
18.244 + while (node != null) {
18.245 + if (node == containedByNode)
18.246 + return true;
18.247 + node = node.parentNode;
18.248 + }
18.249 + return false;
18.250 + },
18.251 +
18.252 + domNodeIsAttachedToDocument: function (node) {
18.253 + return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
18.254 + },
18.255 +
18.256 + tagNameLower: function(element) {
18.257 + // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
18.258 + // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
18.259 + // we don't need to do the .toLowerCase() as it will always be lower case anyway.
18.260 + return element && element.tagName && element.tagName.toLowerCase();
18.261 + },
18.262 +
18.263 + registerEventHandler: function (element, eventType, handler) {
18.264 + var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
18.265 + if (!mustUseAttachEvent && typeof jQuery != "undefined") {
18.266 + if (isClickOnCheckableElement(element, eventType)) {
18.267 + // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
18.268 + // it toggles the element checked state *after* the click event handlers run, whereas native
18.269 + // click events toggle the checked state *before* the event handler.
18.270 + // Fix this by intecepting the handler and applying the correct checkedness before it runs.
18.271 + var originalHandler = handler;
18.272 + handler = function(event, eventData) {
18.273 + var jQuerySuppliedCheckedState = this.checked;
18.274 + if (eventData)
18.275 + this.checked = eventData.checkedStateBeforeEvent !== true;
18.276 + originalHandler.call(this, event);
18.277 + this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
18.278 + };
18.279 + }
18.280 + jQuery(element)['bind'](eventType, handler);
18.281 + } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
18.282 + element.addEventListener(eventType, handler, false);
18.283 + else if (typeof element.attachEvent != "undefined")
18.284 + element.attachEvent("on" + eventType, function (event) {
18.285 + handler.call(element, event);
18.286 + });
18.287 + else
18.288 + throw new Error("Browser doesn't support addEventListener or attachEvent");
18.289 + },
18.290 +
18.291 + triggerEvent: function (element, eventType) {
18.292 + if (!(element && element.nodeType))
18.293 + throw new Error("element must be a DOM node when calling triggerEvent");
18.294 +
18.295 + if (typeof jQuery != "undefined") {
18.296 + var eventData = [];
18.297 + if (isClickOnCheckableElement(element, eventType)) {
18.298 + // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
18.299 + eventData.push({ checkedStateBeforeEvent: element.checked });
18.300 + }
18.301 + jQuery(element)['trigger'](eventType, eventData);
18.302 + } else if (typeof document.createEvent == "function") {
18.303 + if (typeof element.dispatchEvent == "function") {
18.304 + var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
18.305 + var event = document.createEvent(eventCategory);
18.306 + event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
18.307 + element.dispatchEvent(event);
18.308 + }
18.309 + else
18.310 + throw new Error("The supplied element doesn't support dispatchEvent");
18.311 + } else if (typeof element.fireEvent != "undefined") {
18.312 + // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
18.313 + // so to make it consistent, we'll do it manually here
18.314 + if (isClickOnCheckableElement(element, eventType))
18.315 + element.checked = element.checked !== true;
18.316 + element.fireEvent("on" + eventType);
18.317 + }
18.318 + else
18.319 + throw new Error("Browser doesn't support triggering events");
18.320 + },
18.321 +
18.322 + unwrapObservable: function (value) {
18.323 + return ko.isObservable(value) ? value() : value;
18.324 + },
18.325 +
18.326 + peekObservable: function (value) {
18.327 + return ko.isObservable(value) ? value.peek() : value;
18.328 + },
18.329 +
18.330 + toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
18.331 + if (classNames) {
18.332 + var cssClassNameRegex = /[\w-]+/g,
18.333 + currentClassNames = node.className.match(cssClassNameRegex) || [];
18.334 + ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
18.335 + var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
18.336 + if (indexOfClass >= 0) {
18.337 + if (!shouldHaveClass)
18.338 + currentClassNames.splice(indexOfClass, 1);
18.339 + } else {
18.340 + if (shouldHaveClass)
18.341 + currentClassNames.push(className);
18.342 + }
18.343 + });
18.344 + node.className = currentClassNames.join(" ");
18.345 + }
18.346 + },
18.347 +
18.348 + setTextContent: function(element, textContent) {
18.349 + var value = ko.utils.unwrapObservable(textContent);
18.350 + if ((value === null) || (value === undefined))
18.351 + value = "";
18.352 +
18.353 + if (element.nodeType === 3) {
18.354 + element.data = value;
18.355 + } else {
18.356 + // We need there to be exactly one child: a text node.
18.357 + // If there are no children, more than one, or if it's not a text node,
18.358 + // we'll clear everything and create a single text node.
18.359 + var innerTextNode = ko.virtualElements.firstChild(element);
18.360 + if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
18.361 + ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
18.362 + } else {
18.363 + innerTextNode.data = value;
18.364 + }
18.365 +
18.366 + ko.utils.forceRefresh(element);
18.367 + }
18.368 + },
18.369 +
18.370 + setElementName: function(element, name) {
18.371 + element.name = name;
18.372 +
18.373 + // Workaround IE 6/7 issue
18.374 + // - https://github.com/SteveSanderson/knockout/issues/197
18.375 + // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
18.376 + if (ieVersion <= 7) {
18.377 + try {
18.378 + element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
18.379 + }
18.380 + catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
18.381 + }
18.382 + },
18.383 +
18.384 + forceRefresh: function(node) {
18.385 + // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
18.386 + if (ieVersion >= 9) {
18.387 + // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
18.388 + var elem = node.nodeType == 1 ? node : node.parentNode;
18.389 + if (elem.style)
18.390 + elem.style.zoom = elem.style.zoom;
18.391 + }
18.392 + },
18.393 +
18.394 + ensureSelectElementIsRenderedCorrectly: function(selectElement) {
18.395 + // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
18.396 + // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
18.397 + if (ieVersion >= 9) {
18.398 + var originalWidth = selectElement.style.width;
18.399 + selectElement.style.width = 0;
18.400 + selectElement.style.width = originalWidth;
18.401 + }
18.402 + },
18.403 +
18.404 + range: function (min, max) {
18.405 + min = ko.utils.unwrapObservable(min);
18.406 + max = ko.utils.unwrapObservable(max);
18.407 + var result = [];
18.408 + for (var i = min; i <= max; i++)
18.409 + result.push(i);
18.410 + return result;
18.411 + },
18.412 +
18.413 + makeArray: function(arrayLikeObject) {
18.414 + var result = [];
18.415 + for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
18.416 + result.push(arrayLikeObject[i]);
18.417 + };
18.418 + return result;
18.419 + },
18.420 +
18.421 + isIe6 : isIe6,
18.422 + isIe7 : isIe7,
18.423 + ieVersion : ieVersion,
18.424 +
18.425 + getFormFields: function(form, fieldName) {
18.426 + var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
18.427 + var isMatchingField = (typeof fieldName == 'string')
18.428 + ? function(field) { return field.name === fieldName }
18.429 + : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
18.430 + var matches = [];
18.431 + for (var i = fields.length - 1; i >= 0; i--) {
18.432 + if (isMatchingField(fields[i]))
18.433 + matches.push(fields[i]);
18.434 + };
18.435 + return matches;
18.436 + },
18.437 +
18.438 + parseJson: function (jsonString) {
18.439 + if (typeof jsonString == "string") {
18.440 + jsonString = ko.utils.stringTrim(jsonString);
18.441 + if (jsonString) {
18.442 + if (window.JSON && window.JSON.parse) // Use native parsing where available
18.443 + return window.JSON.parse(jsonString);
18.444 + return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
18.445 + }
18.446 + }
18.447 + return null;
18.448 + },
18.449 +
18.450 + stringifyJson: function (data, replacer, space) { // replacer and space are optional
18.451 + if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
18.452 + throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
18.453 + return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
18.454 + },
18.455 +
18.456 + postJson: function (urlOrForm, data, options) {
18.457 + options = options || {};
18.458 + var params = options['params'] || {};
18.459 + var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
18.460 + var url = urlOrForm;
18.461 +
18.462 + // If we were given a form, use its 'action' URL and pick out any requested field values
18.463 + if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
18.464 + var originalForm = urlOrForm;
18.465 + url = originalForm.action;
18.466 + for (var i = includeFields.length - 1; i >= 0; i--) {
18.467 + var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
18.468 + for (var j = fields.length - 1; j >= 0; j--)
18.469 + params[fields[j].name] = fields[j].value;
18.470 + }
18.471 + }
18.472 +
18.473 + data = ko.utils.unwrapObservable(data);
18.474 + var form = document.createElement("form");
18.475 + form.style.display = "none";
18.476 + form.action = url;
18.477 + form.method = "post";
18.478 + for (var key in data) {
18.479 + var input = document.createElement("input");
18.480 + input.name = key;
18.481 + input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
18.482 + form.appendChild(input);
18.483 + }
18.484 + for (var key in params) {
18.485 + var input = document.createElement("input");
18.486 + input.name = key;
18.487 + input.value = params[key];
18.488 + form.appendChild(input);
18.489 + }
18.490 + document.body.appendChild(form);
18.491 + options['submitter'] ? options['submitter'](form) : form.submit();
18.492 + setTimeout(function () { form.parentNode.removeChild(form); }, 0);
18.493 + }
18.494 + }
18.495 +})();
18.496 +
18.497 +ko.exportSymbol('utils', ko.utils);
18.498 +ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
18.499 +ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
18.500 +ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
18.501 +ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
18.502 +ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
18.503 +ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
18.504 +ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
18.505 +ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
18.506 +ko.exportSymbol('utils.extend', ko.utils.extend);
18.507 +ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
18.508 +ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
18.509 +ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
18.510 +ko.exportSymbol('utils.postJson', ko.utils.postJson);
18.511 +ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
18.512 +ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
18.513 +ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
18.514 +ko.exportSymbol('utils.range', ko.utils.range);
18.515 +ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
18.516 +ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
18.517 +ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
18.518 +
18.519 +if (!Function.prototype['bind']) {
18.520 + // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
18.521 + // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
18.522 + Function.prototype['bind'] = function (object) {
18.523 + var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
18.524 + return function () {
18.525 + return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
18.526 + };
18.527 + };
18.528 +}
18.529 +
18.530 +ko.utils.domData = new (function () {
18.531 + var uniqueId = 0;
18.532 + var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
18.533 + var dataStore = {};
18.534 + return {
18.535 + get: function (node, key) {
18.536 + var allDataForNode = ko.utils.domData.getAll(node, false);
18.537 + return allDataForNode === undefined ? undefined : allDataForNode[key];
18.538 + },
18.539 + set: function (node, key, value) {
18.540 + if (value === undefined) {
18.541 + // Make sure we don't actually create a new domData key if we are actually deleting a value
18.542 + if (ko.utils.domData.getAll(node, false) === undefined)
18.543 + return;
18.544 + }
18.545 + var allDataForNode = ko.utils.domData.getAll(node, true);
18.546 + allDataForNode[key] = value;
18.547 + },
18.548 + getAll: function (node, createIfNotFound) {
18.549 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
18.550 + var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
18.551 + if (!hasExistingDataStore) {
18.552 + if (!createIfNotFound)
18.553 + return undefined;
18.554 + dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
18.555 + dataStore[dataStoreKey] = {};
18.556 + }
18.557 + return dataStore[dataStoreKey];
18.558 + },
18.559 + clear: function (node) {
18.560 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
18.561 + if (dataStoreKey) {
18.562 + delete dataStore[dataStoreKey];
18.563 + node[dataStoreKeyExpandoPropertyName] = null;
18.564 + return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
18.565 + }
18.566 + return false;
18.567 + }
18.568 + }
18.569 +})();
18.570 +
18.571 +ko.exportSymbol('utils.domData', ko.utils.domData);
18.572 +ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
18.573 +
18.574 +ko.utils.domNodeDisposal = new (function () {
18.575 + var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
18.576 + var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
18.577 + var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
18.578 +
18.579 + function getDisposeCallbacksCollection(node, createIfNotFound) {
18.580 + var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
18.581 + if ((allDisposeCallbacks === undefined) && createIfNotFound) {
18.582 + allDisposeCallbacks = [];
18.583 + ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
18.584 + }
18.585 + return allDisposeCallbacks;
18.586 + }
18.587 + function destroyCallbacksCollection(node) {
18.588 + ko.utils.domData.set(node, domDataKey, undefined);
18.589 + }
18.590 +
18.591 + function cleanSingleNode(node) {
18.592 + // Run all the dispose callbacks
18.593 + var callbacks = getDisposeCallbacksCollection(node, false);
18.594 + if (callbacks) {
18.595 + callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
18.596 + for (var i = 0; i < callbacks.length; i++)
18.597 + callbacks[i](node);
18.598 + }
18.599 +
18.600 + // Also erase the DOM data
18.601 + ko.utils.domData.clear(node);
18.602 +
18.603 + // Special support for jQuery here because it's so commonly used.
18.604 + // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
18.605 + // so notify it to tear down any resources associated with the node & descendants here.
18.606 + if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
18.607 + jQuery['cleanData']([node]);
18.608 +
18.609 + // Also clear any immediate-child comment nodes, as these wouldn't have been found by
18.610 + // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
18.611 + if (cleanableNodeTypesWithDescendants[node.nodeType])
18.612 + cleanImmediateCommentTypeChildren(node);
18.613 + }
18.614 +
18.615 + function cleanImmediateCommentTypeChildren(nodeWithChildren) {
18.616 + var child, nextChild = nodeWithChildren.firstChild;
18.617 + while (child = nextChild) {
18.618 + nextChild = child.nextSibling;
18.619 + if (child.nodeType === 8)
18.620 + cleanSingleNode(child);
18.621 + }
18.622 + }
18.623 +
18.624 + return {
18.625 + addDisposeCallback : function(node, callback) {
18.626 + if (typeof callback != "function")
18.627 + throw new Error("Callback must be a function");
18.628 + getDisposeCallbacksCollection(node, true).push(callback);
18.629 + },
18.630 +
18.631 + removeDisposeCallback : function(node, callback) {
18.632 + var callbacksCollection = getDisposeCallbacksCollection(node, false);
18.633 + if (callbacksCollection) {
18.634 + ko.utils.arrayRemoveItem(callbacksCollection, callback);
18.635 + if (callbacksCollection.length == 0)
18.636 + destroyCallbacksCollection(node);
18.637 + }
18.638 + },
18.639 +
18.640 + cleanNode : function(node) {
18.641 + // First clean this node, where applicable
18.642 + if (cleanableNodeTypes[node.nodeType]) {
18.643 + cleanSingleNode(node);
18.644 +
18.645 + // ... then its descendants, where applicable
18.646 + if (cleanableNodeTypesWithDescendants[node.nodeType]) {
18.647 + // Clone the descendants list in case it changes during iteration
18.648 + var descendants = [];
18.649 + ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
18.650 + for (var i = 0, j = descendants.length; i < j; i++)
18.651 + cleanSingleNode(descendants[i]);
18.652 + }
18.653 + }
18.654 + return node;
18.655 + },
18.656 +
18.657 + removeNode : function(node) {
18.658 + ko.cleanNode(node);
18.659 + if (node.parentNode)
18.660 + node.parentNode.removeChild(node);
18.661 + }
18.662 + }
18.663 +})();
18.664 +ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
18.665 +ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
18.666 +ko.exportSymbol('cleanNode', ko.cleanNode);
18.667 +ko.exportSymbol('removeNode', ko.removeNode);
18.668 +ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
18.669 +ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
18.670 +ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
18.671 +(function () {
18.672 + var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
18.673 +
18.674 + function simpleHtmlParse(html) {
18.675 + // Based on jQuery's "clean" function, but only accounting for table-related elements.
18.676 + // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
18.677 +
18.678 + // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
18.679 + // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
18.680 + // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
18.681 + // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
18.682 +
18.683 + // Trim whitespace, otherwise indexOf won't work as expected
18.684 + var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
18.685 +
18.686 + // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
18.687 + var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
18.688 + !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
18.689 + (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
18.690 + /* anything else */ [0, "", ""];
18.691 +
18.692 + // Go to html and back, then peel off extra wrappers
18.693 + // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
18.694 + var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
18.695 + if (typeof window['innerShiv'] == "function") {
18.696 + div.appendChild(window['innerShiv'](markup));
18.697 + } else {
18.698 + div.innerHTML = markup;
18.699 + }
18.700 +
18.701 + // Move to the right depth
18.702 + while (wrap[0]--)
18.703 + div = div.lastChild;
18.704 +
18.705 + return ko.utils.makeArray(div.lastChild.childNodes);
18.706 + }
18.707 +
18.708 + function jQueryHtmlParse(html) {
18.709 + // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
18.710 + if (jQuery['parseHTML']) {
18.711 + return jQuery['parseHTML'](html);
18.712 + } else {
18.713 + // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
18.714 + var elems = jQuery['clean']([html]);
18.715 +
18.716 + // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
18.717 + // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
18.718 + // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
18.719 + if (elems && elems[0]) {
18.720 + // Find the top-most parent element that's a direct child of a document fragment
18.721 + var elem = elems[0];
18.722 + while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
18.723 + elem = elem.parentNode;
18.724 + // ... then detach it
18.725 + if (elem.parentNode)
18.726 + elem.parentNode.removeChild(elem);
18.727 + }
18.728 +
18.729 + return elems;
18.730 + }
18.731 + }
18.732 +
18.733 + ko.utils.parseHtmlFragment = function(html) {
18.734 + return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
18.735 + : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
18.736 + };
18.737 +
18.738 + ko.utils.setHtml = function(node, html) {
18.739 + ko.utils.emptyDomNode(node);
18.740 +
18.741 + // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
18.742 + html = ko.utils.unwrapObservable(html);
18.743 +
18.744 + if ((html !== null) && (html !== undefined)) {
18.745 + if (typeof html != 'string')
18.746 + html = html.toString();
18.747 +
18.748 + // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
18.749 + // for example <tr> elements which are not normally allowed to exist on their own.
18.750 + // If you've referenced jQuery we'll use that rather than duplicating its code.
18.751 + if (typeof jQuery != 'undefined') {
18.752 + jQuery(node)['html'](html);
18.753 + } else {
18.754 + // ... otherwise, use KO's own parsing logic.
18.755 + var parsedNodes = ko.utils.parseHtmlFragment(html);
18.756 + for (var i = 0; i < parsedNodes.length; i++)
18.757 + node.appendChild(parsedNodes[i]);
18.758 + }
18.759 + }
18.760 + };
18.761 +})();
18.762 +
18.763 +ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
18.764 +ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
18.765 +
18.766 +ko.memoization = (function () {
18.767 + var memos = {};
18.768 +
18.769 + function randomMax8HexChars() {
18.770 + return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
18.771 + }
18.772 + function generateRandomId() {
18.773 + return randomMax8HexChars() + randomMax8HexChars();
18.774 + }
18.775 + function findMemoNodes(rootNode, appendToArray) {
18.776 + if (!rootNode)
18.777 + return;
18.778 + if (rootNode.nodeType == 8) {
18.779 + var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
18.780 + if (memoId != null)
18.781 + appendToArray.push({ domNode: rootNode, memoId: memoId });
18.782 + } else if (rootNode.nodeType == 1) {
18.783 + for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
18.784 + findMemoNodes(childNodes[i], appendToArray);
18.785 + }
18.786 + }
18.787 +
18.788 + return {
18.789 + memoize: function (callback) {
18.790 + if (typeof callback != "function")
18.791 + throw new Error("You can only pass a function to ko.memoization.memoize()");
18.792 + var memoId = generateRandomId();
18.793 + memos[memoId] = callback;
18.794 + return "<!--[ko_memo:" + memoId + "]-->";
18.795 + },
18.796 +
18.797 + unmemoize: function (memoId, callbackParams) {
18.798 + var callback = memos[memoId];
18.799 + if (callback === undefined)
18.800 + throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
18.801 + try {
18.802 + callback.apply(null, callbackParams || []);
18.803 + return true;
18.804 + }
18.805 + finally { delete memos[memoId]; }
18.806 + },
18.807 +
18.808 + unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
18.809 + var memos = [];
18.810 + findMemoNodes(domNode, memos);
18.811 + for (var i = 0, j = memos.length; i < j; i++) {
18.812 + var node = memos[i].domNode;
18.813 + var combinedParams = [node];
18.814 + if (extraCallbackParamsArray)
18.815 + ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
18.816 + ko.memoization.unmemoize(memos[i].memoId, combinedParams);
18.817 + node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
18.818 + if (node.parentNode)
18.819 + node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
18.820 + }
18.821 + },
18.822 +
18.823 + parseMemoText: function (memoText) {
18.824 + var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
18.825 + return match ? match[1] : null;
18.826 + }
18.827 + };
18.828 +})();
18.829 +
18.830 +ko.exportSymbol('memoization', ko.memoization);
18.831 +ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
18.832 +ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
18.833 +ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
18.834 +ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
18.835 +ko.extenders = {
18.836 + 'throttle': function(target, timeout) {
18.837 + // Throttling means two things:
18.838 +
18.839 + // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
18.840 + // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
18.841 + target['throttleEvaluation'] = timeout;
18.842 +
18.843 + // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
18.844 + // so the target cannot change value synchronously or faster than a certain rate
18.845 + var writeTimeoutInstance = null;
18.846 + return ko.dependentObservable({
18.847 + 'read': target,
18.848 + 'write': function(value) {
18.849 + clearTimeout(writeTimeoutInstance);
18.850 + writeTimeoutInstance = setTimeout(function() {
18.851 + target(value);
18.852 + }, timeout);
18.853 + }
18.854 + });
18.855 + },
18.856 +
18.857 + 'notify': function(target, notifyWhen) {
18.858 + target["equalityComparer"] = notifyWhen == "always"
18.859 + ? function() { return false } // Treat all values as not equal
18.860 + : ko.observable["fn"]["equalityComparer"];
18.861 + return target;
18.862 + }
18.863 +};
18.864 +
18.865 +function applyExtenders(requestedExtenders) {
18.866 + var target = this;
18.867 + if (requestedExtenders) {
18.868 + for (var key in requestedExtenders) {
18.869 + var extenderHandler = ko.extenders[key];
18.870 + if (typeof extenderHandler == 'function') {
18.871 + target = extenderHandler(target, requestedExtenders[key]);
18.872 + }
18.873 + }
18.874 + }
18.875 + return target;
18.876 +}
18.877 +
18.878 +ko.exportSymbol('extenders', ko.extenders);
18.879 +
18.880 +ko.subscription = function (target, callback, disposeCallback) {
18.881 + this.target = target;
18.882 + this.callback = callback;
18.883 + this.disposeCallback = disposeCallback;
18.884 + ko.exportProperty(this, 'dispose', this.dispose);
18.885 +};
18.886 +ko.subscription.prototype.dispose = function () {
18.887 + this.isDisposed = true;
18.888 + this.disposeCallback();
18.889 +};
18.890 +
18.891 +ko.subscribable = function () {
18.892 + this._subscriptions = {};
18.893 +
18.894 + ko.utils.extend(this, ko.subscribable['fn']);
18.895 + ko.exportProperty(this, 'subscribe', this.subscribe);
18.896 + ko.exportProperty(this, 'extend', this.extend);
18.897 + ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
18.898 +}
18.899 +
18.900 +var defaultEvent = "change";
18.901 +
18.902 +ko.subscribable['fn'] = {
18.903 + subscribe: function (callback, callbackTarget, event) {
18.904 + event = event || defaultEvent;
18.905 + var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
18.906 +
18.907 + var subscription = new ko.subscription(this, boundCallback, function () {
18.908 + ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
18.909 + }.bind(this));
18.910 +
18.911 + if (!this._subscriptions[event])
18.912 + this._subscriptions[event] = [];
18.913 + this._subscriptions[event].push(subscription);
18.914 + return subscription;
18.915 + },
18.916 +
18.917 + "notifySubscribers": function (valueToNotify, event) {
18.918 + event = event || defaultEvent;
18.919 + if (this._subscriptions[event]) {
18.920 + ko.dependencyDetection.ignore(function() {
18.921 + ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
18.922 + // In case a subscription was disposed during the arrayForEach cycle, check
18.923 + // for isDisposed on each subscription before invoking its callback
18.924 + if (subscription && (subscription.isDisposed !== true))
18.925 + subscription.callback(valueToNotify);
18.926 + });
18.927 + }, this);
18.928 + }
18.929 + },
18.930 +
18.931 + getSubscriptionsCount: function () {
18.932 + var total = 0;
18.933 + for (var eventName in this._subscriptions) {
18.934 + if (this._subscriptions.hasOwnProperty(eventName))
18.935 + total += this._subscriptions[eventName].length;
18.936 + }
18.937 + return total;
18.938 + },
18.939 +
18.940 + extend: applyExtenders
18.941 +};
18.942 +
18.943 +
18.944 +ko.isSubscribable = function (instance) {
18.945 + return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
18.946 +};
18.947 +
18.948 +ko.exportSymbol('subscribable', ko.subscribable);
18.949 +ko.exportSymbol('isSubscribable', ko.isSubscribable);
18.950 +
18.951 +ko.dependencyDetection = (function () {
18.952 + var _frames = [];
18.953 +
18.954 + return {
18.955 + begin: function (callback) {
18.956 + _frames.push({ callback: callback, distinctDependencies:[] });
18.957 + },
18.958 +
18.959 + end: function () {
18.960 + _frames.pop();
18.961 + },
18.962 +
18.963 + registerDependency: function (subscribable) {
18.964 + if (!ko.isSubscribable(subscribable))
18.965 + throw new Error("Only subscribable things can act as dependencies");
18.966 + if (_frames.length > 0) {
18.967 + var topFrame = _frames[_frames.length - 1];
18.968 + if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
18.969 + return;
18.970 + topFrame.distinctDependencies.push(subscribable);
18.971 + topFrame.callback(subscribable);
18.972 + }
18.973 + },
18.974 +
18.975 + ignore: function(callback, callbackTarget, callbackArgs) {
18.976 + try {
18.977 + _frames.push(null);
18.978 + return callback.apply(callbackTarget, callbackArgs || []);
18.979 + } finally {
18.980 + _frames.pop();
18.981 + }
18.982 + }
18.983 + };
18.984 +})();
18.985 +var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
18.986 +
18.987 +ko.observable = function (initialValue) {
18.988 + var _latestValue = initialValue;
18.989 +
18.990 + function observable() {
18.991 + if (arguments.length > 0) {
18.992 + // Write
18.993 +
18.994 + // Ignore writes if the value hasn't changed
18.995 + if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
18.996 + observable.valueWillMutate();
18.997 + _latestValue = arguments[0];
18.998 + if (DEBUG) observable._latestValue = _latestValue;
18.999 + observable.valueHasMutated();
18.1000 + }
18.1001 + return this; // Permits chained assignments
18.1002 + }
18.1003 + else {
18.1004 + // Read
18.1005 + ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
18.1006 + return _latestValue;
18.1007 + }
18.1008 + }
18.1009 + if (DEBUG) observable._latestValue = _latestValue;
18.1010 + ko.subscribable.call(observable);
18.1011 + observable.peek = function() { return _latestValue };
18.1012 + observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
18.1013 + observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
18.1014 + ko.utils.extend(observable, ko.observable['fn']);
18.1015 +
18.1016 + ko.exportProperty(observable, 'peek', observable.peek);
18.1017 + ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
18.1018 + ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
18.1019 +
18.1020 + return observable;
18.1021 +}
18.1022 +
18.1023 +ko.observable['fn'] = {
18.1024 + "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
18.1025 + var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
18.1026 + return oldValueIsPrimitive ? (a === b) : false;
18.1027 + }
18.1028 +};
18.1029 +
18.1030 +var protoProperty = ko.observable.protoProperty = "__ko_proto__";
18.1031 +ko.observable['fn'][protoProperty] = ko.observable;
18.1032 +
18.1033 +ko.hasPrototype = function(instance, prototype) {
18.1034 + if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
18.1035 + if (instance[protoProperty] === prototype) return true;
18.1036 + return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
18.1037 +};
18.1038 +
18.1039 +ko.isObservable = function (instance) {
18.1040 + return ko.hasPrototype(instance, ko.observable);
18.1041 +}
18.1042 +ko.isWriteableObservable = function (instance) {
18.1043 + // Observable
18.1044 + if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
18.1045 + return true;
18.1046 + // Writeable dependent observable
18.1047 + if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
18.1048 + return true;
18.1049 + // Anything else
18.1050 + return false;
18.1051 +}
18.1052 +
18.1053 +
18.1054 +ko.exportSymbol('observable', ko.observable);
18.1055 +ko.exportSymbol('isObservable', ko.isObservable);
18.1056 +ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
18.1057 +ko.observableArray = function (initialValues) {
18.1058 + if (arguments.length == 0) {
18.1059 + // Zero-parameter constructor initializes to empty array
18.1060 + initialValues = [];
18.1061 + }
18.1062 + if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
18.1063 + throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
18.1064 +
18.1065 + var result = ko.observable(initialValues);
18.1066 + ko.utils.extend(result, ko.observableArray['fn']);
18.1067 + return result;
18.1068 +}
18.1069 +
18.1070 +ko.observableArray['fn'] = {
18.1071 + 'remove': function (valueOrPredicate) {
18.1072 + var underlyingArray = this.peek();
18.1073 + var removedValues = [];
18.1074 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
18.1075 + for (var i = 0; i < underlyingArray.length; i++) {
18.1076 + var value = underlyingArray[i];
18.1077 + if (predicate(value)) {
18.1078 + if (removedValues.length === 0) {
18.1079 + this.valueWillMutate();
18.1080 + }
18.1081 + removedValues.push(value);
18.1082 + underlyingArray.splice(i, 1);
18.1083 + i--;
18.1084 + }
18.1085 + }
18.1086 + if (removedValues.length) {
18.1087 + this.valueHasMutated();
18.1088 + }
18.1089 + return removedValues;
18.1090 + },
18.1091 +
18.1092 + 'removeAll': function (arrayOfValues) {
18.1093 + // If you passed zero args, we remove everything
18.1094 + if (arrayOfValues === undefined) {
18.1095 + var underlyingArray = this.peek();
18.1096 + var allValues = underlyingArray.slice(0);
18.1097 + this.valueWillMutate();
18.1098 + underlyingArray.splice(0, underlyingArray.length);
18.1099 + this.valueHasMutated();
18.1100 + return allValues;
18.1101 + }
18.1102 + // If you passed an arg, we interpret it as an array of entries to remove
18.1103 + if (!arrayOfValues)
18.1104 + return [];
18.1105 + return this['remove'](function (value) {
18.1106 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
18.1107 + });
18.1108 + },
18.1109 +
18.1110 + 'destroy': function (valueOrPredicate) {
18.1111 + var underlyingArray = this.peek();
18.1112 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
18.1113 + this.valueWillMutate();
18.1114 + for (var i = underlyingArray.length - 1; i >= 0; i--) {
18.1115 + var value = underlyingArray[i];
18.1116 + if (predicate(value))
18.1117 + underlyingArray[i]["_destroy"] = true;
18.1118 + }
18.1119 + this.valueHasMutated();
18.1120 + },
18.1121 +
18.1122 + 'destroyAll': function (arrayOfValues) {
18.1123 + // If you passed zero args, we destroy everything
18.1124 + if (arrayOfValues === undefined)
18.1125 + return this['destroy'](function() { return true });
18.1126 +
18.1127 + // If you passed an arg, we interpret it as an array of entries to destroy
18.1128 + if (!arrayOfValues)
18.1129 + return [];
18.1130 + return this['destroy'](function (value) {
18.1131 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
18.1132 + });
18.1133 + },
18.1134 +
18.1135 + 'indexOf': function (item) {
18.1136 + var underlyingArray = this();
18.1137 + return ko.utils.arrayIndexOf(underlyingArray, item);
18.1138 + },
18.1139 +
18.1140 + 'replace': function(oldItem, newItem) {
18.1141 + var index = this['indexOf'](oldItem);
18.1142 + if (index >= 0) {
18.1143 + this.valueWillMutate();
18.1144 + this.peek()[index] = newItem;
18.1145 + this.valueHasMutated();
18.1146 + }
18.1147 + }
18.1148 +}
18.1149 +
18.1150 +// Populate ko.observableArray.fn with read/write functions from native arrays
18.1151 +// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
18.1152 +// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
18.1153 +ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
18.1154 + ko.observableArray['fn'][methodName] = function () {
18.1155 + // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
18.1156 + // (for consistency with mutating regular observables)
18.1157 + var underlyingArray = this.peek();
18.1158 + this.valueWillMutate();
18.1159 + var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
18.1160 + this.valueHasMutated();
18.1161 + return methodCallResult;
18.1162 + };
18.1163 +});
18.1164 +
18.1165 +// Populate ko.observableArray.fn with read-only functions from native arrays
18.1166 +ko.utils.arrayForEach(["slice"], function (methodName) {
18.1167 + ko.observableArray['fn'][methodName] = function () {
18.1168 + var underlyingArray = this();
18.1169 + return underlyingArray[methodName].apply(underlyingArray, arguments);
18.1170 + };
18.1171 +});
18.1172 +
18.1173 +ko.exportSymbol('observableArray', ko.observableArray);
18.1174 +ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
18.1175 + var _latestValue,
18.1176 + _hasBeenEvaluated = false,
18.1177 + _isBeingEvaluated = false,
18.1178 + readFunction = evaluatorFunctionOrOptions;
18.1179 +
18.1180 + if (readFunction && typeof readFunction == "object") {
18.1181 + // Single-parameter syntax - everything is on this "options" param
18.1182 + options = readFunction;
18.1183 + readFunction = options["read"];
18.1184 + } else {
18.1185 + // Multi-parameter syntax - construct the options according to the params passed
18.1186 + options = options || {};
18.1187 + if (!readFunction)
18.1188 + readFunction = options["read"];
18.1189 + }
18.1190 + if (typeof readFunction != "function")
18.1191 + throw new Error("Pass a function that returns the value of the ko.computed");
18.1192 +
18.1193 + function addSubscriptionToDependency(subscribable) {
18.1194 + _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
18.1195 + }
18.1196 +
18.1197 + function disposeAllSubscriptionsToDependencies() {
18.1198 + ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
18.1199 + subscription.dispose();
18.1200 + });
18.1201 + _subscriptionsToDependencies = [];
18.1202 + }
18.1203 +
18.1204 + function evaluatePossiblyAsync() {
18.1205 + var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
18.1206 + if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
18.1207 + clearTimeout(evaluationTimeoutInstance);
18.1208 + evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
18.1209 + } else
18.1210 + evaluateImmediate();
18.1211 + }
18.1212 +
18.1213 + function evaluateImmediate() {
18.1214 + if (_isBeingEvaluated) {
18.1215 + // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
18.1216 + // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
18.1217 + // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
18.1218 + // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
18.1219 + return;
18.1220 + }
18.1221 +
18.1222 + // Don't dispose on first evaluation, because the "disposeWhen" callback might
18.1223 + // e.g., dispose when the associated DOM element isn't in the doc, and it's not
18.1224 + // going to be in the doc until *after* the first evaluation
18.1225 + if (_hasBeenEvaluated && disposeWhen()) {
18.1226 + dispose();
18.1227 + return;
18.1228 + }
18.1229 +
18.1230 + _isBeingEvaluated = true;
18.1231 + try {
18.1232 + // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
18.1233 + // Then, during evaluation, we cross off any that are in fact still being used.
18.1234 + var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
18.1235 +
18.1236 + ko.dependencyDetection.begin(function(subscribable) {
18.1237 + var inOld;
18.1238 + if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
18.1239 + disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
18.1240 + else
18.1241 + addSubscriptionToDependency(subscribable); // Brand new subscription - add it
18.1242 + });
18.1243 +
18.1244 + var newValue = readFunction.call(evaluatorFunctionTarget);
18.1245 +
18.1246 + // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
18.1247 + for (var i = disposalCandidates.length - 1; i >= 0; i--) {
18.1248 + if (disposalCandidates[i])
18.1249 + _subscriptionsToDependencies.splice(i, 1)[0].dispose();
18.1250 + }
18.1251 + _hasBeenEvaluated = true;
18.1252 +
18.1253 + dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
18.1254 + _latestValue = newValue;
18.1255 + if (DEBUG) dependentObservable._latestValue = _latestValue;
18.1256 + } finally {
18.1257 + ko.dependencyDetection.end();
18.1258 + }
18.1259 +
18.1260 + dependentObservable["notifySubscribers"](_latestValue);
18.1261 + _isBeingEvaluated = false;
18.1262 + if (!_subscriptionsToDependencies.length)
18.1263 + dispose();
18.1264 + }
18.1265 +
18.1266 + function dependentObservable() {
18.1267 + if (arguments.length > 0) {
18.1268 + if (typeof writeFunction === "function") {
18.1269 + // Writing a value
18.1270 + writeFunction.apply(evaluatorFunctionTarget, arguments);
18.1271 + } else {
18.1272 + throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
18.1273 + }
18.1274 + return this; // Permits chained assignments
18.1275 + } else {
18.1276 + // Reading the value
18.1277 + if (!_hasBeenEvaluated)
18.1278 + evaluateImmediate();
18.1279 + ko.dependencyDetection.registerDependency(dependentObservable);
18.1280 + return _latestValue;
18.1281 + }
18.1282 + }
18.1283 +
18.1284 + function peek() {
18.1285 + if (!_hasBeenEvaluated)
18.1286 + evaluateImmediate();
18.1287 + return _latestValue;
18.1288 + }
18.1289 +
18.1290 + function isActive() {
18.1291 + return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
18.1292 + }
18.1293 +
18.1294 + // By here, "options" is always non-null
18.1295 + var writeFunction = options["write"],
18.1296 + disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
18.1297 + disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
18.1298 + dispose = disposeAllSubscriptionsToDependencies,
18.1299 + _subscriptionsToDependencies = [],
18.1300 + evaluationTimeoutInstance = null;
18.1301 +
18.1302 + if (!evaluatorFunctionTarget)
18.1303 + evaluatorFunctionTarget = options["owner"];
18.1304 +
18.1305 + dependentObservable.peek = peek;
18.1306 + dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
18.1307 + dependentObservable.hasWriteFunction = typeof options["write"] === "function";
18.1308 + dependentObservable.dispose = function () { dispose(); };
18.1309 + dependentObservable.isActive = isActive;
18.1310 + dependentObservable.valueHasMutated = function() {
18.1311 + _hasBeenEvaluated = false;
18.1312 + evaluateImmediate();
18.1313 + };
18.1314 +
18.1315 + ko.subscribable.call(dependentObservable);
18.1316 + ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
18.1317 +
18.1318 + ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
18.1319 + ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
18.1320 + ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
18.1321 + ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
18.1322 +
18.1323 + // Evaluate, unless deferEvaluation is true
18.1324 + if (options['deferEvaluation'] !== true)
18.1325 + evaluateImmediate();
18.1326 +
18.1327 + // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
18.1328 + // But skip if isActive is false (there will never be any dependencies to dispose).
18.1329 + // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
18.1330 + // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
18.1331 + if (disposeWhenNodeIsRemoved && isActive()) {
18.1332 + dispose = function() {
18.1333 + ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
18.1334 + disposeAllSubscriptionsToDependencies();
18.1335 + };
18.1336 + ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
18.1337 + var existingDisposeWhenFunction = disposeWhen;
18.1338 + disposeWhen = function () {
18.1339 + return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
18.1340 + }
18.1341 + }
18.1342 +
18.1343 + return dependentObservable;
18.1344 +};
18.1345 +
18.1346 +ko.isComputed = function(instance) {
18.1347 + return ko.hasPrototype(instance, ko.dependentObservable);
18.1348 +};
18.1349 +
18.1350 +var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
18.1351 +ko.dependentObservable[protoProp] = ko.observable;
18.1352 +
18.1353 +ko.dependentObservable['fn'] = {};
18.1354 +ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
18.1355 +
18.1356 +ko.exportSymbol('dependentObservable', ko.dependentObservable);
18.1357 +ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
18.1358 +ko.exportSymbol('isComputed', ko.isComputed);
18.1359 +
18.1360 +(function() {
18.1361 + var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
18.1362 +
18.1363 + ko.toJS = function(rootObject) {
18.1364 + if (arguments.length == 0)
18.1365 + throw new Error("When calling ko.toJS, pass the object you want to convert.");
18.1366 +
18.1367 + // We just unwrap everything at every level in the object graph
18.1368 + return mapJsObjectGraph(rootObject, function(valueToMap) {
18.1369 + // Loop because an observable's value might in turn be another observable wrapper
18.1370 + for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
18.1371 + valueToMap = valueToMap();
18.1372 + return valueToMap;
18.1373 + });
18.1374 + };
18.1375 +
18.1376 + ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
18.1377 + var plainJavaScriptObject = ko.toJS(rootObject);
18.1378 + return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
18.1379 + };
18.1380 +
18.1381 + function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
18.1382 + visitedObjects = visitedObjects || new objectLookup();
18.1383 +
18.1384 + rootObject = mapInputCallback(rootObject);
18.1385 + var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
18.1386 + if (!canHaveProperties)
18.1387 + return rootObject;
18.1388 +
18.1389 + var outputProperties = rootObject instanceof Array ? [] : {};
18.1390 + visitedObjects.save(rootObject, outputProperties);
18.1391 +
18.1392 + visitPropertiesOrArrayEntries(rootObject, function(indexer) {
18.1393 + var propertyValue = mapInputCallback(rootObject[indexer]);
18.1394 +
18.1395 + switch (typeof propertyValue) {
18.1396 + case "boolean":
18.1397 + case "number":
18.1398 + case "string":
18.1399 + case "function":
18.1400 + outputProperties[indexer] = propertyValue;
18.1401 + break;
18.1402 + case "object":
18.1403 + case "undefined":
18.1404 + var previouslyMappedValue = visitedObjects.get(propertyValue);
18.1405 + outputProperties[indexer] = (previouslyMappedValue !== undefined)
18.1406 + ? previouslyMappedValue
18.1407 + : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
18.1408 + break;
18.1409 + }
18.1410 + });
18.1411 +
18.1412 + return outputProperties;
18.1413 + }
18.1414 +
18.1415 + function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
18.1416 + if (rootObject instanceof Array) {
18.1417 + for (var i = 0; i < rootObject.length; i++)
18.1418 + visitorCallback(i);
18.1419 +
18.1420 + // For arrays, also respect toJSON property for custom mappings (fixes #278)
18.1421 + if (typeof rootObject['toJSON'] == 'function')
18.1422 + visitorCallback('toJSON');
18.1423 + } else {
18.1424 + for (var propertyName in rootObject)
18.1425 + visitorCallback(propertyName);
18.1426 + }
18.1427 + };
18.1428 +
18.1429 + function objectLookup() {
18.1430 + var keys = [];
18.1431 + var values = [];
18.1432 + this.save = function(key, value) {
18.1433 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
18.1434 + if (existingIndex >= 0)
18.1435 + values[existingIndex] = value;
18.1436 + else {
18.1437 + keys.push(key);
18.1438 + values.push(value);
18.1439 + }
18.1440 + };
18.1441 + this.get = function(key) {
18.1442 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
18.1443 + return (existingIndex >= 0) ? values[existingIndex] : undefined;
18.1444 + };
18.1445 + };
18.1446 +})();
18.1447 +
18.1448 +ko.exportSymbol('toJS', ko.toJS);
18.1449 +ko.exportSymbol('toJSON', ko.toJSON);
18.1450 +(function () {
18.1451 + var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
18.1452 +
18.1453 + // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
18.1454 + // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
18.1455 + // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
18.1456 + ko.selectExtensions = {
18.1457 + readValue : function(element) {
18.1458 + switch (ko.utils.tagNameLower(element)) {
18.1459 + case 'option':
18.1460 + if (element[hasDomDataExpandoProperty] === true)
18.1461 + return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
18.1462 + return ko.utils.ieVersion <= 7
18.1463 + ? (element.getAttributeNode('value').specified ? element.value : element.text)
18.1464 + : element.value;
18.1465 + case 'select':
18.1466 + return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
18.1467 + default:
18.1468 + return element.value;
18.1469 + }
18.1470 + },
18.1471 +
18.1472 + writeValue: function(element, value) {
18.1473 + switch (ko.utils.tagNameLower(element)) {
18.1474 + case 'option':
18.1475 + switch(typeof value) {
18.1476 + case "string":
18.1477 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
18.1478 + if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
18.1479 + delete element[hasDomDataExpandoProperty];
18.1480 + }
18.1481 + element.value = value;
18.1482 + break;
18.1483 + default:
18.1484 + // Store arbitrary object using DomData
18.1485 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
18.1486 + element[hasDomDataExpandoProperty] = true;
18.1487 +
18.1488 + // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
18.1489 + element.value = typeof value === "number" ? value : "";
18.1490 + break;
18.1491 + }
18.1492 + break;
18.1493 + case 'select':
18.1494 + for (var i = element.options.length - 1; i >= 0; i--) {
18.1495 + if (ko.selectExtensions.readValue(element.options[i]) == value) {
18.1496 + element.selectedIndex = i;
18.1497 + break;
18.1498 + }
18.1499 + }
18.1500 + break;
18.1501 + default:
18.1502 + if ((value === null) || (value === undefined))
18.1503 + value = "";
18.1504 + element.value = value;
18.1505 + break;
18.1506 + }
18.1507 + }
18.1508 + };
18.1509 +})();
18.1510 +
18.1511 +ko.exportSymbol('selectExtensions', ko.selectExtensions);
18.1512 +ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
18.1513 +ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
18.1514 +ko.expressionRewriting = (function () {
18.1515 + var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
18.1516 + var javaScriptReservedWords = ["true", "false"];
18.1517 +
18.1518 + // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
18.1519 + // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
18.1520 + var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
18.1521 +
18.1522 + function restoreTokens(string, tokens) {
18.1523 + var prevValue = null;
18.1524 + while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
18.1525 + prevValue = string;
18.1526 + string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
18.1527 + return tokens[tokenIndex];
18.1528 + });
18.1529 + }
18.1530 + return string;
18.1531 + }
18.1532 +
18.1533 + function getWriteableValue(expression) {
18.1534 + if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
18.1535 + return false;
18.1536 + var match = expression.match(javaScriptAssignmentTarget);
18.1537 + return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
18.1538 + }
18.1539 +
18.1540 + function ensureQuoted(key) {
18.1541 + var trimmedKey = ko.utils.stringTrim(key);
18.1542 + switch (trimmedKey.length && trimmedKey.charAt(0)) {
18.1543 + case "'":
18.1544 + case '"':
18.1545 + return key;
18.1546 + default:
18.1547 + return "'" + trimmedKey + "'";
18.1548 + }
18.1549 + }
18.1550 +
18.1551 + return {
18.1552 + bindingRewriteValidators: [],
18.1553 +
18.1554 + parseObjectLiteral: function(objectLiteralString) {
18.1555 + // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
18.1556 + // that is sufficient just to split an object literal string into a set of top-level key-value pairs
18.1557 +
18.1558 + var str = ko.utils.stringTrim(objectLiteralString);
18.1559 + if (str.length < 3)
18.1560 + return [];
18.1561 + if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
18.1562 + str = str.substring(1, str.length - 1);
18.1563 +
18.1564 + // Pull out any string literals and regex literals
18.1565 + var tokens = [];
18.1566 + var tokenStart = null, tokenEndChar;
18.1567 + for (var position = 0; position < str.length; position++) {
18.1568 + var c = str.charAt(position);
18.1569 + if (tokenStart === null) {
18.1570 + switch (c) {
18.1571 + case '"':
18.1572 + case "'":
18.1573 + case "/":
18.1574 + tokenStart = position;
18.1575 + tokenEndChar = c;
18.1576 + break;
18.1577 + }
18.1578 + } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
18.1579 + var token = str.substring(tokenStart, position + 1);
18.1580 + tokens.push(token);
18.1581 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
18.1582 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
18.1583 + position -= (token.length - replacement.length);
18.1584 + tokenStart = null;
18.1585 + }
18.1586 + }
18.1587 +
18.1588 + // Next pull out balanced paren, brace, and bracket blocks
18.1589 + tokenStart = null;
18.1590 + tokenEndChar = null;
18.1591 + var tokenDepth = 0, tokenStartChar = null;
18.1592 + for (var position = 0; position < str.length; position++) {
18.1593 + var c = str.charAt(position);
18.1594 + if (tokenStart === null) {
18.1595 + switch (c) {
18.1596 + case "{": tokenStart = position; tokenStartChar = c;
18.1597 + tokenEndChar = "}";
18.1598 + break;
18.1599 + case "(": tokenStart = position; tokenStartChar = c;
18.1600 + tokenEndChar = ")";
18.1601 + break;
18.1602 + case "[": tokenStart = position; tokenStartChar = c;
18.1603 + tokenEndChar = "]";
18.1604 + break;
18.1605 + }
18.1606 + }
18.1607 +
18.1608 + if (c === tokenStartChar)
18.1609 + tokenDepth++;
18.1610 + else if (c === tokenEndChar) {
18.1611 + tokenDepth--;
18.1612 + if (tokenDepth === 0) {
18.1613 + var token = str.substring(tokenStart, position + 1);
18.1614 + tokens.push(token);
18.1615 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
18.1616 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
18.1617 + position -= (token.length - replacement.length);
18.1618 + tokenStart = null;
18.1619 + }
18.1620 + }
18.1621 + }
18.1622 +
18.1623 + // Now we can safely split on commas to get the key/value pairs
18.1624 + var result = [];
18.1625 + var keyValuePairs = str.split(",");
18.1626 + for (var i = 0, j = keyValuePairs.length; i < j; i++) {
18.1627 + var pair = keyValuePairs[i];
18.1628 + var colonPos = pair.indexOf(":");
18.1629 + if ((colonPos > 0) && (colonPos < pair.length - 1)) {
18.1630 + var key = pair.substring(0, colonPos);
18.1631 + var value = pair.substring(colonPos + 1);
18.1632 + result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
18.1633 + } else {
18.1634 + result.push({ 'unknown': restoreTokens(pair, tokens) });
18.1635 + }
18.1636 + }
18.1637 + return result;
18.1638 + },
18.1639 +
18.1640 + preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
18.1641 + var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
18.1642 + ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
18.1643 + : objectLiteralStringOrKeyValueArray;
18.1644 + var resultStrings = [], propertyAccessorResultStrings = [];
18.1645 +
18.1646 + var keyValueEntry;
18.1647 + for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
18.1648 + if (resultStrings.length > 0)
18.1649 + resultStrings.push(",");
18.1650 +
18.1651 + if (keyValueEntry['key']) {
18.1652 + var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
18.1653 + resultStrings.push(quotedKey);
18.1654 + resultStrings.push(":");
18.1655 + resultStrings.push(val);
18.1656 +
18.1657 + if (val = getWriteableValue(ko.utils.stringTrim(val))) {
18.1658 + if (propertyAccessorResultStrings.length > 0)
18.1659 + propertyAccessorResultStrings.push(", ");
18.1660 + propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
18.1661 + }
18.1662 + } else if (keyValueEntry['unknown']) {
18.1663 + resultStrings.push(keyValueEntry['unknown']);
18.1664 + }
18.1665 + }
18.1666 +
18.1667 + var combinedResult = resultStrings.join("");
18.1668 + if (propertyAccessorResultStrings.length > 0) {
18.1669 + var allPropertyAccessors = propertyAccessorResultStrings.join("");
18.1670 + combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
18.1671 + }
18.1672 +
18.1673 + return combinedResult;
18.1674 + },
18.1675 +
18.1676 + keyValueArrayContainsKey: function(keyValueArray, key) {
18.1677 + for (var i = 0; i < keyValueArray.length; i++)
18.1678 + if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
18.1679 + return true;
18.1680 + return false;
18.1681 + },
18.1682 +
18.1683 + // Internal, private KO utility for updating model properties from within bindings
18.1684 + // property: If the property being updated is (or might be) an observable, pass it here
18.1685 + // If it turns out to be a writable observable, it will be written to directly
18.1686 + // allBindingsAccessor: All bindings in the current execution context.
18.1687 + // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
18.1688 + // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
18.1689 + // value: The value to be written
18.1690 + // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
18.1691 + // it is !== existing value on that writable observable
18.1692 + writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
18.1693 + if (!property || !ko.isWriteableObservable(property)) {
18.1694 + var propWriters = allBindingsAccessor()['_ko_property_writers'];
18.1695 + if (propWriters && propWriters[key])
18.1696 + propWriters[key](value);
18.1697 + } else if (!checkIfDifferent || property.peek() !== value) {
18.1698 + property(value);
18.1699 + }
18.1700 + }
18.1701 + };
18.1702 +})();
18.1703 +
18.1704 +ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
18.1705 +ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
18.1706 +ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
18.1707 +ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
18.1708 +
18.1709 +// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
18.1710 +// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
18.1711 +ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
18.1712 +ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
18.1713 + // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
18.1714 + // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
18.1715 + // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
18.1716 + // of that virtual hierarchy
18.1717 + //
18.1718 + // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
18.1719 + // without having to scatter special cases all over the binding and templating code.
18.1720 +
18.1721 + // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
18.1722 + // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
18.1723 + // So, use node.text where available, and node.nodeValue elsewhere
18.1724 + var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
18.1725 +
18.1726 + var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
18.1727 + var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
18.1728 + var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
18.1729 +
18.1730 + function isStartComment(node) {
18.1731 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
18.1732 + }
18.1733 +
18.1734 + function isEndComment(node) {
18.1735 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
18.1736 + }
18.1737 +
18.1738 + function getVirtualChildren(startComment, allowUnbalanced) {
18.1739 + var currentNode = startComment;
18.1740 + var depth = 1;
18.1741 + var children = [];
18.1742 + while (currentNode = currentNode.nextSibling) {
18.1743 + if (isEndComment(currentNode)) {
18.1744 + depth--;
18.1745 + if (depth === 0)
18.1746 + return children;
18.1747 + }
18.1748 +
18.1749 + children.push(currentNode);
18.1750 +
18.1751 + if (isStartComment(currentNode))
18.1752 + depth++;
18.1753 + }
18.1754 + if (!allowUnbalanced)
18.1755 + throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
18.1756 + return null;
18.1757 + }
18.1758 +
18.1759 + function getMatchingEndComment(startComment, allowUnbalanced) {
18.1760 + var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
18.1761 + if (allVirtualChildren) {
18.1762 + if (allVirtualChildren.length > 0)
18.1763 + return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
18.1764 + return startComment.nextSibling;
18.1765 + } else
18.1766 + return null; // Must have no matching end comment, and allowUnbalanced is true
18.1767 + }
18.1768 +
18.1769 + function getUnbalancedChildTags(node) {
18.1770 + // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
18.1771 + // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
18.1772 + var childNode = node.firstChild, captureRemaining = null;
18.1773 + if (childNode) {
18.1774 + do {
18.1775 + if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
18.1776 + captureRemaining.push(childNode);
18.1777 + else if (isStartComment(childNode)) {
18.1778 + var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
18.1779 + if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
18.1780 + childNode = matchingEndComment;
18.1781 + else
18.1782 + captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
18.1783 + } else if (isEndComment(childNode)) {
18.1784 + captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
18.1785 + }
18.1786 + } while (childNode = childNode.nextSibling);
18.1787 + }
18.1788 + return captureRemaining;
18.1789 + }
18.1790 +
18.1791 + ko.virtualElements = {
18.1792 + allowedBindings: {},
18.1793 +
18.1794 + childNodes: function(node) {
18.1795 + return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
18.1796 + },
18.1797 +
18.1798 + emptyNode: function(node) {
18.1799 + if (!isStartComment(node))
18.1800 + ko.utils.emptyDomNode(node);
18.1801 + else {
18.1802 + var virtualChildren = ko.virtualElements.childNodes(node);
18.1803 + for (var i = 0, j = virtualChildren.length; i < j; i++)
18.1804 + ko.removeNode(virtualChildren[i]);
18.1805 + }
18.1806 + },
18.1807 +
18.1808 + setDomNodeChildren: function(node, childNodes) {
18.1809 + if (!isStartComment(node))
18.1810 + ko.utils.setDomNodeChildren(node, childNodes);
18.1811 + else {
18.1812 + ko.virtualElements.emptyNode(node);
18.1813 + var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
18.1814 + for (var i = 0, j = childNodes.length; i < j; i++)
18.1815 + endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
18.1816 + }
18.1817 + },
18.1818 +
18.1819 + prepend: function(containerNode, nodeToPrepend) {
18.1820 + if (!isStartComment(containerNode)) {
18.1821 + if (containerNode.firstChild)
18.1822 + containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
18.1823 + else
18.1824 + containerNode.appendChild(nodeToPrepend);
18.1825 + } else {
18.1826 + // Start comments must always have a parent and at least one following sibling (the end comment)
18.1827 + containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
18.1828 + }
18.1829 + },
18.1830 +
18.1831 + insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
18.1832 + if (!insertAfterNode) {
18.1833 + ko.virtualElements.prepend(containerNode, nodeToInsert);
18.1834 + } else if (!isStartComment(containerNode)) {
18.1835 + // Insert after insertion point
18.1836 + if (insertAfterNode.nextSibling)
18.1837 + containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
18.1838 + else
18.1839 + containerNode.appendChild(nodeToInsert);
18.1840 + } else {
18.1841 + // Children of start comments must always have a parent and at least one following sibling (the end comment)
18.1842 + containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
18.1843 + }
18.1844 + },
18.1845 +
18.1846 + firstChild: function(node) {
18.1847 + if (!isStartComment(node))
18.1848 + return node.firstChild;
18.1849 + if (!node.nextSibling || isEndComment(node.nextSibling))
18.1850 + return null;
18.1851 + return node.nextSibling;
18.1852 + },
18.1853 +
18.1854 + nextSibling: function(node) {
18.1855 + if (isStartComment(node))
18.1856 + node = getMatchingEndComment(node);
18.1857 + if (node.nextSibling && isEndComment(node.nextSibling))
18.1858 + return null;
18.1859 + return node.nextSibling;
18.1860 + },
18.1861 +
18.1862 + virtualNodeBindingValue: function(node) {
18.1863 + var regexMatch = isStartComment(node);
18.1864 + return regexMatch ? regexMatch[1] : null;
18.1865 + },
18.1866 +
18.1867 + normaliseVirtualElementDomStructure: function(elementVerified) {
18.1868 + // Workaround for https://github.com/SteveSanderson/knockout/issues/155
18.1869 + // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
18.1870 + // that are direct descendants of <ul> into the preceding <li>)
18.1871 + if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
18.1872 + return;
18.1873 +
18.1874 + // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
18.1875 + // must be intended to appear *after* that child, so move them there.
18.1876 + var childNode = elementVerified.firstChild;
18.1877 + if (childNode) {
18.1878 + do {
18.1879 + if (childNode.nodeType === 1) {
18.1880 + var unbalancedTags = getUnbalancedChildTags(childNode);
18.1881 + if (unbalancedTags) {
18.1882 + // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
18.1883 + var nodeToInsertBefore = childNode.nextSibling;
18.1884 + for (var i = 0; i < unbalancedTags.length; i++) {
18.1885 + if (nodeToInsertBefore)
18.1886 + elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
18.1887 + else
18.1888 + elementVerified.appendChild(unbalancedTags[i]);
18.1889 + }
18.1890 + }
18.1891 + }
18.1892 + } while (childNode = childNode.nextSibling);
18.1893 + }
18.1894 + }
18.1895 + };
18.1896 +})();
18.1897 +ko.exportSymbol('virtualElements', ko.virtualElements);
18.1898 +ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
18.1899 +ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
18.1900 +//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
18.1901 +ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
18.1902 +//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
18.1903 +ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
18.1904 +ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
18.1905 +(function() {
18.1906 + var defaultBindingAttributeName = "data-bind";
18.1907 +
18.1908 + ko.bindingProvider = function() {
18.1909 + this.bindingCache = {};
18.1910 + };
18.1911 +
18.1912 + ko.utils.extend(ko.bindingProvider.prototype, {
18.1913 + 'nodeHasBindings': function(node) {
18.1914 + switch (node.nodeType) {
18.1915 + case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
18.1916 + case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
18.1917 + default: return false;
18.1918 + }
18.1919 + },
18.1920 +
18.1921 + 'getBindings': function(node, bindingContext) {
18.1922 + var bindingsString = this['getBindingsString'](node, bindingContext);
18.1923 + return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
18.1924 + },
18.1925 +
18.1926 + // The following function is only used internally by this default provider.
18.1927 + // It's not part of the interface definition for a general binding provider.
18.1928 + 'getBindingsString': function(node, bindingContext) {
18.1929 + switch (node.nodeType) {
18.1930 + case 1: return node.getAttribute(defaultBindingAttributeName); // Element
18.1931 + case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
18.1932 + default: return null;
18.1933 + }
18.1934 + },
18.1935 +
18.1936 + // The following function is only used internally by this default provider.
18.1937 + // It's not part of the interface definition for a general binding provider.
18.1938 + 'parseBindingsString': function(bindingsString, bindingContext, node) {
18.1939 + try {
18.1940 + var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
18.1941 + return bindingFunction(bindingContext, node);
18.1942 + } catch (ex) {
18.1943 + throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
18.1944 + }
18.1945 + }
18.1946 + });
18.1947 +
18.1948 + ko.bindingProvider['instance'] = new ko.bindingProvider();
18.1949 +
18.1950 + function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
18.1951 + var cacheKey = bindingsString;
18.1952 + return cache[cacheKey]
18.1953 + || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
18.1954 + }
18.1955 +
18.1956 + function createBindingsStringEvaluator(bindingsString) {
18.1957 + // Build the source for a function that evaluates "expression"
18.1958 + // For each scope variable, add an extra level of "with" nesting
18.1959 + // Example result: with(sc1) { with(sc0) { return (expression) } }
18.1960 + var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
18.1961 + functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
18.1962 + return new Function("$context", "$element", functionBody);
18.1963 + }
18.1964 +})();
18.1965 +
18.1966 +ko.exportSymbol('bindingProvider', ko.bindingProvider);
18.1967 +(function () {
18.1968 + ko.bindingHandlers = {};
18.1969 +
18.1970 + ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
18.1971 + if (parentBindingContext) {
18.1972 + ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
18.1973 + this['$parentContext'] = parentBindingContext;
18.1974 + this['$parent'] = parentBindingContext['$data'];
18.1975 + this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
18.1976 + this['$parents'].unshift(this['$parent']);
18.1977 + } else {
18.1978 + this['$parents'] = [];
18.1979 + this['$root'] = dataItem;
18.1980 + // Export 'ko' in the binding context so it will be available in bindings and templates
18.1981 + // even if 'ko' isn't exported as a global, such as when using an AMD loader.
18.1982 + // See https://github.com/SteveSanderson/knockout/issues/490
18.1983 + this['ko'] = ko;
18.1984 + }
18.1985 + this['$data'] = dataItem;
18.1986 + if (dataItemAlias)
18.1987 + this[dataItemAlias] = dataItem;
18.1988 + }
18.1989 + ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
18.1990 + return new ko.bindingContext(dataItem, this, dataItemAlias);
18.1991 + };
18.1992 + ko.bindingContext.prototype['extend'] = function(properties) {
18.1993 + var clone = ko.utils.extend(new ko.bindingContext(), this);
18.1994 + return ko.utils.extend(clone, properties);
18.1995 + };
18.1996 +
18.1997 + function validateThatBindingIsAllowedForVirtualElements(bindingName) {
18.1998 + var validator = ko.virtualElements.allowedBindings[bindingName];
18.1999 + if (!validator)
18.2000 + throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
18.2001 + }
18.2002 +
18.2003 + function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
18.2004 + var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
18.2005 + while (currentChild = nextInQueue) {
18.2006 + // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
18.2007 + nextInQueue = ko.virtualElements.nextSibling(currentChild);
18.2008 + applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
18.2009 + }
18.2010 + }
18.2011 +
18.2012 + function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
18.2013 + var shouldBindDescendants = true;
18.2014 +
18.2015 + // Perf optimisation: Apply bindings only if...
18.2016 + // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
18.2017 + // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
18.2018 + // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
18.2019 + var isElement = (nodeVerified.nodeType === 1);
18.2020 + if (isElement) // Workaround IE <= 8 HTML parsing weirdness
18.2021 + ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
18.2022 +
18.2023 + var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
18.2024 + || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
18.2025 + if (shouldApplyBindings)
18.2026 + shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
18.2027 +
18.2028 + if (shouldBindDescendants) {
18.2029 + // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
18.2030 + // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
18.2031 + // hence bindingContextsMayDifferFromDomParentElement is false
18.2032 + // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
18.2033 + // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
18.2034 + // hence bindingContextsMayDifferFromDomParentElement is true
18.2035 + applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
18.2036 + }
18.2037 + }
18.2038 +
18.2039 + function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
18.2040 + // Need to be sure that inits are only run once, and updates never run until all the inits have been run
18.2041 + var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
18.2042 +
18.2043 + // Each time the dependentObservable is evaluated (after data changes),
18.2044 + // the binding attribute is reparsed so that it can pick out the correct
18.2045 + // model properties in the context of the changed data.
18.2046 + // DOM event callbacks need to be able to access this changed data,
18.2047 + // so we need a single parsedBindings variable (shared by all callbacks
18.2048 + // associated with this node's bindings) that all the closures can access.
18.2049 + var parsedBindings;
18.2050 + function makeValueAccessor(bindingKey) {
18.2051 + return function () { return parsedBindings[bindingKey] }
18.2052 + }
18.2053 + function parsedBindingsAccessor() {
18.2054 + return parsedBindings;
18.2055 + }
18.2056 +
18.2057 + var bindingHandlerThatControlsDescendantBindings;
18.2058 + ko.dependentObservable(
18.2059 + function () {
18.2060 + // Ensure we have a nonnull binding context to work with
18.2061 + var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
18.2062 + ? viewModelOrBindingContext
18.2063 + : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
18.2064 + var viewModel = bindingContextInstance['$data'];
18.2065 +
18.2066 + // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
18.2067 + // we can easily recover it just by scanning up the node's ancestors in the DOM
18.2068 + // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
18.2069 + if (bindingContextMayDifferFromDomParentElement)
18.2070 + ko.storedBindingContextForNode(node, bindingContextInstance);
18.2071 +
18.2072 + // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
18.2073 + var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
18.2074 + parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
18.2075 +
18.2076 + if (parsedBindings) {
18.2077 + // First run all the inits, so bindings can register for notification on changes
18.2078 + if (initPhase === 0) {
18.2079 + initPhase = 1;
18.2080 + for (var bindingKey in parsedBindings) {
18.2081 + var binding = ko.bindingHandlers[bindingKey];
18.2082 + if (binding && node.nodeType === 8)
18.2083 + validateThatBindingIsAllowedForVirtualElements(bindingKey);
18.2084 +
18.2085 + if (binding && typeof binding["init"] == "function") {
18.2086 + var handlerInitFn = binding["init"];
18.2087 + var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
18.2088 +
18.2089 + // If this binding handler claims to control descendant bindings, make a note of this
18.2090 + if (initResult && initResult['controlsDescendantBindings']) {
18.2091 + if (bindingHandlerThatControlsDescendantBindings !== undefined)
18.2092 + throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
18.2093 + bindingHandlerThatControlsDescendantBindings = bindingKey;
18.2094 + }
18.2095 + }
18.2096 + }
18.2097 + initPhase = 2;
18.2098 + }
18.2099 +
18.2100 + // ... then run all the updates, which might trigger changes even on the first evaluation
18.2101 + if (initPhase === 2) {
18.2102 + for (var bindingKey in parsedBindings) {
18.2103 + var binding = ko.bindingHandlers[bindingKey];
18.2104 + if (binding && typeof binding["update"] == "function") {
18.2105 + var handlerUpdateFn = binding["update"];
18.2106 + handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
18.2107 + }
18.2108 + }
18.2109 + }
18.2110 + }
18.2111 + },
18.2112 + null,
18.2113 + { disposeWhenNodeIsRemoved : node }
18.2114 + );
18.2115 +
18.2116 + return {
18.2117 + shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
18.2118 + };
18.2119 + };
18.2120 +
18.2121 + var storedBindingContextDomDataKey = "__ko_bindingContext__";
18.2122 + ko.storedBindingContextForNode = function (node, bindingContext) {
18.2123 + if (arguments.length == 2)
18.2124 + ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
18.2125 + else
18.2126 + return ko.utils.domData.get(node, storedBindingContextDomDataKey);
18.2127 + }
18.2128 +
18.2129 + ko.applyBindingsToNode = function (node, bindings, viewModel) {
18.2130 + if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
18.2131 + ko.virtualElements.normaliseVirtualElementDomStructure(node);
18.2132 + return applyBindingsToNodeInternal(node, bindings, viewModel, true);
18.2133 + };
18.2134 +
18.2135 + ko.applyBindingsToDescendants = function(viewModel, rootNode) {
18.2136 + if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
18.2137 + applyBindingsToDescendantsInternal(viewModel, rootNode, true);
18.2138 + };
18.2139 +
18.2140 + ko.applyBindings = function (viewModel, rootNode) {
18.2141 + if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
18.2142 + throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
18.2143 + rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
18.2144 +
18.2145 + applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
18.2146 + };
18.2147 +
18.2148 + // Retrieving binding context from arbitrary nodes
18.2149 + ko.contextFor = function(node) {
18.2150 + // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
18.2151 + switch (node.nodeType) {
18.2152 + case 1:
18.2153 + case 8:
18.2154 + var context = ko.storedBindingContextForNode(node);
18.2155 + if (context) return context;
18.2156 + if (node.parentNode) return ko.contextFor(node.parentNode);
18.2157 + break;
18.2158 + }
18.2159 + return undefined;
18.2160 + };
18.2161 + ko.dataFor = function(node) {
18.2162 + var context = ko.contextFor(node);
18.2163 + return context ? context['$data'] : undefined;
18.2164 + };
18.2165 +
18.2166 + ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
18.2167 + ko.exportSymbol('applyBindings', ko.applyBindings);
18.2168 + ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
18.2169 + ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
18.2170 + ko.exportSymbol('contextFor', ko.contextFor);
18.2171 + ko.exportSymbol('dataFor', ko.dataFor);
18.2172 +})();
18.2173 +var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
18.2174 +ko.bindingHandlers['attr'] = {
18.2175 + 'update': function(element, valueAccessor, allBindingsAccessor) {
18.2176 + var value = ko.utils.unwrapObservable(valueAccessor()) || {};
18.2177 + for (var attrName in value) {
18.2178 + if (typeof attrName == "string") {
18.2179 + var attrValue = ko.utils.unwrapObservable(value[attrName]);
18.2180 +
18.2181 + // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
18.2182 + // when someProp is a "no value"-like value (strictly null, false, or undefined)
18.2183 + // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
18.2184 + var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
18.2185 + if (toRemove)
18.2186 + element.removeAttribute(attrName);
18.2187 +
18.2188 + // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
18.2189 + // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
18.2190 + // but instead of figuring out the mode, we'll just set the attribute through the Javascript
18.2191 + // property for IE <= 8.
18.2192 + if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
18.2193 + attrName = attrHtmlToJavascriptMap[attrName];
18.2194 + if (toRemove)
18.2195 + element.removeAttribute(attrName);
18.2196 + else
18.2197 + element[attrName] = attrValue;
18.2198 + } else if (!toRemove) {
18.2199 + try {
18.2200 + element.setAttribute(attrName, attrValue.toString());
18.2201 + } catch (err) {
18.2202 + // ignore for now
18.2203 + if (console) {
18.2204 + console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
18.2205 + }
18.2206 + }
18.2207 + }
18.2208 +
18.2209 + // Treat "name" specially - although you can think of it as an attribute, it also needs
18.2210 + // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
18.2211 + // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
18.2212 + // entirely, and there's no strong reason to allow for such casing in HTML.
18.2213 + if (attrName === "name") {
18.2214 + ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
18.2215 + }
18.2216 + }
18.2217 + }
18.2218 + }
18.2219 +};
18.2220 +ko.bindingHandlers['checked'] = {
18.2221 + 'init': function (element, valueAccessor, allBindingsAccessor) {
18.2222 + var updateHandler = function() {
18.2223 + var valueToWrite;
18.2224 + if (element.type == "checkbox") {
18.2225 + valueToWrite = element.checked;
18.2226 + } else if ((element.type == "radio") && (element.checked)) {
18.2227 + valueToWrite = element.value;
18.2228 + } else {
18.2229 + return; // "checked" binding only responds to checkboxes and selected radio buttons
18.2230 + }
18.2231 +
18.2232 + var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
18.2233 + if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
18.2234 + // For checkboxes bound to an array, we add/remove the checkbox value to that array
18.2235 + // This works for both observable and non-observable arrays
18.2236 + var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
18.2237 + if (element.checked && (existingEntryIndex < 0))
18.2238 + modelValue.push(element.value);
18.2239 + else if ((!element.checked) && (existingEntryIndex >= 0))
18.2240 + modelValue.splice(existingEntryIndex, 1);
18.2241 + } else {
18.2242 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
18.2243 + }
18.2244 + };
18.2245 + ko.utils.registerEventHandler(element, "click", updateHandler);
18.2246 +
18.2247 + // IE 6 won't allow radio buttons to be selected unless they have a name
18.2248 + if ((element.type == "radio") && !element.name)
18.2249 + ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
18.2250 + },
18.2251 + 'update': function (element, valueAccessor) {
18.2252 + var value = ko.utils.unwrapObservable(valueAccessor());
18.2253 +
18.2254 + if (element.type == "checkbox") {
18.2255 + if (value instanceof Array) {
18.2256 + // When bound to an array, the checkbox being checked represents its value being present in that array
18.2257 + element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
18.2258 + } else {
18.2259 + // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
18.2260 + element.checked = value;
18.2261 + }
18.2262 + } else if (element.type == "radio") {
18.2263 + element.checked = (element.value == value);
18.2264 + }
18.2265 + }
18.2266 +};
18.2267 +var classesWrittenByBindingKey = '__ko__cssValue';
18.2268 +ko.bindingHandlers['css'] = {
18.2269 + 'update': function (element, valueAccessor) {
18.2270 + var value = ko.utils.unwrapObservable(valueAccessor());
18.2271 + if (typeof value == "object") {
18.2272 + for (var className in value) {
18.2273 + var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
18.2274 + ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
18.2275 + }
18.2276 + } else {
18.2277 + value = String(value || ''); // Make sure we don't try to store or set a non-string value
18.2278 + ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
18.2279 + element[classesWrittenByBindingKey] = value;
18.2280 + ko.utils.toggleDomNodeCssClass(element, value, true);
18.2281 + }
18.2282 + }
18.2283 +};
18.2284 +ko.bindingHandlers['enable'] = {
18.2285 + 'update': function (element, valueAccessor) {
18.2286 + var value = ko.utils.unwrapObservable(valueAccessor());
18.2287 + if (value && element.disabled)
18.2288 + element.removeAttribute("disabled");
18.2289 + else if ((!value) && (!element.disabled))
18.2290 + element.disabled = true;
18.2291 + }
18.2292 +};
18.2293 +
18.2294 +ko.bindingHandlers['disable'] = {
18.2295 + 'update': function (element, valueAccessor) {
18.2296 + ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
18.2297 + }
18.2298 +};
18.2299 +// For certain common events (currently just 'click'), allow a simplified data-binding syntax
18.2300 +// e.g. click:handler instead of the usual full-length event:{click:handler}
18.2301 +function makeEventHandlerShortcut(eventName) {
18.2302 + ko.bindingHandlers[eventName] = {
18.2303 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
18.2304 + var newValueAccessor = function () {
18.2305 + var result = {};
18.2306 + result[eventName] = valueAccessor();
18.2307 + return result;
18.2308 + };
18.2309 + return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
18.2310 + }
18.2311 + }
18.2312 +}
18.2313 +
18.2314 +ko.bindingHandlers['event'] = {
18.2315 + 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
18.2316 + var eventsToHandle = valueAccessor() || {};
18.2317 + for(var eventNameOutsideClosure in eventsToHandle) {
18.2318 + (function() {
18.2319 + var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
18.2320 + if (typeof eventName == "string") {
18.2321 + ko.utils.registerEventHandler(element, eventName, function (event) {
18.2322 + var handlerReturnValue;
18.2323 + var handlerFunction = valueAccessor()[eventName];
18.2324 + if (!handlerFunction)
18.2325 + return;
18.2326 + var allBindings = allBindingsAccessor();
18.2327 +
18.2328 + try {
18.2329 + // Take all the event args, and prefix with the viewmodel
18.2330 + var argsForHandler = ko.utils.makeArray(arguments);
18.2331 + argsForHandler.unshift(viewModel);
18.2332 + handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
18.2333 + } finally {
18.2334 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
18.2335 + if (event.preventDefault)
18.2336 + event.preventDefault();
18.2337 + else
18.2338 + event.returnValue = false;
18.2339 + }
18.2340 + }
18.2341 +
18.2342 + var bubble = allBindings[eventName + 'Bubble'] !== false;
18.2343 + if (!bubble) {
18.2344 + event.cancelBubble = true;
18.2345 + if (event.stopPropagation)
18.2346 + event.stopPropagation();
18.2347 + }
18.2348 + });
18.2349 + }
18.2350 + })();
18.2351 + }
18.2352 + }
18.2353 +};
18.2354 +// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
18.2355 +// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
18.2356 +ko.bindingHandlers['foreach'] = {
18.2357 + makeTemplateValueAccessor: function(valueAccessor) {
18.2358 + return function() {
18.2359 + var modelValue = valueAccessor(),
18.2360 + unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
18.2361 +
18.2362 + // If unwrappedValue is the array, pass in the wrapped value on its own
18.2363 + // The value will be unwrapped and tracked within the template binding
18.2364 + // (See https://github.com/SteveSanderson/knockout/issues/523)
18.2365 + if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
18.2366 + return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
18.2367 +
18.2368 + // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
18.2369 + ko.utils.unwrapObservable(modelValue);
18.2370 + return {
18.2371 + 'foreach': unwrappedValue['data'],
18.2372 + 'as': unwrappedValue['as'],
18.2373 + 'includeDestroyed': unwrappedValue['includeDestroyed'],
18.2374 + 'afterAdd': unwrappedValue['afterAdd'],
18.2375 + 'beforeRemove': unwrappedValue['beforeRemove'],
18.2376 + 'afterRender': unwrappedValue['afterRender'],
18.2377 + 'beforeMove': unwrappedValue['beforeMove'],
18.2378 + 'afterMove': unwrappedValue['afterMove'],
18.2379 + 'templateEngine': ko.nativeTemplateEngine.instance
18.2380 + };
18.2381 + };
18.2382 + },
18.2383 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
18.2384 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
18.2385 + },
18.2386 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
18.2387 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
18.2388 + }
18.2389 +};
18.2390 +ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
18.2391 +ko.virtualElements.allowedBindings['foreach'] = true;
18.2392 +var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
18.2393 +ko.bindingHandlers['hasfocus'] = {
18.2394 + 'init': function(element, valueAccessor, allBindingsAccessor) {
18.2395 + var handleElementFocusChange = function(isFocused) {
18.2396 + // Where possible, ignore which event was raised and determine focus state using activeElement,
18.2397 + // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
18.2398 + // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
18.2399 + // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
18.2400 + // from calling 'blur()' on the element when it loses focus.
18.2401 + // Discussion at https://github.com/SteveSanderson/knockout/pull/352
18.2402 + element[hasfocusUpdatingProperty] = true;
18.2403 + var ownerDoc = element.ownerDocument;
18.2404 + if ("activeElement" in ownerDoc) {
18.2405 + isFocused = (ownerDoc.activeElement === element);
18.2406 + }
18.2407 + var modelValue = valueAccessor();
18.2408 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
18.2409 + element[hasfocusUpdatingProperty] = false;
18.2410 + };
18.2411 + var handleElementFocusIn = handleElementFocusChange.bind(null, true);
18.2412 + var handleElementFocusOut = handleElementFocusChange.bind(null, false);
18.2413 +
18.2414 + ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
18.2415 + ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
18.2416 + ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
18.2417 + ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
18.2418 + },
18.2419 + 'update': function(element, valueAccessor) {
18.2420 + var value = ko.utils.unwrapObservable(valueAccessor());
18.2421 + if (!element[hasfocusUpdatingProperty]) {
18.2422 + value ? element.focus() : element.blur();
18.2423 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
18.2424 + }
18.2425 + }
18.2426 +};
18.2427 +ko.bindingHandlers['html'] = {
18.2428 + 'init': function() {
18.2429 + // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
18.2430 + return { 'controlsDescendantBindings': true };
18.2431 + },
18.2432 + 'update': function (element, valueAccessor) {
18.2433 + // setHtml will unwrap the value if needed
18.2434 + ko.utils.setHtml(element, valueAccessor());
18.2435 + }
18.2436 +};
18.2437 +var withIfDomDataKey = '__ko_withIfBindingData';
18.2438 +// Makes a binding like with or if
18.2439 +function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
18.2440 + ko.bindingHandlers[bindingKey] = {
18.2441 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
18.2442 + ko.utils.domData.set(element, withIfDomDataKey, {});
18.2443 + return { 'controlsDescendantBindings': true };
18.2444 + },
18.2445 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
18.2446 + var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
18.2447 + dataValue = ko.utils.unwrapObservable(valueAccessor()),
18.2448 + shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
18.2449 + isFirstRender = !withIfData.savedNodes,
18.2450 + needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
18.2451 +
18.2452 + if (needsRefresh) {
18.2453 + if (isFirstRender) {
18.2454 + withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
18.2455 + }
18.2456 +
18.2457 + if (shouldDisplay) {
18.2458 + if (!isFirstRender) {
18.2459 + ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
18.2460 + }
18.2461 + ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
18.2462 + } else {
18.2463 + ko.virtualElements.emptyNode(element);
18.2464 + }
18.2465 +
18.2466 + withIfData.didDisplayOnLastUpdate = shouldDisplay;
18.2467 + }
18.2468 + }
18.2469 + };
18.2470 + ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
18.2471 + ko.virtualElements.allowedBindings[bindingKey] = true;
18.2472 +}
18.2473 +
18.2474 +// Construct the actual binding handlers
18.2475 +makeWithIfBinding('if');
18.2476 +makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
18.2477 +makeWithIfBinding('with', true /* isWith */, false /* isNot */,
18.2478 + function(bindingContext, dataValue) {
18.2479 + return bindingContext['createChildContext'](dataValue);
18.2480 + }
18.2481 +);
18.2482 +function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
18.2483 + if (preferModelValue) {
18.2484 + if (modelValue !== ko.selectExtensions.readValue(element))
18.2485 + ko.selectExtensions.writeValue(element, modelValue);
18.2486 + }
18.2487 +
18.2488 + // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
18.2489 + // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
18.2490 + // change the model value to match the dropdown.
18.2491 + if (modelValue !== ko.selectExtensions.readValue(element))
18.2492 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
18.2493 +};
18.2494 +
18.2495 +ko.bindingHandlers['options'] = {
18.2496 + 'update': function (element, valueAccessor, allBindingsAccessor) {
18.2497 + if (ko.utils.tagNameLower(element) !== "select")
18.2498 + throw new Error("options binding applies only to SELECT elements");
18.2499 +
18.2500 + var selectWasPreviouslyEmpty = element.length == 0;
18.2501 + var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
18.2502 + return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
18.2503 + }), function (node) {
18.2504 + return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
18.2505 + });
18.2506 + var previousScrollTop = element.scrollTop;
18.2507 +
18.2508 + var value = ko.utils.unwrapObservable(valueAccessor());
18.2509 + var selectedValue = element.value;
18.2510 +
18.2511 + // Remove all existing <option>s.
18.2512 + // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
18.2513 + while (element.length > 0) {
18.2514 + ko.cleanNode(element.options[0]);
18.2515 + element.remove(0);
18.2516 + }
18.2517 +
18.2518 + if (value) {
18.2519 + var allBindings = allBindingsAccessor(),
18.2520 + includeDestroyed = allBindings['optionsIncludeDestroyed'];
18.2521 +
18.2522 + if (typeof value.length != "number")
18.2523 + value = [value];
18.2524 + if (allBindings['optionsCaption']) {
18.2525 + var option = document.createElement("option");
18.2526 + ko.utils.setHtml(option, allBindings['optionsCaption']);
18.2527 + ko.selectExtensions.writeValue(option, undefined);
18.2528 + element.appendChild(option);
18.2529 + }
18.2530 +
18.2531 + for (var i = 0, j = value.length; i < j; i++) {
18.2532 + // Skip destroyed items
18.2533 + var arrayEntry = value[i];
18.2534 + if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
18.2535 + continue;
18.2536 +
18.2537 + var option = document.createElement("option");
18.2538 +
18.2539 + function applyToObject(object, predicate, defaultValue) {
18.2540 + var predicateType = typeof predicate;
18.2541 + if (predicateType == "function") // Given a function; run it against the data value
18.2542 + return predicate(object);
18.2543 + else if (predicateType == "string") // Given a string; treat it as a property name on the data value
18.2544 + return object[predicate];
18.2545 + else // Given no optionsText arg; use the data value itself
18.2546 + return defaultValue;
18.2547 + }
18.2548 +
18.2549 + // Apply a value to the option element
18.2550 + var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
18.2551 + ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
18.2552 +
18.2553 + // Apply some text to the option element
18.2554 + var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
18.2555 + ko.utils.setTextContent(option, optionText);
18.2556 +
18.2557 + element.appendChild(option);
18.2558 + }
18.2559 +
18.2560 + // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
18.2561 + // That's why we first added them without selection. Now it's time to set the selection.
18.2562 + var newOptions = element.getElementsByTagName("option");
18.2563 + var countSelectionsRetained = 0;
18.2564 + for (var i = 0, j = newOptions.length; i < j; i++) {
18.2565 + if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
18.2566 + ko.utils.setOptionNodeSelectionState(newOptions[i], true);
18.2567 + countSelectionsRetained++;
18.2568 + }
18.2569 + }
18.2570 +
18.2571 + element.scrollTop = previousScrollTop;
18.2572 +
18.2573 + if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
18.2574 + // Ensure consistency between model value and selected option.
18.2575 + // If the dropdown is being populated for the first time here (or was otherwise previously empty),
18.2576 + // the dropdown selection state is meaningless, so we preserve the model value.
18.2577 + ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
18.2578 + }
18.2579 +
18.2580 + // Workaround for IE9 bug
18.2581 + ko.utils.ensureSelectElementIsRenderedCorrectly(element);
18.2582 + }
18.2583 + }
18.2584 +};
18.2585 +ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
18.2586 +ko.bindingHandlers['selectedOptions'] = {
18.2587 + 'init': function (element, valueAccessor, allBindingsAccessor) {
18.2588 + ko.utils.registerEventHandler(element, "change", function () {
18.2589 + var value = valueAccessor(), valueToWrite = [];
18.2590 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
18.2591 + if (node.selected)
18.2592 + valueToWrite.push(ko.selectExtensions.readValue(node));
18.2593 + });
18.2594 + ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
18.2595 + });
18.2596 + },
18.2597 + 'update': function (element, valueAccessor) {
18.2598 + if (ko.utils.tagNameLower(element) != "select")
18.2599 + throw new Error("values binding applies only to SELECT elements");
18.2600 +
18.2601 + var newValue = ko.utils.unwrapObservable(valueAccessor());
18.2602 + if (newValue && typeof newValue.length == "number") {
18.2603 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
18.2604 + var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
18.2605 + ko.utils.setOptionNodeSelectionState(node, isSelected);
18.2606 + });
18.2607 + }
18.2608 + }
18.2609 +};
18.2610 +ko.bindingHandlers['style'] = {
18.2611 + 'update': function (element, valueAccessor) {
18.2612 + var value = ko.utils.unwrapObservable(valueAccessor() || {});
18.2613 + for (var styleName in value) {
18.2614 + if (typeof styleName == "string") {
18.2615 + var styleValue = ko.utils.unwrapObservable(value[styleName]);
18.2616 + element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
18.2617 + }
18.2618 + }
18.2619 + }
18.2620 +};
18.2621 +ko.bindingHandlers['submit'] = {
18.2622 + 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
18.2623 + if (typeof valueAccessor() != "function")
18.2624 + throw new Error("The value for a submit binding must be a function");
18.2625 + ko.utils.registerEventHandler(element, "submit", function (event) {
18.2626 + var handlerReturnValue;
18.2627 + var value = valueAccessor();
18.2628 + try { handlerReturnValue = value.call(viewModel, element); }
18.2629 + finally {
18.2630 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
18.2631 + if (event.preventDefault)
18.2632 + event.preventDefault();
18.2633 + else
18.2634 + event.returnValue = false;
18.2635 + }
18.2636 + }
18.2637 + });
18.2638 + }
18.2639 +};
18.2640 +ko.bindingHandlers['text'] = {
18.2641 + 'update': function (element, valueAccessor) {
18.2642 + ko.utils.setTextContent(element, valueAccessor());
18.2643 + }
18.2644 +};
18.2645 +ko.virtualElements.allowedBindings['text'] = true;
18.2646 +ko.bindingHandlers['uniqueName'] = {
18.2647 + 'init': function (element, valueAccessor) {
18.2648 + if (valueAccessor()) {
18.2649 + var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
18.2650 + ko.utils.setElementName(element, name);
18.2651 + }
18.2652 + }
18.2653 +};
18.2654 +ko.bindingHandlers['uniqueName'].currentIndex = 0;
18.2655 +ko.bindingHandlers['value'] = {
18.2656 + 'init': function (element, valueAccessor, allBindingsAccessor) {
18.2657 + // Always catch "change" event; possibly other events too if asked
18.2658 + var eventsToCatch = ["change"];
18.2659 + var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
18.2660 + var propertyChangedFired = false;
18.2661 + if (requestedEventsToCatch) {
18.2662 + if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
18.2663 + requestedEventsToCatch = [requestedEventsToCatch];
18.2664 + ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
18.2665 + eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
18.2666 + }
18.2667 +
18.2668 + var valueUpdateHandler = function() {
18.2669 + propertyChangedFired = false;
18.2670 + var modelValue = valueAccessor();
18.2671 + var elementValue = ko.selectExtensions.readValue(element);
18.2672 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
18.2673 + }
18.2674 +
18.2675 + // Workaround for https://github.com/SteveSanderson/knockout/issues/122
18.2676 + // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
18.2677 + var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
18.2678 + && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
18.2679 + if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
18.2680 + ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
18.2681 + ko.utils.registerEventHandler(element, "blur", function() {
18.2682 + if (propertyChangedFired) {
18.2683 + valueUpdateHandler();
18.2684 + }
18.2685 + });
18.2686 + }
18.2687 +
18.2688 + ko.utils.arrayForEach(eventsToCatch, function(eventName) {
18.2689 + // The syntax "after<eventname>" means "run the handler asynchronously after the event"
18.2690 + // This is useful, for example, to catch "keydown" events after the browser has updated the control
18.2691 + // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
18.2692 + var handler = valueUpdateHandler;
18.2693 + if (ko.utils.stringStartsWith(eventName, "after")) {
18.2694 + handler = function() { setTimeout(valueUpdateHandler, 0) };
18.2695 + eventName = eventName.substring("after".length);
18.2696 + }
18.2697 + ko.utils.registerEventHandler(element, eventName, handler);
18.2698 + });
18.2699 + },
18.2700 + 'update': function (element, valueAccessor) {
18.2701 + var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
18.2702 + var newValue = ko.utils.unwrapObservable(valueAccessor());
18.2703 + var elementValue = ko.selectExtensions.readValue(element);
18.2704 + var valueHasChanged = (newValue != elementValue);
18.2705 +
18.2706 + // JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
18.2707 + // We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
18.2708 + if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
18.2709 + valueHasChanged = true;
18.2710 +
18.2711 + if (valueHasChanged) {
18.2712 + var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
18.2713 + applyValueAction();
18.2714 +
18.2715 + // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
18.2716 + // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
18.2717 + // to apply the value as well.
18.2718 + var alsoApplyAsynchronously = valueIsSelectOption;
18.2719 + if (alsoApplyAsynchronously)
18.2720 + setTimeout(applyValueAction, 0);
18.2721 + }
18.2722 +
18.2723 + // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
18.2724 + // because you're not allowed to have a model value that disagrees with a visible UI selection.
18.2725 + if (valueIsSelectOption && (element.length > 0))
18.2726 + ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
18.2727 + }
18.2728 +};
18.2729 +ko.bindingHandlers['visible'] = {
18.2730 + 'update': function (element, valueAccessor) {
18.2731 + var value = ko.utils.unwrapObservable(valueAccessor());
18.2732 + var isCurrentlyVisible = !(element.style.display == "none");
18.2733 + if (value && !isCurrentlyVisible)
18.2734 + element.style.display = "";
18.2735 + else if ((!value) && isCurrentlyVisible)
18.2736 + element.style.display = "none";
18.2737 + }
18.2738 +};
18.2739 +// 'click' is just a shorthand for the usual full-length event:{click:handler}
18.2740 +makeEventHandlerShortcut('click');
18.2741 +// If you want to make a custom template engine,
18.2742 +//
18.2743 +// [1] Inherit from this class (like ko.nativeTemplateEngine does)
18.2744 +// [2] Override 'renderTemplateSource', supplying a function with this signature:
18.2745 +//
18.2746 +// function (templateSource, bindingContext, options) {
18.2747 +// // - templateSource.text() is the text of the template you should render
18.2748 +// // - bindingContext.$data is the data you should pass into the template
18.2749 +// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
18.2750 +// // and bindingContext.$root available in the template too
18.2751 +// // - options gives you access to any other properties set on "data-bind: { template: options }"
18.2752 +// //
18.2753 +// // Return value: an array of DOM nodes
18.2754 +// }
18.2755 +//
18.2756 +// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
18.2757 +//
18.2758 +// function (script) {
18.2759 +// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
18.2760 +// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
18.2761 +// }
18.2762 +//
18.2763 +// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
18.2764 +// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
18.2765 +// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
18.2766 +
18.2767 +ko.templateEngine = function () { };
18.2768 +
18.2769 +ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
18.2770 + throw new Error("Override renderTemplateSource");
18.2771 +};
18.2772 +
18.2773 +ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
18.2774 + throw new Error("Override createJavaScriptEvaluatorBlock");
18.2775 +};
18.2776 +
18.2777 +ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
18.2778 + // Named template
18.2779 + if (typeof template == "string") {
18.2780 + templateDocument = templateDocument || document;
18.2781 + var elem = templateDocument.getElementById(template);
18.2782 + if (!elem)
18.2783 + throw new Error("Cannot find template with ID " + template);
18.2784 + return new ko.templateSources.domElement(elem);
18.2785 + } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
18.2786 + // Anonymous template
18.2787 + return new ko.templateSources.anonymousTemplate(template);
18.2788 + } else
18.2789 + throw new Error("Unknown template type: " + template);
18.2790 +};
18.2791 +
18.2792 +ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
18.2793 + var templateSource = this['makeTemplateSource'](template, templateDocument);
18.2794 + return this['renderTemplateSource'](templateSource, bindingContext, options);
18.2795 +};
18.2796 +
18.2797 +ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
18.2798 + // Skip rewriting if requested
18.2799 + if (this['allowTemplateRewriting'] === false)
18.2800 + return true;
18.2801 + return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
18.2802 +};
18.2803 +
18.2804 +ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
18.2805 + var templateSource = this['makeTemplateSource'](template, templateDocument);
18.2806 + var rewritten = rewriterCallback(templateSource['text']());
18.2807 + templateSource['text'](rewritten);
18.2808 + templateSource['data']("isRewritten", true);
18.2809 +};
18.2810 +
18.2811 +ko.exportSymbol('templateEngine', ko.templateEngine);
18.2812 +
18.2813 +ko.templateRewriting = (function () {
18.2814 + var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
18.2815 + var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
18.2816 +
18.2817 + function validateDataBindValuesForRewriting(keyValueArray) {
18.2818 + var allValidators = ko.expressionRewriting.bindingRewriteValidators;
18.2819 + for (var i = 0; i < keyValueArray.length; i++) {
18.2820 + var key = keyValueArray[i]['key'];
18.2821 + if (allValidators.hasOwnProperty(key)) {
18.2822 + var validator = allValidators[key];
18.2823 +
18.2824 + if (typeof validator === "function") {
18.2825 + var possibleErrorMessage = validator(keyValueArray[i]['value']);
18.2826 + if (possibleErrorMessage)
18.2827 + throw new Error(possibleErrorMessage);
18.2828 + } else if (!validator) {
18.2829 + throw new Error("This template engine does not support the '" + key + "' binding within its templates");
18.2830 + }
18.2831 + }
18.2832 + }
18.2833 + }
18.2834 +
18.2835 + function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
18.2836 + var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
18.2837 + validateDataBindValuesForRewriting(dataBindKeyValueArray);
18.2838 + var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
18.2839 +
18.2840 + // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
18.2841 + // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
18.2842 + // extra indirection.
18.2843 + var applyBindingsToNextSiblingScript =
18.2844 + "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
18.2845 + return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
18.2846 + }
18.2847 +
18.2848 + return {
18.2849 + ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
18.2850 + if (!templateEngine['isTemplateRewritten'](template, templateDocument))
18.2851 + templateEngine['rewriteTemplate'](template, function (htmlString) {
18.2852 + return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
18.2853 + }, templateDocument);
18.2854 + },
18.2855 +
18.2856 + memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
18.2857 + return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
18.2858 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
18.2859 + }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
18.2860 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
18.2861 + });
18.2862 + },
18.2863 +
18.2864 + applyMemoizedBindingsToNextSibling: function (bindings) {
18.2865 + return ko.memoization.memoize(function (domNode, bindingContext) {
18.2866 + if (domNode.nextSibling)
18.2867 + ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
18.2868 + });
18.2869 + }
18.2870 + }
18.2871 +})();
18.2872 +
18.2873 +
18.2874 +// Exported only because it has to be referenced by string lookup from within rewritten template
18.2875 +ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
18.2876 +(function() {
18.2877 + // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
18.2878 + // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
18.2879 + //
18.2880 + // Two are provided by default:
18.2881 + // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
18.2882 + // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
18.2883 + // without reading/writing the actual element text content, since it will be overwritten
18.2884 + // with the rendered template output.
18.2885 + // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
18.2886 + // Template sources need to have the following functions:
18.2887 + // text() - returns the template text from your storage location
18.2888 + // text(value) - writes the supplied template text to your storage location
18.2889 + // data(key) - reads values stored using data(key, value) - see below
18.2890 + // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
18.2891 + //
18.2892 + // Optionally, template sources can also have the following functions:
18.2893 + // nodes() - returns a DOM element containing the nodes of this template, where available
18.2894 + // nodes(value) - writes the given DOM element to your storage location
18.2895 + // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
18.2896 + // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
18.2897 + //
18.2898 + // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
18.2899 + // using and overriding "makeTemplateSource" to return an instance of your custom template source.
18.2900 +
18.2901 + ko.templateSources = {};
18.2902 +
18.2903 + // ---- ko.templateSources.domElement -----
18.2904 +
18.2905 + ko.templateSources.domElement = function(element) {
18.2906 + this.domElement = element;
18.2907 + }
18.2908 +
18.2909 + ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
18.2910 + var tagNameLower = ko.utils.tagNameLower(this.domElement),
18.2911 + elemContentsProperty = tagNameLower === "script" ? "text"
18.2912 + : tagNameLower === "textarea" ? "value"
18.2913 + : "innerHTML";
18.2914 +
18.2915 + if (arguments.length == 0) {
18.2916 + return this.domElement[elemContentsProperty];
18.2917 + } else {
18.2918 + var valueToWrite = arguments[0];
18.2919 + if (elemContentsProperty === "innerHTML")
18.2920 + ko.utils.setHtml(this.domElement, valueToWrite);
18.2921 + else
18.2922 + this.domElement[elemContentsProperty] = valueToWrite;
18.2923 + }
18.2924 + };
18.2925 +
18.2926 + ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
18.2927 + if (arguments.length === 1) {
18.2928 + return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
18.2929 + } else {
18.2930 + ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
18.2931 + }
18.2932 + };
18.2933 +
18.2934 + // ---- ko.templateSources.anonymousTemplate -----
18.2935 + // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
18.2936 + // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
18.2937 + // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
18.2938 +
18.2939 + var anonymousTemplatesDomDataKey = "__ko_anon_template__";
18.2940 + ko.templateSources.anonymousTemplate = function(element) {
18.2941 + this.domElement = element;
18.2942 + }
18.2943 + ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
18.2944 + ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
18.2945 + if (arguments.length == 0) {
18.2946 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
18.2947 + if (templateData.textData === undefined && templateData.containerData)
18.2948 + templateData.textData = templateData.containerData.innerHTML;
18.2949 + return templateData.textData;
18.2950 + } else {
18.2951 + var valueToWrite = arguments[0];
18.2952 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
18.2953 + }
18.2954 + };
18.2955 + ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
18.2956 + if (arguments.length == 0) {
18.2957 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
18.2958 + return templateData.containerData;
18.2959 + } else {
18.2960 + var valueToWrite = arguments[0];
18.2961 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
18.2962 + }
18.2963 + };
18.2964 +
18.2965 + ko.exportSymbol('templateSources', ko.templateSources);
18.2966 + ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
18.2967 + ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
18.2968 +})();
18.2969 +(function () {
18.2970 + var _templateEngine;
18.2971 + ko.setTemplateEngine = function (templateEngine) {
18.2972 + if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
18.2973 + throw new Error("templateEngine must inherit from ko.templateEngine");
18.2974 + _templateEngine = templateEngine;
18.2975 + }
18.2976 +
18.2977 + function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
18.2978 + var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
18.2979 + while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
18.2980 + nextInQueue = ko.virtualElements.nextSibling(node);
18.2981 + if (node.nodeType === 1 || node.nodeType === 8)
18.2982 + action(node);
18.2983 + }
18.2984 + }
18.2985 +
18.2986 + function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
18.2987 + // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
18.2988 + // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
18.2989 + // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
18.2990 + // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
18.2991 + // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
18.2992 +
18.2993 + if (continuousNodeArray.length) {
18.2994 + var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
18.2995 +
18.2996 + // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
18.2997 + // whereas a regular applyBindings won't introduce new memoized nodes
18.2998 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
18.2999 + ko.applyBindings(bindingContext, node);
18.3000 + });
18.3001 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
18.3002 + ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
18.3003 + });
18.3004 + }
18.3005 + }
18.3006 +
18.3007 + function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
18.3008 + return nodeOrNodeArray.nodeType ? nodeOrNodeArray
18.3009 + : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
18.3010 + : null;
18.3011 + }
18.3012 +
18.3013 + function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
18.3014 + options = options || {};
18.3015 + var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
18.3016 + var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
18.3017 + var templateEngineToUse = (options['templateEngine'] || _templateEngine);
18.3018 + ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
18.3019 + var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
18.3020 +
18.3021 + // Loosely check result is an array of DOM nodes
18.3022 + if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
18.3023 + throw new Error("Template engine must return an array of DOM nodes");
18.3024 +
18.3025 + var haveAddedNodesToParent = false;
18.3026 + switch (renderMode) {
18.3027 + case "replaceChildren":
18.3028 + ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
18.3029 + haveAddedNodesToParent = true;
18.3030 + break;
18.3031 + case "replaceNode":
18.3032 + ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
18.3033 + haveAddedNodesToParent = true;
18.3034 + break;
18.3035 + case "ignoreTargetNode": break;
18.3036 + default:
18.3037 + throw new Error("Unknown renderMode: " + renderMode);
18.3038 + }
18.3039 +
18.3040 + if (haveAddedNodesToParent) {
18.3041 + activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
18.3042 + if (options['afterRender'])
18.3043 + ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
18.3044 + }
18.3045 +
18.3046 + return renderedNodesArray;
18.3047 + }
18.3048 +
18.3049 + ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
18.3050 + options = options || {};
18.3051 + if ((options['templateEngine'] || _templateEngine) == undefined)
18.3052 + throw new Error("Set a template engine before calling renderTemplate");
18.3053 + renderMode = renderMode || "replaceChildren";
18.3054 +
18.3055 + if (targetNodeOrNodeArray) {
18.3056 + var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
18.3057 +
18.3058 + var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
18.3059 + var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
18.3060 +
18.3061 + return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
18.3062 + function () {
18.3063 + // Ensure we've got a proper binding context to work with
18.3064 + var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
18.3065 + ? dataOrBindingContext
18.3066 + : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
18.3067 +
18.3068 + // Support selecting template as a function of the data being rendered
18.3069 + var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
18.3070 +
18.3071 + var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
18.3072 + if (renderMode == "replaceNode") {
18.3073 + targetNodeOrNodeArray = renderedNodesArray;
18.3074 + firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
18.3075 + }
18.3076 + },
18.3077 + null,
18.3078 + { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
18.3079 + );
18.3080 + } else {
18.3081 + // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
18.3082 + return ko.memoization.memoize(function (domNode) {
18.3083 + ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
18.3084 + });
18.3085 + }
18.3086 + };
18.3087 +
18.3088 + ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
18.3089 + // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
18.3090 + // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
18.3091 + var arrayItemContext;
18.3092 +
18.3093 + // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
18.3094 + var executeTemplateForArrayItem = function (arrayValue, index) {
18.3095 + // Support selecting template as a function of the data being rendered
18.3096 + arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
18.3097 + arrayItemContext['$index'] = index;
18.3098 + var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
18.3099 + return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
18.3100 + }
18.3101 +
18.3102 + // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
18.3103 + var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
18.3104 + activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
18.3105 + if (options['afterRender'])
18.3106 + options['afterRender'](addedNodesArray, arrayValue);
18.3107 + };
18.3108 +
18.3109 + return ko.dependentObservable(function () {
18.3110 + var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
18.3111 + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
18.3112 + unwrappedArray = [unwrappedArray];
18.3113 +
18.3114 + // Filter out any entries marked as destroyed
18.3115 + var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
18.3116 + return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
18.3117 + });
18.3118 +
18.3119 + // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
18.3120 + // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
18.3121 + ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
18.3122 +
18.3123 + }, null, { disposeWhenNodeIsRemoved: targetNode });
18.3124 + };
18.3125 +
18.3126 + var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
18.3127 + function disposeOldComputedAndStoreNewOne(element, newComputed) {
18.3128 + var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
18.3129 + if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
18.3130 + oldComputed.dispose();
18.3131 + ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
18.3132 + }
18.3133 +
18.3134 + ko.bindingHandlers['template'] = {
18.3135 + 'init': function(element, valueAccessor) {
18.3136 + // Support anonymous templates
18.3137 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
18.3138 + if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
18.3139 + // It's an anonymous template - store the element contents, then clear the element
18.3140 + var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
18.3141 + container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
18.3142 + new ko.templateSources.anonymousTemplate(element)['nodes'](container);
18.3143 + }
18.3144 + return { 'controlsDescendantBindings': true };
18.3145 + },
18.3146 + 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
18.3147 + var templateName = ko.utils.unwrapObservable(valueAccessor()),
18.3148 + options = {},
18.3149 + shouldDisplay = true,
18.3150 + dataValue,
18.3151 + templateComputed = null;
18.3152 +
18.3153 + if (typeof templateName != "string") {
18.3154 + options = templateName;
18.3155 + templateName = options['name'];
18.3156 +
18.3157 + // Support "if"/"ifnot" conditions
18.3158 + if ('if' in options)
18.3159 + shouldDisplay = ko.utils.unwrapObservable(options['if']);
18.3160 + if (shouldDisplay && 'ifnot' in options)
18.3161 + shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
18.3162 +
18.3163 + dataValue = ko.utils.unwrapObservable(options['data']);
18.3164 + }
18.3165 +
18.3166 + if ('foreach' in options) {
18.3167 + // Render once for each data point (treating data set as empty if shouldDisplay==false)
18.3168 + var dataArray = (shouldDisplay && options['foreach']) || [];
18.3169 + templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
18.3170 + } else if (!shouldDisplay) {
18.3171 + ko.virtualElements.emptyNode(element);
18.3172 + } else {
18.3173 + // Render once for this single data point (or use the viewModel if no data was provided)
18.3174 + var innerBindingContext = ('data' in options) ?
18.3175 + bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
18.3176 + bindingContext; // Given no explicit 'data' value, we retain the same binding context
18.3177 + templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
18.3178 + }
18.3179 +
18.3180 + // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
18.3181 + disposeOldComputedAndStoreNewOne(element, templateComputed);
18.3182 + }
18.3183 + };
18.3184 +
18.3185 + // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
18.3186 + ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
18.3187 + var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
18.3188 +
18.3189 + if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
18.3190 + return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
18.3191 +
18.3192 + if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
18.3193 + return null; // Named templates can be rewritten, so return "no error"
18.3194 + return "This template engine does not support anonymous templates nested within its templates";
18.3195 + };
18.3196 +
18.3197 + ko.virtualElements.allowedBindings['template'] = true;
18.3198 +})();
18.3199 +
18.3200 +ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
18.3201 +ko.exportSymbol('renderTemplate', ko.renderTemplate);
18.3202 +
18.3203 +ko.utils.compareArrays = (function () {
18.3204 + var statusNotInOld = 'added', statusNotInNew = 'deleted';
18.3205 +
18.3206 + // Simple calculation based on Levenshtein distance.
18.3207 + function compareArrays(oldArray, newArray, dontLimitMoves) {
18.3208 + oldArray = oldArray || [];
18.3209 + newArray = newArray || [];
18.3210 +
18.3211 + if (oldArray.length <= newArray.length)
18.3212 + return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
18.3213 + else
18.3214 + return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
18.3215 + }
18.3216 +
18.3217 + function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
18.3218 + var myMin = Math.min,
18.3219 + myMax = Math.max,
18.3220 + editDistanceMatrix = [],
18.3221 + smlIndex, smlIndexMax = smlArray.length,
18.3222 + bigIndex, bigIndexMax = bigArray.length,
18.3223 + compareRange = (bigIndexMax - smlIndexMax) || 1,
18.3224 + maxDistance = smlIndexMax + bigIndexMax + 1,
18.3225 + thisRow, lastRow,
18.3226 + bigIndexMaxForRow, bigIndexMinForRow;
18.3227 +
18.3228 + for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
18.3229 + lastRow = thisRow;
18.3230 + editDistanceMatrix.push(thisRow = []);
18.3231 + bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
18.3232 + bigIndexMinForRow = myMax(0, smlIndex - 1);
18.3233 + for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
18.3234 + if (!bigIndex)
18.3235 + thisRow[bigIndex] = smlIndex + 1;
18.3236 + else if (!smlIndex) // Top row - transform empty array into new array via additions
18.3237 + thisRow[bigIndex] = bigIndex + 1;
18.3238 + else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
18.3239 + thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
18.3240 + else {
18.3241 + var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
18.3242 + var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
18.3243 + thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
18.3244 + }
18.3245 + }
18.3246 + }
18.3247 +
18.3248 + var editScript = [], meMinusOne, notInSml = [], notInBig = [];
18.3249 + for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
18.3250 + meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
18.3251 + if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
18.3252 + notInSml.push(editScript[editScript.length] = { // added
18.3253 + 'status': statusNotInSml,
18.3254 + 'value': bigArray[--bigIndex],
18.3255 + 'index': bigIndex });
18.3256 + } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
18.3257 + notInBig.push(editScript[editScript.length] = { // deleted
18.3258 + 'status': statusNotInBig,
18.3259 + 'value': smlArray[--smlIndex],
18.3260 + 'index': smlIndex });
18.3261 + } else {
18.3262 + editScript.push({
18.3263 + 'status': "retained",
18.3264 + 'value': bigArray[--bigIndex] });
18.3265 + --smlIndex;
18.3266 + }
18.3267 + }
18.3268 +
18.3269 + if (notInSml.length && notInBig.length) {
18.3270 + // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
18.3271 + // smlIndexMax keeps the time complexity of this algorithm linear.
18.3272 + var limitFailedCompares = smlIndexMax * 10, failedCompares,
18.3273 + a, d, notInSmlItem, notInBigItem;
18.3274 + // Go through the items that have been added and deleted and try to find matches between them.
18.3275 + for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
18.3276 + for (d = 0; notInBigItem = notInBig[d]; d++) {
18.3277 + if (notInSmlItem['value'] === notInBigItem['value']) {
18.3278 + notInSmlItem['moved'] = notInBigItem['index'];
18.3279 + notInBigItem['moved'] = notInSmlItem['index'];
18.3280 + notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
18.3281 + failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
18.3282 + break;
18.3283 + }
18.3284 + }
18.3285 + failedCompares += d;
18.3286 + }
18.3287 + }
18.3288 + return editScript.reverse();
18.3289 + }
18.3290 +
18.3291 + return compareArrays;
18.3292 +})();
18.3293 +
18.3294 +ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
18.3295 +
18.3296 +(function () {
18.3297 + // Objective:
18.3298 + // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
18.3299 + // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
18.3300 + // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
18.3301 + // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
18.3302 + // previously mapped - retain those nodes, and just insert/delete other ones
18.3303 +
18.3304 + // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
18.3305 + // You can use this, for example, to activate bindings on those nodes.
18.3306 +
18.3307 + function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
18.3308 + // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
18.3309 + // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
18.3310 + // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
18.3311 + // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
18.3312 + // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
18.3313 + //
18.3314 + // Rules:
18.3315 + // [A] Any leading nodes that aren't in the document any more should be ignored
18.3316 + // These most likely correspond to memoization nodes that were already removed during binding
18.3317 + // See https://github.com/SteveSanderson/knockout/pull/440
18.3318 + // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
18.3319 + // have already been removed, and include any nodes that have been inserted among the previous collection
18.3320 +
18.3321 + // Rule [A]
18.3322 + while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
18.3323 + contiguousNodeArray.splice(0, 1);
18.3324 +
18.3325 + // Rule [B]
18.3326 + if (contiguousNodeArray.length > 1) {
18.3327 + // Build up the actual new contiguous node set
18.3328 + var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
18.3329 + while (current !== last) {
18.3330 + current = current.nextSibling;
18.3331 + if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
18.3332 + return;
18.3333 + newContiguousSet.push(current);
18.3334 + }
18.3335 +
18.3336 + // ... then mutate the input array to match this.
18.3337 + // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
18.3338 + Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
18.3339 + }
18.3340 + return contiguousNodeArray;
18.3341 + }
18.3342 +
18.3343 + function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
18.3344 + // Map this array value inside a dependentObservable so we re-map when any dependency changes
18.3345 + var mappedNodes = [];
18.3346 + var dependentObservable = ko.dependentObservable(function() {
18.3347 + var newMappedNodes = mapping(valueToMap, index) || [];
18.3348 +
18.3349 + // On subsequent evaluations, just replace the previously-inserted DOM nodes
18.3350 + if (mappedNodes.length > 0) {
18.3351 + ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
18.3352 + if (callbackAfterAddingNodes)
18.3353 + ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
18.3354 + }
18.3355 +
18.3356 + // Replace the contents of the mappedNodes array, thereby updating the record
18.3357 + // of which nodes would be deleted if valueToMap was itself later removed
18.3358 + mappedNodes.splice(0, mappedNodes.length);
18.3359 + ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
18.3360 + }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
18.3361 + return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
18.3362 + }
18.3363 +
18.3364 + var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
18.3365 +
18.3366 + ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
18.3367 + // Compare the provided array against the previous one
18.3368 + array = array || [];
18.3369 + options = options || {};
18.3370 + var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
18.3371 + var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
18.3372 + var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
18.3373 + var editScript = ko.utils.compareArrays(lastArray, array);
18.3374 +
18.3375 + // Build the new mapping result
18.3376 + var newMappingResult = [];
18.3377 + var lastMappingResultIndex = 0;
18.3378 + var newMappingResultIndex = 0;
18.3379 +
18.3380 + var nodesToDelete = [];
18.3381 + var itemsToProcess = [];
18.3382 + var itemsForBeforeRemoveCallbacks = [];
18.3383 + var itemsForMoveCallbacks = [];
18.3384 + var itemsForAfterAddCallbacks = [];
18.3385 + var mapData;
18.3386 +
18.3387 + function itemMovedOrRetained(editScriptIndex, oldPosition) {
18.3388 + mapData = lastMappingResult[oldPosition];
18.3389 + if (newMappingResultIndex !== oldPosition)
18.3390 + itemsForMoveCallbacks[editScriptIndex] = mapData;
18.3391 + // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
18.3392 + mapData.indexObservable(newMappingResultIndex++);
18.3393 + fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
18.3394 + newMappingResult.push(mapData);
18.3395 + itemsToProcess.push(mapData);
18.3396 + }
18.3397 +
18.3398 + function callCallback(callback, items) {
18.3399 + if (callback) {
18.3400 + for (var i = 0, n = items.length; i < n; i++) {
18.3401 + if (items[i]) {
18.3402 + ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
18.3403 + callback(node, i, items[i].arrayEntry);
18.3404 + });
18.3405 + }
18.3406 + }
18.3407 + }
18.3408 + }
18.3409 +
18.3410 + for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
18.3411 + movedIndex = editScriptItem['moved'];
18.3412 + switch (editScriptItem['status']) {
18.3413 + case "deleted":
18.3414 + if (movedIndex === undefined) {
18.3415 + mapData = lastMappingResult[lastMappingResultIndex];
18.3416 +
18.3417 + // Stop tracking changes to the mapping for these nodes
18.3418 + if (mapData.dependentObservable)
18.3419 + mapData.dependentObservable.dispose();
18.3420 +
18.3421 + // Queue these nodes for later removal
18.3422 + nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
18.3423 + if (options['beforeRemove']) {
18.3424 + itemsForBeforeRemoveCallbacks[i] = mapData;
18.3425 + itemsToProcess.push(mapData);
18.3426 + }
18.3427 + }
18.3428 + lastMappingResultIndex++;
18.3429 + break;
18.3430 +
18.3431 + case "retained":
18.3432 + itemMovedOrRetained(i, lastMappingResultIndex++);
18.3433 + break;
18.3434 +
18.3435 + case "added":
18.3436 + if (movedIndex !== undefined) {
18.3437 + itemMovedOrRetained(i, movedIndex);
18.3438 + } else {
18.3439 + mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
18.3440 + newMappingResult.push(mapData);
18.3441 + itemsToProcess.push(mapData);
18.3442 + if (!isFirstExecution)
18.3443 + itemsForAfterAddCallbacks[i] = mapData;
18.3444 + }
18.3445 + break;
18.3446 + }
18.3447 + }
18.3448 +
18.3449 + // Call beforeMove first before any changes have been made to the DOM
18.3450 + callCallback(options['beforeMove'], itemsForMoveCallbacks);
18.3451 +
18.3452 + // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
18.3453 + ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
18.3454 +
18.3455 + // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
18.3456 + for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
18.3457 + // Get nodes for newly added items
18.3458 + if (!mapData.mappedNodes)
18.3459 + ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
18.3460 +
18.3461 + // Put nodes in the right place if they aren't there already
18.3462 + for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
18.3463 + if (node !== nextNode)
18.3464 + ko.virtualElements.insertAfter(domNode, node, lastNode);
18.3465 + }
18.3466 +
18.3467 + // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
18.3468 + if (!mapData.initialized && callbackAfterAddingNodes) {
18.3469 + callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
18.3470 + mapData.initialized = true;
18.3471 + }
18.3472 + }
18.3473 +
18.3474 + // If there's a beforeRemove callback, call it after reordering.
18.3475 + // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
18.3476 + // some sort of animation, which is why we first reorder the nodes that will be removed. If the
18.3477 + // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
18.3478 + // Perhaps we'll make that change in the future if this scenario becomes more common.
18.3479 + callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
18.3480 +
18.3481 + // Finally call afterMove and afterAdd callbacks
18.3482 + callCallback(options['afterMove'], itemsForMoveCallbacks);
18.3483 + callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
18.3484 +
18.3485 + // Store a copy of the array items we just considered so we can difference it next time
18.3486 + ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
18.3487 + }
18.3488 +})();
18.3489 +
18.3490 +ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
18.3491 +ko.nativeTemplateEngine = function () {
18.3492 + this['allowTemplateRewriting'] = false;
18.3493 +}
18.3494 +
18.3495 +ko.nativeTemplateEngine.prototype = new ko.templateEngine();
18.3496 +ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
18.3497 + var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
18.3498 + templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
18.3499 + templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
18.3500 +
18.3501 + if (templateNodes) {
18.3502 + return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
18.3503 + } else {
18.3504 + var templateText = templateSource['text']();
18.3505 + return ko.utils.parseHtmlFragment(templateText);
18.3506 + }
18.3507 +};
18.3508 +
18.3509 +ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
18.3510 +ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
18.3511 +
18.3512 +ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
18.3513 +(function() {
18.3514 + ko.jqueryTmplTemplateEngine = function () {
18.3515 + // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
18.3516 + // doesn't expose a version number, so we have to infer it.
18.3517 + // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
18.3518 + // which KO internally refers to as version "2", so older versions are no longer detected.
18.3519 + var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
18.3520 + if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
18.3521 + return 0;
18.3522 + // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
18.3523 + try {
18.3524 + if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
18.3525 + // Since 1.0.0pre, custom tags should append markup to an array called "__"
18.3526 + return 2; // Final version of jquery.tmpl
18.3527 + }
18.3528 + } catch(ex) { /* Apparently not the version we were looking for */ }
18.3529 +
18.3530 + return 1; // Any older version that we don't support
18.3531 + })();
18.3532 +
18.3533 + function ensureHasReferencedJQueryTemplates() {
18.3534 + if (jQueryTmplVersion < 2)
18.3535 + throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
18.3536 + }
18.3537 +
18.3538 + function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
18.3539 + return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
18.3540 + }
18.3541 +
18.3542 + this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
18.3543 + options = options || {};
18.3544 + ensureHasReferencedJQueryTemplates();
18.3545 +
18.3546 + // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
18.3547 + var precompiled = templateSource['data']('precompiled');
18.3548 + if (!precompiled) {
18.3549 + var templateText = templateSource['text']() || "";
18.3550 + // Wrap in "with($whatever.koBindingContext) { ... }"
18.3551 + templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
18.3552 +
18.3553 + precompiled = jQuery['template'](null, templateText);
18.3554 + templateSource['data']('precompiled', precompiled);
18.3555 + }
18.3556 +
18.3557 + var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
18.3558 + var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
18.3559 +
18.3560 + var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
18.3561 + resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
18.3562 +
18.3563 + jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
18.3564 + return resultNodes;
18.3565 + };
18.3566 +
18.3567 + this['createJavaScriptEvaluatorBlock'] = function(script) {
18.3568 + return "{{ko_code ((function() { return " + script + " })()) }}";
18.3569 + };
18.3570 +
18.3571 + this['addTemplate'] = function(templateName, templateMarkup) {
18.3572 + document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
18.3573 + };
18.3574 +
18.3575 + if (jQueryTmplVersion > 0) {
18.3576 + jQuery['tmpl']['tag']['ko_code'] = {
18.3577 + open: "__.push($1 || '');"
18.3578 + };
18.3579 + jQuery['tmpl']['tag']['ko_with'] = {
18.3580 + open: "with($1) {",
18.3581 + close: "} "
18.3582 + };
18.3583 + }
18.3584 + };
18.3585 +
18.3586 + ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
18.3587 +
18.3588 + // Use this one by default *only if jquery.tmpl is referenced*
18.3589 + var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
18.3590 + if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
18.3591 + ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
18.3592 +
18.3593 + ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
18.3594 +})();
18.3595 +});
18.3596 +})(window,document,navigator,window["jQuery"]);
18.3597 +})();
18.3598 \ No newline at end of file
19.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
19.2 +++ b/ko4j/src/test/java/org/netbeans/html/ko4j/DynamicHTTP.java Thu Jan 09 15:03:34 2014 +0100
19.3 @@ -0,0 +1,259 @@
19.4 +/**
19.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
19.6 + *
19.7 + * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
19.8 + *
19.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
19.10 + * Other names may be trademarks of their respective owners.
19.11 + *
19.12 + * The contents of this file are subject to the terms of either the GNU
19.13 + * General Public License Version 2 only ("GPL") or the Common
19.14 + * Development and Distribution License("CDDL") (collectively, the
19.15 + * "License"). You may not use this file except in compliance with the
19.16 + * License. You can obtain a copy of the License at
19.17 + * http://www.netbeans.org/cddl-gplv2.html
19.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
19.19 + * specific language governing permissions and limitations under the
19.20 + * License. When distributing the software, include this License Header
19.21 + * Notice in each file and include the License file at
19.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
19.23 + * particular file as subject to the "Classpath" exception as provided
19.24 + * by Oracle in the GPL Version 2 section of the License file that
19.25 + * accompanied this code. If applicable, add the following below the
19.26 + * License Header, with the fields enclosed by brackets [] replaced by
19.27 + * your own identifying information:
19.28 + * "Portions Copyrighted [year] [name of copyright owner]"
19.29 + *
19.30 + * Contributor(s):
19.31 + *
19.32 + * The Original Software is NetBeans. The Initial Developer of the Original
19.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
19.34 + *
19.35 + * If you wish your version of this file to be governed by only the CDDL
19.36 + * or only the GPL Version 2, indicate your decision by adding
19.37 + * "[Contributor] elects to include this software in this distribution
19.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
19.39 + * single choice of license, a recipient has the option to distribute
19.40 + * your version of this file under either the CDDL, the GPL Version 2 or
19.41 + * to extend the choice of license to its licensees as provided above.
19.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
19.43 + * Version 2 license, then the option applies only if the new code is
19.44 + * made subject to such option by the copyright holder.
19.45 + */
19.46 +package org.netbeans.html.ko4j;
19.47 +
19.48 +import java.io.ByteArrayInputStream;
19.49 +import java.io.ByteArrayOutputStream;
19.50 +import java.io.IOException;
19.51 +import java.io.InputStream;
19.52 +import java.io.OutputStream;
19.53 +import java.io.Reader;
19.54 +import java.net.URI;
19.55 +import java.net.URISyntaxException;
19.56 +import java.util.ArrayList;
19.57 +import java.util.List;
19.58 +import java.util.logging.Level;
19.59 +import java.util.logging.Logger;
19.60 +import org.glassfish.grizzly.PortRange;
19.61 +import org.glassfish.grizzly.http.server.HttpHandler;
19.62 +import org.glassfish.grizzly.http.server.HttpServer;
19.63 +import org.glassfish.grizzly.http.server.NetworkListener;
19.64 +import org.glassfish.grizzly.http.server.Request;
19.65 +import org.glassfish.grizzly.http.server.Response;
19.66 +import org.glassfish.grizzly.http.server.ServerConfiguration;
19.67 +import org.glassfish.grizzly.websockets.WebSocket;
19.68 +import org.glassfish.grizzly.websockets.WebSocketAddOn;
19.69 +import org.glassfish.grizzly.websockets.WebSocketApplication;
19.70 +import org.glassfish.grizzly.websockets.WebSocketEngine;
19.71 +
19.72 +/**
19.73 + *
19.74 + * @author Jaroslav Tulach <jtulach@netbeans.org>
19.75 + */
19.76 +final class DynamicHTTP extends HttpHandler {
19.77 + private static final Logger LOG = Logger.getLogger(DynamicHTTP.class.getName());
19.78 + private static int resourcesCount;
19.79 + private static List<Resource> resources;
19.80 + private static ServerConfiguration conf;
19.81 + private static HttpServer server;
19.82 +
19.83 + private DynamicHTTP() {
19.84 + }
19.85 +
19.86 + static URI initServer() throws Exception {
19.87 + server = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
19.88 + final WebSocketAddOn addon = new WebSocketAddOn();
19.89 + for (NetworkListener listener : server.getListeners()) {
19.90 + listener.registerAddOn(addon);
19.91 + }
19.92 + resources = new ArrayList<Resource>();
19.93 +
19.94 + conf = server.getServerConfiguration();
19.95 + final DynamicHTTP dh = new DynamicHTTP();
19.96 +
19.97 + conf.addHttpHandler(dh, "/");
19.98 +
19.99 + server.start();
19.100 +
19.101 + return pageURL("http", server, "/test.html");
19.102 + }
19.103 +
19.104 + @Override
19.105 + public void service(Request request, Response response) throws Exception {
19.106 + if ("/test.html".equals(request.getRequestURI())) {
19.107 + response.setContentType("text/html");
19.108 + final InputStream is = DynamicHTTP.class.getResourceAsStream("test.html");
19.109 + copyStream(is, response.getOutputStream(), null);
19.110 + return;
19.111 + }
19.112 + if ("/dynamic".equals(request.getRequestURI())) {
19.113 + String mimeType = request.getParameter("mimeType");
19.114 + List<String> params = new ArrayList<String>();
19.115 + boolean webSocket = false;
19.116 + for (int i = 0;; i++) {
19.117 + String p = request.getParameter("param" + i);
19.118 + if (p == null) {
19.119 + break;
19.120 + }
19.121 + if ("protocol:ws".equals(p)) {
19.122 + webSocket = true;
19.123 + continue;
19.124 + }
19.125 + params.add(p);
19.126 + }
19.127 + final String cnt = request.getParameter("content");
19.128 + String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
19.129 + ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
19.130 + URI url;
19.131 + final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
19.132 + if (webSocket) {
19.133 + url = registerWebSocket(res);
19.134 + } else {
19.135 + url = registerResource(res);
19.136 + }
19.137 + response.getWriter().write(url.toString());
19.138 + response.getWriter().write("\n");
19.139 + return;
19.140 + }
19.141 +
19.142 + for (Resource r : resources) {
19.143 + if (r.httpPath.equals(request.getRequestURI())) {
19.144 + response.setContentType(r.httpType);
19.145 + r.httpContent.reset();
19.146 + String[] params = null;
19.147 + if (r.parameters.length != 0) {
19.148 + params = new String[r.parameters.length];
19.149 + for (int i = 0; i < r.parameters.length; i++) {
19.150 + params[i] = request.getParameter(r.parameters[i]);
19.151 + if (params[i] == null) {
19.152 + if ("http.method".equals(r.parameters[i])) {
19.153 + params[i] = request.getMethod().toString();
19.154 + } else if ("http.requestBody".equals(r.parameters[i])) {
19.155 + Reader rdr = request.getReader();
19.156 + StringBuilder sb = new StringBuilder();
19.157 + for (;;) {
19.158 + int ch = rdr.read();
19.159 + if (ch == -1) {
19.160 + break;
19.161 + }
19.162 + sb.append((char) ch);
19.163 + }
19.164 + params[i] = sb.toString();
19.165 + }
19.166 + }
19.167 + if (params[i] == null) {
19.168 + params[i] = "null";
19.169 + }
19.170 + }
19.171 + }
19.172 +
19.173 + copyStream(r.httpContent, response.getOutputStream(), null, params);
19.174 + }
19.175 + }
19.176 + }
19.177 +
19.178 + private URI registerWebSocket(Resource r) {
19.179 + WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
19.180 + return pageURL("ws", server, r.httpPath);
19.181 + }
19.182 +
19.183 + private URI registerResource(Resource r) {
19.184 + if (!resources.contains(r)) {
19.185 + resources.add(r);
19.186 + conf.addHttpHandler(this, r.httpPath);
19.187 + }
19.188 + return pageURL("http", server, r.httpPath);
19.189 + }
19.190 +
19.191 + private static URI pageURL(String proto, HttpServer server, final String page) {
19.192 + NetworkListener listener = server.getListeners().iterator().next();
19.193 + int port = listener.getPort();
19.194 + try {
19.195 + return new URI(proto + "://localhost:" + port + page);
19.196 + } catch (URISyntaxException ex) {
19.197 + throw new IllegalStateException(ex);
19.198 + }
19.199 + }
19.200 +
19.201 + static final class Resource {
19.202 +
19.203 + final InputStream httpContent;
19.204 + final String httpType;
19.205 + final String httpPath;
19.206 + final String[] parameters;
19.207 +
19.208 + Resource(InputStream httpContent, String httpType, String httpPath,
19.209 + String[] parameters) {
19.210 + httpContent.mark(Integer.MAX_VALUE);
19.211 + this.httpContent = httpContent;
19.212 + this.httpType = httpType;
19.213 + this.httpPath = httpPath;
19.214 + this.parameters = parameters;
19.215 + }
19.216 + }
19.217 +
19.218 + static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
19.219 + for (;;) {
19.220 + int ch = is.read();
19.221 + if (ch == -1) {
19.222 + break;
19.223 + }
19.224 + if (ch == '$' && params.length > 0) {
19.225 + int cnt = is.read() - '0';
19.226 + if (baseURL != null && cnt == 'U' - '0') {
19.227 + os.write(baseURL.getBytes("UTF-8"));
19.228 + } else {
19.229 + if (cnt >= 0 && cnt < params.length) {
19.230 + os.write(params[cnt].getBytes("UTF-8"));
19.231 + } else {
19.232 + os.write('$');
19.233 + os.write(cnt + '0');
19.234 + }
19.235 + }
19.236 + } else {
19.237 + os.write(ch);
19.238 + }
19.239 + }
19.240 + }
19.241 +
19.242 + private static class WS extends WebSocketApplication {
19.243 + private final Resource r;
19.244 +
19.245 + private WS(Resource r) {
19.246 + this.r = r;
19.247 + }
19.248 +
19.249 + @Override
19.250 + public void onMessage(WebSocket socket, String text) {
19.251 + try {
19.252 + r.httpContent.reset();
19.253 + ByteArrayOutputStream out = new ByteArrayOutputStream();
19.254 + copyStream(r.httpContent, out, null, text);
19.255 + String s = new String(out.toByteArray(), "UTF-8");
19.256 + socket.send(s);
19.257 + } catch (IOException ex) {
19.258 + LOG.log(Level.WARNING, "Error processing message " + text, ex);
19.259 + }
19.260 + }
19.261 + }
19.262 +}
20.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
20.2 +++ b/ko4j/src/test/java/org/netbeans/html/ko4j/KOFx.java Thu Jan 09 15:03:34 2014 +0100
20.3 @@ -0,0 +1,118 @@
20.4 +/**
20.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
20.6 + *
20.7 + * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
20.8 + *
20.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
20.10 + * Other names may be trademarks of their respective owners.
20.11 + *
20.12 + * The contents of this file are subject to the terms of either the GNU
20.13 + * General Public License Version 2 only ("GPL") or the Common
20.14 + * Development and Distribution License("CDDL") (collectively, the
20.15 + * "License"). You may not use this file except in compliance with the
20.16 + * License. You can obtain a copy of the License at
20.17 + * http://www.netbeans.org/cddl-gplv2.html
20.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
20.19 + * specific language governing permissions and limitations under the
20.20 + * License. When distributing the software, include this License Header
20.21 + * Notice in each file and include the License file at
20.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
20.23 + * particular file as subject to the "Classpath" exception as provided
20.24 + * by Oracle in the GPL Version 2 section of the License file that
20.25 + * accompanied this code. If applicable, add the following below the
20.26 + * License Header, with the fields enclosed by brackets [] replaced by
20.27 + * your own identifying information:
20.28 + * "Portions Copyrighted [year] [name of copyright owner]"
20.29 + *
20.30 + * Contributor(s):
20.31 + *
20.32 + * The Original Software is NetBeans. The Initial Developer of the Original
20.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
20.34 + *
20.35 + * If you wish your version of this file to be governed by only the CDDL
20.36 + * or only the GPL Version 2, indicate your decision by adding
20.37 + * "[Contributor] elects to include this software in this distribution
20.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
20.39 + * single choice of license, a recipient has the option to distribute
20.40 + * your version of this file under either the CDDL, the GPL Version 2 or
20.41 + * to extend the choice of license to its licensees as provided above.
20.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
20.43 + * Version 2 license, then the option applies only if the new code is
20.44 + * made subject to such option by the copyright holder.
20.45 + */
20.46 +package org.netbeans.html.ko4j;
20.47 +
20.48 +import java.io.Closeable;
20.49 +import java.lang.reflect.InvocationTargetException;
20.50 +import java.lang.reflect.Method;
20.51 +import javafx.application.Platform;
20.52 +import org.apidesign.html.boot.spi.Fn;
20.53 +import org.testng.ITest;
20.54 +import org.testng.annotations.Test;
20.55 +
20.56 +/**
20.57 + *
20.58 + * @author Jaroslav Tulach <jtulach@netbeans.org>
20.59 + */
20.60 +public final class KOFx implements ITest, Runnable {
20.61 + private final Fn.Presenter p;
20.62 + private final Method m;
20.63 + private Object result;
20.64 + private Object inst;
20.65 + private int count;
20.66 +
20.67 + KOFx(Fn.Presenter p, Method m) {
20.68 + this.p = p;
20.69 + this.m = m;
20.70 + }
20.71 +
20.72 + @Override
20.73 + public String getTestName() {
20.74 + return m.getName();
20.75 + }
20.76 +
20.77 + @Test
20.78 + public synchronized void executeTest() throws Exception {
20.79 + if (result == null) {
20.80 + Platform.runLater(this);
20.81 + wait();
20.82 + }
20.83 + if (result instanceof Exception) {
20.84 + throw (Exception)result;
20.85 + }
20.86 + if (result instanceof Error) {
20.87 + throw (Error)result;
20.88 + }
20.89 + }
20.90 +
20.91 + @Override
20.92 + public synchronized void run() {
20.93 + boolean notify = true;
20.94 + try (Closeable a = Fn.activate(p)) {
20.95 + if (inst == null) {
20.96 + inst = m.getDeclaringClass().newInstance();
20.97 + }
20.98 + result = m.invoke(inst);
20.99 + if (result == null) {
20.100 + result = this;
20.101 + }
20.102 + } catch (InvocationTargetException ex) {
20.103 + Throwable r = ex.getTargetException();
20.104 + if (r instanceof InterruptedException) {
20.105 + if (count++ < 10000) {
20.106 + notify = false;
20.107 + Platform.runLater(this);
20.108 + return;
20.109 + }
20.110 + }
20.111 + result = r;
20.112 + } catch (Exception ex) {
20.113 + result = ex;
20.114 + } finally {
20.115 + if (notify) {
20.116 + notifyAll();
20.117 + }
20.118 + }
20.119 + }
20.120 +
20.121 +}
21.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
21.2 +++ b/ko4j/src/test/java/org/netbeans/html/ko4j/KnockoutFXTest.java Thu Jan 09 15:03:34 2014 +0100
21.3 @@ -0,0 +1,229 @@
21.4 +/**
21.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
21.6 + *
21.7 + * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
21.8 + *
21.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
21.10 + * Other names may be trademarks of their respective owners.
21.11 + *
21.12 + * The contents of this file are subject to the terms of either the GNU
21.13 + * General Public License Version 2 only ("GPL") or the Common
21.14 + * Development and Distribution License("CDDL") (collectively, the
21.15 + * "License"). You may not use this file except in compliance with the
21.16 + * License. You can obtain a copy of the License at
21.17 + * http://www.netbeans.org/cddl-gplv2.html
21.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
21.19 + * specific language governing permissions and limitations under the
21.20 + * License. When distributing the software, include this License Header
21.21 + * Notice in each file and include the License file at
21.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
21.23 + * particular file as subject to the "Classpath" exception as provided
21.24 + * by Oracle in the GPL Version 2 section of the License file that
21.25 + * accompanied this code. If applicable, add the following below the
21.26 + * License Header, with the fields enclosed by brackets [] replaced by
21.27 + * your own identifying information:
21.28 + * "Portions Copyrighted [year] [name of copyright owner]"
21.29 + *
21.30 + * Contributor(s):
21.31 + *
21.32 + * The Original Software is NetBeans. The Initial Developer of the Original
21.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
21.34 + *
21.35 + * If you wish your version of this file to be governed by only the CDDL
21.36 + * or only the GPL Version 2, indicate your decision by adding
21.37 + * "[Contributor] elects to include this software in this distribution
21.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
21.39 + * single choice of license, a recipient has the option to distribute
21.40 + * your version of this file under either the CDDL, the GPL Version 2 or
21.41 + * to extend the choice of license to its licensees as provided above.
21.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
21.43 + * Version 2 license, then the option applies only if the new code is
21.44 + * made subject to such option by the copyright holder.
21.45 + */
21.46 +package org.netbeans.html.ko4j;
21.47 +
21.48 +import java.io.BufferedReader;
21.49 +import java.io.IOException;
21.50 +import java.io.InputStreamReader;
21.51 +import java.lang.annotation.Annotation;
21.52 +import java.lang.reflect.Method;
21.53 +import java.net.URI;
21.54 +import java.net.URISyntaxException;
21.55 +import java.net.URL;
21.56 +import java.net.URLConnection;
21.57 +import java.util.ArrayList;
21.58 +import java.util.List;
21.59 +import java.util.Map;
21.60 +import java.util.concurrent.Executors;
21.61 +import net.java.html.BrwsrCtx;
21.62 +import net.java.html.boot.BrowserBuilder;
21.63 +import net.java.html.js.JavaScriptBody;
21.64 +import org.netbeans.html.boot.impl.FnContext;
21.65 +import org.apidesign.html.boot.spi.Fn;
21.66 +import org.apidesign.html.context.spi.Contexts;
21.67 +import org.apidesign.html.json.spi.Technology;
21.68 +import org.apidesign.html.json.spi.Transfer;
21.69 +import org.apidesign.html.json.spi.WSTransfer;
21.70 +import org.apidesign.html.json.tck.KOTest;
21.71 +import org.apidesign.html.json.tck.KnockoutTCK;
21.72 +import org.json.JSONException;
21.73 +import org.json.JSONObject;
21.74 +import org.openide.util.lookup.ServiceProvider;
21.75 +import org.testng.annotations.Factory;
21.76 +import static org.testng.Assert.*;
21.77 +
21.78 +/**
21.79 + *
21.80 + * @author Jaroslav Tulach <jtulach@netbeans.org>
21.81 + */
21.82 +@ServiceProvider(service = KnockoutTCK.class)
21.83 +public final class KnockoutFXTest extends KnockoutTCK {
21.84 + private static Class<?> browserClass;
21.85 + private static Fn.Presenter browserContext;
21.86 +
21.87 + public KnockoutFXTest() {
21.88 + }
21.89 +
21.90 + @Factory public static Object[] compatibilityTests() throws Exception {
21.91 + Class[] arr = testClasses();
21.92 + for (int i = 0; i < arr.length; i++) {
21.93 + assertEquals(
21.94 + arr[i].getClassLoader(),
21.95 + KnockoutFXTest.class.getClassLoader(),
21.96 + "All classes loaded by the same classloader"
21.97 + );
21.98 + }
21.99 +
21.100 + URI uri = DynamicHTTP.initServer();
21.101 +
21.102 + final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(KnockoutFXTest.class).
21.103 + loadPage(uri.toString()).
21.104 + invoke("initialized");
21.105 +
21.106 + Executors.newSingleThreadExecutor().submit(new Runnable() {
21.107 + @Override
21.108 + public void run() {
21.109 + bb.showAndWait();
21.110 + }
21.111 + });
21.112 +
21.113 + ClassLoader l = getClassLoader();
21.114 + List<Object> res = new ArrayList<Object>();
21.115 + for (int i = 0; i < arr.length; i++) {
21.116 + Class<?> c = Class.forName(arr[i].getName(), true, l);
21.117 + seekKOTests(c, res);
21.118 + }
21.119 + Class<?> c = Class.forName(LessCallbacksCheck.class.getName(), true, l);
21.120 + seekKOTests(c, res);
21.121 + return res.toArray();
21.122 + }
21.123 +
21.124 + private static void seekKOTests(Class<?> c, List<Object> res) throws SecurityException, ClassNotFoundException {
21.125 + Class<? extends Annotation> koTest =
21.126 + c.getClassLoader().loadClass(KOTest.class.getName()).
21.127 + asSubclass(Annotation.class);
21.128 + for (Method m : c.getMethods()) {
21.129 + if (m.getAnnotation(koTest) != null) {
21.130 + res.add(new KOFx(browserContext, m));
21.131 + }
21.132 + }
21.133 + }
21.134 +
21.135 + static synchronized ClassLoader getClassLoader() throws InterruptedException {
21.136 + while (browserClass == null) {
21.137 + KnockoutFXTest.class.wait();
21.138 + }
21.139 + return browserClass.getClassLoader();
21.140 + }
21.141 +
21.142 + public static synchronized void initialized(Class<?> browserCls) throws Exception {
21.143 + browserClass = browserCls;
21.144 + browserContext = FnContext.currentPresenter();
21.145 + KnockoutFXTest.class.notifyAll();
21.146 + }
21.147 +
21.148 + public static void initialized() throws Exception {
21.149 + Class<?> classpathClass = ClassLoader.getSystemClassLoader().loadClass(KnockoutFXTest.class.getName());
21.150 + Method m = classpathClass.getMethod("initialized", Class.class);
21.151 + m.invoke(null, KnockoutFXTest.class);
21.152 + browserContext = FnContext.currentPresenter();
21.153 + }
21.154 +
21.155 + @Override
21.156 + public BrwsrCtx createContext() {
21.157 + FXContext fx = new FXContext(browserContext);
21.158 + Contexts.Builder cb = Contexts.newBuilder().
21.159 + register(Technology.class, fx, 10).
21.160 + register(Transfer.class, fx, 10);
21.161 + if (fx.areWebSocketsSupported()) {
21.162 + cb.register(WSTransfer.class, fx, 10);
21.163 + }
21.164 + return cb.build();
21.165 + }
21.166 +
21.167 + @Override
21.168 + public Object createJSON(Map<String, Object> values) {
21.169 + JSONObject json = new JSONObject();
21.170 + for (Map.Entry<String, Object> entry : values.entrySet()) {
21.171 + try {
21.172 + json.put(entry.getKey(), entry.getValue());
21.173 + } catch (JSONException ex) {
21.174 + throw new IllegalStateException(ex);
21.175 + }
21.176 + }
21.177 + return json;
21.178 + }
21.179 +
21.180 + @Override
21.181 + @JavaScriptBody(args = { "s", "args" }, body = ""
21.182 + + "var f = new Function(s); "
21.183 + + "return f.apply(null, args);"
21.184 + )
21.185 + public native Object executeScript(String script, Object[] arguments);
21.186 +
21.187 + @JavaScriptBody(args = { }, body =
21.188 + "var h;"
21.189 + + "if (!!window && !!window.location && !!window.location.href)\n"
21.190 + + " h = window.location.href;\n"
21.191 + + "else "
21.192 + + " h = null;"
21.193 + + "return h;\n"
21.194 + )
21.195 + private static native String findBaseURL();
21.196 +
21.197 + @Override
21.198 + public URI prepareURL(String content, String mimeType, String[] parameters) {
21.199 + try {
21.200 + final URL baseURL = new URL(findBaseURL());
21.201 + StringBuilder sb = new StringBuilder();
21.202 + sb.append("/dynamic?mimeType=").append(mimeType);
21.203 + for (int i = 0; i < parameters.length; i++) {
21.204 + sb.append("¶m" + i).append("=").append(parameters[i]);
21.205 + }
21.206 + String mangle = content.replace("\n", "%0a")
21.207 + .replace("\"", "\\\"").replace(" ", "%20");
21.208 + sb.append("&content=").append(mangle);
21.209 +
21.210 + URL query = new URL(baseURL, sb.toString());
21.211 + URLConnection c = query.openConnection();
21.212 + BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
21.213 + URI connectTo = new URI(br.readLine());
21.214 + return connectTo;
21.215 + } catch (IOException ex) {
21.216 + throw new IllegalStateException(ex);
21.217 + } catch (URISyntaxException ex) {
21.218 + throw new IllegalStateException(ex);
21.219 + }
21.220 + }
21.221 +
21.222 + @Override
21.223 + public boolean canFailWebSocketTest() {
21.224 + try {
21.225 + Class.forName("java.util.function.Function");
21.226 + return false;
21.227 + } catch (ClassNotFoundException ex) {
21.228 + // running on JDK7, FX WebView WebSocket impl does not work
21.229 + return true;
21.230 + }
21.231 + }
21.232 +}
22.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
22.2 +++ b/ko4j/src/test/java/org/netbeans/html/ko4j/LessCallbacksCheck.java Thu Jan 09 15:03:34 2014 +0100
22.3 @@ -0,0 +1,82 @@
22.4 +/**
22.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
22.6 + *
22.7 + * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
22.8 + *
22.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
22.10 + * Other names may be trademarks of their respective owners.
22.11 + *
22.12 + * The contents of this file are subject to the terms of either the GNU
22.13 + * General Public License Version 2 only ("GPL") or the Common
22.14 + * Development and Distribution License("CDDL") (collectively, the
22.15 + * "License"). You may not use this file except in compliance with the
22.16 + * License. You can obtain a copy of the License at
22.17 + * http://www.netbeans.org/cddl-gplv2.html
22.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
22.19 + * specific language governing permissions and limitations under the
22.20 + * License. When distributing the software, include this License Header
22.21 + * Notice in each file and include the License file at
22.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
22.23 + * particular file as subject to the "Classpath" exception as provided
22.24 + * by Oracle in the GPL Version 2 section of the License file that
22.25 + * accompanied this code. If applicable, add the following below the
22.26 + * License Header, with the fields enclosed by brackets [] replaced by
22.27 + * your own identifying information:
22.28 + * "Portions Copyrighted [year] [name of copyright owner]"
22.29 + *
22.30 + * Contributor(s):
22.31 + *
22.32 + * The Original Software is NetBeans. The Initial Developer of the Original
22.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
22.34 + *
22.35 + * If you wish your version of this file to be governed by only the CDDL
22.36 + * or only the GPL Version 2, indicate your decision by adding
22.37 + * "[Contributor] elects to include this software in this distribution
22.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
22.39 + * single choice of license, a recipient has the option to distribute
22.40 + * your version of this file under either the CDDL, the GPL Version 2 or
22.41 + * to extend the choice of license to its licensees as provided above.
22.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
22.43 + * Version 2 license, then the option applies only if the new code is
22.44 + * made subject to such option by the copyright holder.
22.45 + */
22.46 +package org.netbeans.html.ko4j;
22.47 +
22.48 +import java.io.PrintWriter;
22.49 +import java.io.StringWriter;
22.50 +import net.java.html.json.ComputedProperty;
22.51 +import net.java.html.json.Model;
22.52 +import net.java.html.json.Property;
22.53 +import org.apidesign.html.json.tck.KOTest;
22.54 +
22.55 +/**
22.56 + *
22.57 + * @author Jaroslav Tulach <jtulach@netbeans.org>
22.58 + */
22.59 +@Model(className = "LessCalls", properties = {
22.60 + @Property(name = "value", type = int.class)
22.61 +})
22.62 +public class LessCallbacksCheck {
22.63 + private static StringWriter sw;
22.64 +
22.65 + @ComputedProperty static int plusOne(int value) {
22.66 + if (sw == null) {
22.67 + sw = new StringWriter();
22.68 + }
22.69 + new Exception("Who calls me?").printStackTrace(
22.70 + new PrintWriter(sw)
22.71 + );
22.72 + return value + 1;
22.73 + }
22.74 +
22.75 + @KOTest public void dontCallForInitialValueBackToJavaVM() {
22.76 + LessCalls m = new LessCalls(10).applyBindings();
22.77 + assert m.getPlusOne() == 11 : "Expecting 11: " + m.getPlusOne();
22.78 +
22.79 + assert sw != null : "StringWriter should be initialized: " + sw;
22.80 +
22.81 + if (sw.toString().contains("$JsCallbacks$")) {
22.82 + assert false : "Don't call for initial value via JsCallbacks:\n" + sw;
22.83 + }
22.84 + }
22.85 +}
23.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
23.2 +++ b/ko4j/src/test/resources/org/netbeans/html/ko4j/test.html Thu Jan 09 15:03:34 2014 +0100
23.3 @@ -0,0 +1,56 @@
23.4 +<!--
23.5 +
23.6 + DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
23.7 +
23.8 + Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
23.9 +
23.10 + Oracle and Java are registered trademarks of Oracle and/or its affiliates.
23.11 + Other names may be trademarks of their respective owners.
23.12 +
23.13 + The contents of this file are subject to the terms of either the GNU
23.14 + General Public License Version 2 only ("GPL") or the Common
23.15 + Development and Distribution License("CDDL") (collectively, the
23.16 + "License"). You may not use this file except in compliance with the
23.17 + License. You can obtain a copy of the License at
23.18 + http://www.netbeans.org/cddl-gplv2.html
23.19 + or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
23.20 + specific language governing permissions and limitations under the
23.21 + License. When distributing the software, include this License Header
23.22 + Notice in each file and include the License file at
23.23 + nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
23.24 + particular file as subject to the "Classpath" exception as provided
23.25 + by Oracle in the GPL Version 2 section of the License file that
23.26 + accompanied this code. If applicable, add the following below the
23.27 + License Header, with the fields enclosed by brackets [] replaced by
23.28 + your own identifying information:
23.29 + "Portions Copyrighted [year] [name of copyright owner]"
23.30 +
23.31 + Contributor(s):
23.32 +
23.33 + The Original Software is NetBeans. The Initial Developer of the Original
23.34 + Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
23.35 +
23.36 + If you wish your version of this file to be governed by only the CDDL
23.37 + or only the GPL Version 2, indicate your decision by adding
23.38 + "[Contributor] elects to include this software in this distribution
23.39 + under the [CDDL or GPL Version 2] license." If you do not indicate a
23.40 + single choice of license, a recipient has the option to distribute
23.41 + your version of this file under either the CDDL, the GPL Version 2 or
23.42 + to extend the choice of license to its licensees as provided above.
23.43 + However, if you add GPL Version 2 code and therefore, elected the GPL
23.44 + Version 2 license, then the option applies only if the new code is
23.45 + made subject to such option by the copyright holder.
23.46 +
23.47 +-->
23.48 +<!DOCTYPE html>
23.49 +<html>
23.50 + <head>
23.51 + <title>Knockout.fx Execution Harness</title>
23.52 + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
23.53 + <meta name="viewport" content="width=device-width">
23.54 + </head>
23.55 + <body>
23.56 + <h1>Knockout.fx Execution Harness</h1>
23.57 + </body>
23.58 + <script></script>
23.59 +</html>
24.1 --- a/pom.xml Thu Jan 09 11:53:46 2014 +0100
24.2 +++ b/pom.xml Thu Jan 09 15:03:34 2014 +0100
24.3 @@ -23,7 +23,7 @@
24.4 <module>json-tck</module>
24.5 <module>ko-archetype</module>
24.6 <module>ko-archetype-test</module>
24.7 - <module>ko-fx</module>
24.8 + <module>ko4j</module>
24.9 <module>sound</module>
24.10 <module>context</module>
24.11 <module>boot</module>