The classloader based approach seems to work OK, so merging into default branch
1.1 --- a/.hgtags Wed May 29 19:36:31 2013 +0200
1.2 +++ b/.hgtags Wed Jun 26 18:09:25 2013 +0200
1.3 @@ -2,3 +2,4 @@
1.4 4b63ae70ea42cc9baba0cab5f5596e1bab7766e7 release-0.2
1.5 309dcf0774ffd5880edccdbec330c90d88f6f4e1 release-0.3
1.6 93433764b44e705adb784e52a49beab849c94073 release-0.3.1
1.7 +5c5fc5ee2d6396f792114bd8567e17e1e6c4d360 fxlauncher
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/boot-fx/pom.xml Wed Jun 26 18:09:25 2013 +0200
2.3 @@ -0,0 +1,39 @@
2.4 +<?xml version="1.0"?>
2.5 +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
2.6 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
2.7 + <modelVersion>4.0.0</modelVersion>
2.8 + <parent>
2.9 + <groupId>org.apidesign</groupId>
2.10 + <artifactId>html</artifactId>
2.11 + <version>0.4-SNAPSHOT</version>
2.12 + </parent>
2.13 + <groupId>org.apidesign.html</groupId>
2.14 + <artifactId>boot-fx</artifactId>
2.15 + <version>0.4-SNAPSHOT</version>
2.16 + <name>FX WebView Bootstrap</name>
2.17 + <url>http://maven.apache.org</url>
2.18 + <properties>
2.19 + <jfxrt.jar>${java.home}/lib/jfxrt.jar</jfxrt.jar>
2.20 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
2.21 + </properties>
2.22 + <dependencies>
2.23 + <dependency>
2.24 + <groupId>com.oracle</groupId>
2.25 + <artifactId>javafx</artifactId>
2.26 + <version>2.2</version>
2.27 + <scope>system</scope>
2.28 + <systemPath>${jfxrt.jar}</systemPath>
2.29 + </dependency>
2.30 + <dependency>
2.31 + <groupId>org.netbeans.api</groupId>
2.32 + <artifactId>org-openide-util</artifactId>
2.33 + <scope>provided</scope>
2.34 + </dependency>
2.35 + <dependency>
2.36 + <groupId>org.apidesign.html</groupId>
2.37 + <artifactId>net.java.html.boot</artifactId>
2.38 + <version>${project.version}</version>
2.39 + <type>jar</type>
2.40 + </dependency>
2.41 + </dependencies>
2.42 +</project>
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/boot-fx/src/main/java/org/apidesign/html/boot/fx/FXPresenter.java Wed Jun 26 18:09:25 2013 +0200
3.3 @@ -0,0 +1,325 @@
3.4 +/**
3.5 + * HTML via Java(tm) Language Bindings
3.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
3.7 + *
3.8 + * This program is free software: you can redistribute it and/or modify
3.9 + * it under the terms of the GNU General Public License as published by
3.10 + * the Free Software Foundation, version 2 of the License.
3.11 + *
3.12 + * This program is distributed in the hope that it will be useful,
3.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
3.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3.15 + * GNU General Public License for more details. apidesign.org
3.16 + * designates this particular file as subject to the
3.17 + * "Classpath" exception as provided by apidesign.org
3.18 + * in the License file that accompanied this code.
3.19 + *
3.20 + * You should have received a copy of the GNU General Public License
3.21 + * along with this program. Look for COPYING file in the top folder.
3.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
3.23 + */
3.24 +package org.apidesign.html.boot.fx;
3.25 +
3.26 +import java.io.BufferedReader;
3.27 +import java.io.Reader;
3.28 +import java.lang.reflect.Method;
3.29 +import java.net.URL;
3.30 +import java.net.URLClassLoader;
3.31 +import java.util.ArrayList;
3.32 +import java.util.Arrays;
3.33 +import java.util.List;
3.34 +import java.util.concurrent.CountDownLatch;
3.35 +import java.util.concurrent.Executors;
3.36 +import java.util.logging.Level;
3.37 +import java.util.logging.Logger;
3.38 +import javafx.application.Application;
3.39 +import javafx.application.Platform;
3.40 +import javafx.beans.value.ChangeListener;
3.41 +import javafx.beans.value.ObservableValue;
3.42 +import javafx.concurrent.Worker;
3.43 +import javafx.event.ActionEvent;
3.44 +import javafx.event.EventHandler;
3.45 +import javafx.geometry.Insets;
3.46 +import javafx.geometry.Pos;
3.47 +import javafx.scene.Scene;
3.48 +import javafx.scene.control.Button;
3.49 +import javafx.scene.layout.BorderPane;
3.50 +import javafx.scene.layout.HBox;
3.51 +import javafx.scene.layout.VBox;
3.52 +import javafx.scene.text.Text;
3.53 +import javafx.scene.web.WebEngine;
3.54 +import javafx.scene.web.WebEvent;
3.55 +import javafx.scene.web.WebView;
3.56 +import javafx.stage.Modality;
3.57 +import javafx.stage.Stage;
3.58 +import netscape.javascript.JSObject;
3.59 +import org.apidesign.html.boot.spi.Fn;
3.60 +import org.openide.util.Exceptions;
3.61 +import org.openide.util.lookup.ServiceProvider;
3.62 +
3.63 +/**
3.64 + *
3.65 + * @author Jaroslav Tulach <jtulach@netbeans.org>
3.66 + */
3.67 +@ServiceProvider(service = Fn.Presenter.class)
3.68 +public final class FXPresenter implements Fn.Presenter {
3.69 + static {
3.70 + try {
3.71 + Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
3.72 + m.setAccessible(true);
3.73 + URL l = new URL("file://" + System.getProperty("java.home") + "/lib/jfxrt.jar");
3.74 +// LOG.log(Level.INFO, "url : {0}", l);
3.75 + m.invoke(ClassLoader.getSystemClassLoader(), l);
3.76 + } catch (Exception ex) {
3.77 + throw new LinkageError("Can't add jfxrt.jar on the classpath", ex);
3.78 + }
3.79 + }
3.80 +
3.81 + private WebEngine engine;
3.82 +
3.83 + @Override
3.84 + public Fn defineFn(String code, String... names) {
3.85 + StringBuilder sb = new StringBuilder();
3.86 + sb.append("(function() {");
3.87 + sb.append(" return function(");
3.88 + String sep = "";
3.89 + for (String n : names) {
3.90 + sb.append(sep).append(n);
3.91 + sep = ",";
3.92 + }
3.93 + sb.append(") {\n");
3.94 + sb.append(code);
3.95 + sb.append("};");
3.96 + sb.append("})()");
3.97 +
3.98 + JSObject x = (JSObject) engine.executeScript(sb.toString());
3.99 + return new JSFn(x);
3.100 + }
3.101 +
3.102 + @Override
3.103 + public void loadScript(Reader code) throws Exception {
3.104 + BufferedReader r = new BufferedReader(code);
3.105 + StringBuilder sb = new StringBuilder();
3.106 + for (;;) {
3.107 + String l = r.readLine();
3.108 + if (l == null) {
3.109 + break;
3.110 + }
3.111 + sb.append(l).append('\n');
3.112 + }
3.113 + engine.executeScript(sb.toString());
3.114 + }
3.115 +
3.116 + @Override
3.117 + public void displayPage(final URL resource, Runnable onLoad) {
3.118 + engine = FXBrwsr.findEngine(onLoad);
3.119 + Platform.runLater(new Runnable() {
3.120 + @Override
3.121 + public void run() {
3.122 + engine.load(resource.toExternalForm());
3.123 + }
3.124 + });
3.125 + FXBrwsr.waitFinished();
3.126 + }
3.127 +
3.128 + private static final class JSFn extends Fn {
3.129 + private final JSObject fn;
3.130 +
3.131 + public JSFn(JSObject fn) {
3.132 + this.fn = fn;
3.133 + }
3.134 +
3.135 + @Override
3.136 + public Object invoke(Object thiz, Object... args) throws Exception {
3.137 + try {
3.138 + List<Object> all = new ArrayList<Object>(args.length + 1);
3.139 + all.add(thiz == null ? fn : thiz);
3.140 + all.addAll(Arrays.asList(args));
3.141 + Object ret = fn.call("call", all.toArray()); // NOI18N
3.142 + return ret == fn ? null : ret;
3.143 + } catch (Error t) {
3.144 + t.printStackTrace();
3.145 + throw t;
3.146 + } catch (Exception t) {
3.147 + t.printStackTrace();
3.148 + throw t;
3.149 + }
3.150 + }
3.151 + }
3.152 +
3.153 + public static class FXBrwsr extends Application {
3.154 + private static FXBrwsr INSTANCE;
3.155 + private static final CountDownLatch FINISHED = new CountDownLatch(1);
3.156 +
3.157 + private BorderPane root;
3.158 +
3.159 + private static final Logger LOG = Logger.getLogger(FXBrwsr.class.getName());
3.160 +
3.161 + public synchronized static WebEngine findEngine(final Runnable onLoad) {
3.162 + if (INSTANCE == null) {
3.163 + Executors.newFixedThreadPool(1).submit(new Runnable() {
3.164 + @Override
3.165 + public void run() {
3.166 + try {
3.167 + FXBrwsr.launch(FXBrwsr.class);
3.168 + } catch (Throwable ex) {
3.169 + ex.printStackTrace();
3.170 + } finally {
3.171 + FINISHED.countDown();
3.172 + }
3.173 + }
3.174 + });
3.175 + }
3.176 + while (INSTANCE == null) {
3.177 + try {
3.178 + FXBrwsr.class.wait();
3.179 + } catch (InterruptedException ex) {
3.180 + // wait more
3.181 + }
3.182 + }
3.183 + if (!Platform.isFxApplicationThread()) {
3.184 + final WebEngine[] arr = { null };
3.185 + final CountDownLatch waitForResult = new CountDownLatch(1);
3.186 + Platform.runLater(new Runnable() {
3.187 + @Override
3.188 + public void run() {
3.189 + arr[0] = INSTANCE.newEngine(onLoad);
3.190 + waitForResult.countDown();
3.191 + }
3.192 + });
3.193 + for (;;) {
3.194 + try {
3.195 + waitForResult.await();
3.196 + break;
3.197 + } catch (InterruptedException ex) {
3.198 + Exceptions.printStackTrace(ex);
3.199 + }
3.200 + }
3.201 + return arr[0];
3.202 + } else {
3.203 + return INSTANCE.newEngine(onLoad);
3.204 + }
3.205 + }
3.206 +
3.207 + @Override
3.208 + public void start(Stage primaryStage) throws Exception {
3.209 + synchronized (FXBrwsr.class) {
3.210 + INSTANCE = this;
3.211 + FXBrwsr.class.notifyAll();
3.212 + }
3.213 + BorderPane r = new BorderPane();
3.214 + final boolean showToolbar = "true".equals(this.getParameters().getNamed().get("toolbar")); // NOI18N
3.215 + final boolean useFirebug = "true".equals(this.getParameters().getNamed().get("firebug")); // NOI18N
3.216 + if (showToolbar) {
3.217 + //final ToolBar toolbar = new BrowserToolbar(view, vbox, useFirebug, wc.dbg);
3.218 + //root.setTop(toolbar);
3.219 + }
3.220 + Scene scene = new Scene(r, 800, 600);
3.221 + primaryStage.setTitle("Device Emulator");
3.222 + primaryStage.setScene(scene);
3.223 + primaryStage.show();
3.224 + this.root = r;
3.225 + }
3.226 +
3.227 + private WebEngine newEngine(final Runnable onLoad) {
3.228 + final WebView view = new WebView();
3.229 + final String nbUserDir = this.getParameters().getNamed().get("userdir"); // NOI18N
3.230 + WebController wc = new WebController(view, nbUserDir, getParameters().getUnnamed());
3.231 +
3.232 + final VBox vbox = new VBox();
3.233 + vbox.setAlignment(Pos.CENTER);
3.234 + vbox.setStyle("-fx-background-color: #808080;");
3.235 +
3.236 + HBox hbox = new HBox();
3.237 + hbox.setStyle("-fx-background-color: #808080;");
3.238 + hbox.setAlignment(Pos.CENTER);
3.239 + hbox.getChildren().add(vbox);
3.240 + vbox.getChildren().add(view);
3.241 + root.setCenter(hbox);
3.242 +
3.243 + final Worker<Void> w = view.getEngine().getLoadWorker();
3.244 + w.stateProperty().addListener(new ChangeListener<Worker.State>() {
3.245 + @Override
3.246 + public void changed(ObservableValue<? extends Worker.State> ov, Worker.State t, Worker.State newState) {
3.247 + if (newState.equals(Worker.State.SUCCEEDED)) {
3.248 + w.stateProperty().removeListener(this);
3.249 + onLoad.run();
3.250 + }
3.251 + }
3.252 + });
3.253 + return view.getEngine();
3.254 + }
3.255 +
3.256 + /**
3.257 + * Create a resizable WebView pane
3.258 + */
3.259 + private static class WebController {
3.260 + private final String ud;
3.261 +
3.262 + public WebController(WebView view, String ud, List<String> params) {
3.263 + final WebEngine eng = view.getEngine();
3.264 +// this.bridge = new JVMBridge(view.getEngine());
3.265 + this.ud = ud;
3.266 + LOG.log(Level.INFO, "Initializing WebView with {0}", params);
3.267 +
3.268 + if (params.size() > 0) {
3.269 + LOG.log(Level.INFO, "loading page {0}", params.get(0));
3.270 + eng.load(params.get(0));
3.271 + LOG.fine("back from load");
3.272 + }
3.273 + eng.setOnAlert(new EventHandler<WebEvent<String>>() {
3.274 + @Override
3.275 + public void handle(WebEvent<String> t) {
3.276 + final Stage dialogStage = new Stage();
3.277 + dialogStage.initModality(Modality.WINDOW_MODAL);
3.278 + dialogStage.setTitle("Warning");
3.279 + final Button button = new Button("Close");
3.280 + final Text text = new Text(t.getData());
3.281 +
3.282 + VBox box = new VBox();
3.283 + box.setAlignment(Pos.CENTER);
3.284 + box.setSpacing(10);
3.285 + box.setPadding(new Insets(10));
3.286 + box.getChildren().addAll(text, button);
3.287 +
3.288 + dialogStage.setScene(new Scene(box));
3.289 +
3.290 + button.setCancelButton(true);
3.291 + button.setOnAction(new EventHandler<ActionEvent>() {
3.292 + @Override
3.293 + public void handle(ActionEvent t) {
3.294 + dialogStage.close();
3.295 + }
3.296 + });
3.297 +
3.298 + dialogStage.centerOnScreen();
3.299 + dialogStage.showAndWait();
3.300 + }
3.301 + });
3.302 + /*
3.303 + WebDebug wd = null;
3.304 + try {
3.305 + if (ud != null) {
3.306 + wd = WebDebug.create(eng.impl_getDebugger(), ud);
3.307 + }
3.308 + } catch (Exception ex) {
3.309 + LOG.log(Level.WARNING, null, ex);
3.310 + }
3.311 + this.dbg = wd;
3.312 + */
3.313 + }
3.314 +
3.315 + }
3.316 + private static void waitFinished() {
3.317 + for (;;) {
3.318 + try {
3.319 + FINISHED.await();
3.320 + break;
3.321 + } catch (InterruptedException ex) {
3.322 + Exceptions.printStackTrace(ex);
3.323 + }
3.324 + }
3.325 + }
3.326 +
3.327 + }
3.328 +}
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/boot/pom.xml Wed Jun 26 18:09:25 2013 +0200
4.3 @@ -0,0 +1,49 @@
4.4 +<?xml version="1.0"?>
4.5 +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
4.6 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
4.7 + <modelVersion>4.0.0</modelVersion>
4.8 + <parent>
4.9 + <groupId>org.apidesign</groupId>
4.10 + <artifactId>html</artifactId>
4.11 + <version>0.4-SNAPSHOT</version>
4.12 + </parent>
4.13 + <groupId>org.apidesign.html</groupId>
4.14 + <artifactId>net.java.html.boot</artifactId>
4.15 + <version>0.4-SNAPSHOT</version>
4.16 + <name>Browser Bootstrap</name>
4.17 + <url>http://maven.apache.org</url>
4.18 + <properties>
4.19 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
4.20 + </properties>
4.21 + <build>
4.22 + <plugins>
4.23 + <plugin>
4.24 + <groupId>org.apache.maven.plugins</groupId>
4.25 + <artifactId>maven-javadoc-plugin</artifactId>
4.26 + <configuration>
4.27 + <subpackages>net.java.html.js:net.java.html.boot</subpackages>
4.28 + <skip>false</skip>
4.29 + </configuration>
4.30 + </plugin>
4.31 + </plugins>
4.32 + </build>
4.33 + <dependencies>
4.34 + <dependency>
4.35 + <groupId>org.ow2.asm</groupId>
4.36 + <artifactId>asm</artifactId>
4.37 + <version>4.1</version>
4.38 + <type>jar</type>
4.39 + </dependency>
4.40 + <dependency>
4.41 + <groupId>org.testng</groupId>
4.42 + <artifactId>testng</artifactId>
4.43 + <scope>test</scope>
4.44 + <type>jar</type>
4.45 + </dependency>
4.46 + <dependency>
4.47 + <groupId>org.netbeans.api</groupId>
4.48 + <artifactId>org-openide-util-lookup</artifactId>
4.49 + <scope>compile</scope>
4.50 + </dependency>
4.51 + </dependencies>
4.52 +</project>
5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/boot/src/main/java/net/java/html/boot/BrowserBuilder.java Wed Jun 26 18:09:25 2013 +0200
5.3 @@ -0,0 +1,237 @@
5.4 +/**
5.5 + * HTML via Java(tm) Language Bindings
5.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5.7 + *
5.8 + * This program is free software: you can redistribute it and/or modify
5.9 + * it under the terms of the GNU General Public License as published by
5.10 + * the Free Software Foundation, version 2 of the License.
5.11 + *
5.12 + * This program is distributed in the hope that it will be useful,
5.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
5.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5.15 + * GNU General Public License for more details. apidesign.org
5.16 + * designates this particular file as subject to the
5.17 + * "Classpath" exception as provided by apidesign.org
5.18 + * in the License file that accompanied this code.
5.19 + *
5.20 + * You should have received a copy of the GNU General Public License
5.21 + * along with this program. Look for COPYING file in the top folder.
5.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
5.23 + */
5.24 +package net.java.html.boot;
5.25 +
5.26 +import java.io.IOException;
5.27 +import java.lang.reflect.Method;
5.28 +import java.net.MalformedURLException;
5.29 +import java.net.URL;
5.30 +import java.util.Arrays;
5.31 +import java.util.Collection;
5.32 +import java.util.Enumeration;
5.33 +import java.util.ServiceLoader;
5.34 +import java.util.logging.Level;
5.35 +import java.util.logging.Logger;
5.36 +import net.java.html.js.JavaScriptBody;
5.37 +import org.apidesign.html.boot.impl.FnUtils;
5.38 +import org.apidesign.html.boot.spi.Fn;
5.39 +import org.apidesign.html.boot.impl.FindResources;
5.40 +
5.41 +/** Use this builder to launch your Java/HTML based application. Typical
5.42 + * usage in a main method of your application looks like this:
5.43 + * <pre>
5.44 + *
5.45 + * <b>public static void</b> <em>main</em>(String... args) {
5.46 + * BrowserBuilder.{@link #newBrowser}.
5.47 + * {@link #loadClass(java.lang.Class) loadClass(YourMain.class)}.
5.48 + * {@link #loadPage(java.lang.String) loadPage("index.html")}.
5.49 + * {@link #invoke(java.lang.String, java.lang.String[]) invoke("initialized", args)}.
5.50 + * {@link #showAndWait()};
5.51 + * System.exit(0);
5.52 + * }
5.53 + * </pre>
5.54 + * The above will load <code>YourMain</code> class via
5.55 + * a special classloader, it will locate an <code>index.html</code> (relative
5.56 + * to <code>YourMain</code> class) and show it in a browser window. When the
5.57 + * initialization is over, a <b>public static</b> method <em>initialized</em>
5.58 + * in <code>YourMain</code> will be called with provided string parameters.
5.59 + * <p>
5.60 + * This module provides only API for building browsers. To use it properly one
5.61 + * also needs an implementation on the classpath of one's application. For example
5.62 + * use: <pre>
5.63 + * <dependency>
5.64 + * <groupId>org.apidesign.html</groupId>
5.65 + * <artifactId>boot-fx</artifactId>
5.66 + * <scope>runtime</scope>
5.67 + * </dependency>
5.68 + * </pre>
5.69 + *
5.70 + * @author Jaroslav Tulach <jtulach@netbeans.org>
5.71 + */
5.72 +public final class BrowserBuilder {
5.73 + private static final Logger LOG = Logger.getLogger(BrowserBuilder.class.getName());
5.74 +
5.75 + private String resource;
5.76 + private Class<?> clazz;
5.77 + private Class[] browserClass;
5.78 + private Runnable onLoad;
5.79 + private String methodName;
5.80 + private String[] methodArgs;
5.81 +
5.82 + private BrowserBuilder() {
5.83 + }
5.84 +
5.85 + /** Entry method to obtain a new browser builder. Follow by calling
5.86 + * its instance methods like {@link #loadClass(java.lang.Class)} and
5.87 + * {@link #loadPage(java.lang.String)}.
5.88 + *
5.89 + * @return new browser builder
5.90 + */
5.91 + public static BrowserBuilder newBrowser() {
5.92 + return new BrowserBuilder();
5.93 + }
5.94 +
5.95 + /** The class to load when the browser is initialized. This class
5.96 + * is loaded by a special classloader (that supports {@link JavaScriptBody}
5.97 + * and co.).
5.98 + *
5.99 + * @param mainClass the class to load and resolve when the browser is ready
5.100 + * @return this builder
5.101 + */
5.102 + public BrowserBuilder loadClass(Class<?> mainClass) {
5.103 + this.clazz = mainClass;
5.104 + return this;
5.105 + }
5.106 +
5.107 + /** Page to load into the browser. If the <code>page</code> represents
5.108 + * a {@link URL} known to the Java system, the URL is passed to the browser.
5.109 + * Otherwise the system seeks for the resource via {@link Class#getResource(java.lang.String)}
5.110 + * method.
5.111 + *
5.112 + * @param page the location (relative, absolute, or URL) of a page to load
5.113 + * @return this browser
5.114 + */
5.115 + public BrowserBuilder loadPage(String page) {
5.116 + this.resource = page;
5.117 + return this;
5.118 + }
5.119 +
5.120 + /** Specifies callback method to notify the application that the browser is ready.
5.121 + * There should be a <b>public static</b> method in the class specified
5.122 + * by {@link #loadClass(java.lang.Class)} which takes an array of {@link String}
5.123 + * argument. The method is called on the browser dispatch thread one
5.124 + * the browser finishes loading of the {@link #loadPage(java.lang.String) HTML page}.
5.125 + *
5.126 + * @param methodName name of a method to seek for
5.127 + * @param args parameters to pass to the method
5.128 + * @return this builder
5.129 + */
5.130 + public BrowserBuilder invoke(String methodName, String... args) {
5.131 + this.methodName = methodName;
5.132 + this.methodArgs = args;
5.133 + return this;
5.134 + }
5.135 +
5.136 + /** Shows the browser, loads specified page in and executes the
5.137 + * {@link #invoke(java.lang.String, java.lang.String[]) initialization method}.
5.138 + * The method returns when the browser is closed.
5.139 + *
5.140 + * @throws NullPointerException if some of essential parameters (like {@link #loadPage(java.lang.String) page} or
5.141 + * {@link #loadClass(java.lang.Class) class} have not been specified
5.142 + */
5.143 + public void showAndWait() {
5.144 + if (resource == null) {
5.145 + throw new NullPointerException("Need to specify resource via loadPage method");
5.146 + }
5.147 +
5.148 + FImpl impl = new FImpl(clazz.getClassLoader());
5.149 + URL url = null;
5.150 + MalformedURLException mal = null;
5.151 + try {
5.152 + url = new URL(resource);
5.153 + } catch (MalformedURLException ex) {
5.154 + mal = ex;
5.155 + }
5.156 + if (url == null) {
5.157 + url = clazz.getResource(resource);
5.158 + }
5.159 + if (url == null) {
5.160 + IllegalStateException ise = new IllegalStateException("Can't find resouce: " + resource + " relative to " + clazz);
5.161 + if (mal != null) {
5.162 + ise.initCause(mal);
5.163 + }
5.164 + throw ise;
5.165 + }
5.166 +
5.167 + for (Fn.Presenter dfnr : ServiceLoader.load(Fn.Presenter.class)) {
5.168 + final ClassLoader loader = FnUtils.newLoader(impl, dfnr, clazz.getClassLoader().getParent());
5.169 +
5.170 + class OnPageLoad implements Runnable {
5.171 + @Override
5.172 + public void run() {
5.173 + try {
5.174 + Class<?> newClazz = Class.forName(clazz.getName(), true, loader);
5.175 + if (browserClass != null) {
5.176 + browserClass[0] = newClazz;
5.177 + }
5.178 + if (onLoad != null) {
5.179 + onLoad.run();
5.180 + }
5.181 + INIT: if (methodName != null) {
5.182 + Exception firstError = null;
5.183 + if (methodArgs.length == 0) {
5.184 + try {
5.185 + Method m = newClazz.getMethod(methodName);
5.186 + m.invoke(null);
5.187 + break INIT;
5.188 + } catch (Exception ex) {
5.189 + firstError = ex;
5.190 + }
5.191 + }
5.192 + try {
5.193 + Method m = newClazz.getMethod(methodName, String[].class);
5.194 + m.invoke(m, (Object) methodArgs);
5.195 + } catch (Exception ex) {
5.196 + if (firstError != null) {
5.197 + LOG.log(Level.SEVERE, "Can't call " + methodName, firstError);
5.198 + }
5.199 + LOG.log(Level.SEVERE, "Can't call " + methodName + " with args " + Arrays.toString(methodArgs), ex);
5.200 + }
5.201 + }
5.202 + } catch (ClassNotFoundException ex) {
5.203 + LOG.log(Level.SEVERE, "Can't load " + clazz.getName(), ex);
5.204 + }
5.205 + }
5.206 + }
5.207 + dfnr.displayPage(url, new OnPageLoad());
5.208 + return;
5.209 + }
5.210 + throw new IllegalStateException("Can't find any Fn.Definer");
5.211 + }
5.212 +
5.213 + private static final class FImpl implements FindResources {
5.214 + final ClassLoader l;
5.215 +
5.216 + public FImpl(ClassLoader l) {
5.217 + this.l = l;
5.218 + }
5.219 +
5.220 + @Override
5.221 + public void findResources(String path, Collection<? super URL> results, boolean oneIsEnough) {
5.222 + if (oneIsEnough) {
5.223 + URL u = l.getResource(path);
5.224 + if (u != null) {
5.225 + results.add(u);
5.226 + }
5.227 + } else {
5.228 + try {
5.229 + Enumeration<URL> en = l.getResources(path);
5.230 + while (en.hasMoreElements()) {
5.231 + results.add(en.nextElement());
5.232 + }
5.233 + } catch (IOException ex) {
5.234 + // no results
5.235 + }
5.236 + }
5.237 + }
5.238 +
5.239 + }
5.240 +}
6.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
6.2 +++ b/boot/src/main/java/net/java/html/boot/package.html Wed Jun 26 18:09:25 2013 +0200
6.3 @@ -0,0 +1,28 @@
6.4 +<!--
6.5 +
6.6 + HTML via Java(tm) Language Bindings
6.7 + Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
6.8 +
6.9 + This program is free software: you can redistribute it and/or modify
6.10 + it under the terms of the GNU General Public License as published by
6.11 + the Free Software Foundation, version 2 of the License.
6.12 +
6.13 + This program is distributed in the hope that it will be useful,
6.14 + but WITHOUT ANY WARRANTY; without even the implied warranty of
6.15 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
6.16 + GNU General Public License for more details. apidesign.org
6.17 + designates this particular file as subject to the
6.18 + "Classpath" exception as provided by apidesign.org
6.19 + in the License file that accompanied this code.
6.20 +
6.21 + You should have received a copy of the GNU General Public License
6.22 + along with this program. Look for COPYING file in the top folder.
6.23 + If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
6.24 +
6.25 +-->
6.26 +<!DOCTYPE html>
6.27 +<html>
6.28 + <body>
6.29 + <div>Builder class to bootstrap your Java/HTML based application</div>
6.30 + </body>
6.31 +</html>
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/boot/src/main/java/net/java/html/js/JavaScriptBody.java Wed Jun 26 18:09:25 2013 +0200
7.3 @@ -0,0 +1,67 @@
7.4 +/**
7.5 + * HTML via Java(tm) Language Bindings
7.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
7.7 + *
7.8 + * This program is free software: you can redistribute it and/or modify
7.9 + * it under the terms of the GNU General Public License as published by
7.10 + * the Free Software Foundation, version 2 of the License.
7.11 + *
7.12 + * This program is distributed in the hope that it will be useful,
7.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
7.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7.15 + * GNU General Public License for more details. apidesign.org
7.16 + * designates this particular file as subject to the
7.17 + * "Classpath" exception as provided by apidesign.org
7.18 + * in the License file that accompanied this code.
7.19 + *
7.20 + * You should have received a copy of the GNU General Public License
7.21 + * along with this program. Look for COPYING file in the top folder.
7.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
7.23 + */
7.24 +package net.java.html.js;
7.25 +
7.26 +import java.lang.annotation.ElementType;
7.27 +import java.lang.annotation.Retention;
7.28 +import java.lang.annotation.RetentionPolicy;
7.29 +import java.lang.annotation.Target;
7.30 +
7.31 +/** Put this annotation on a method to provide its special implementation
7.32 + * in JavaScript. This is a way to define <em>native</em> methods that
7.33 + * interact with the surrounding environment.
7.34 + *
7.35 + * @author Jaroslav Tulach <jtulach@netbeans.org>
7.36 + */
7.37 +@Retention(RetentionPolicy.CLASS)
7.38 +@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR })
7.39 +public @interface JavaScriptBody {
7.40 + /** Names of parameters for the method generated method that can
7.41 + * be referenced from {@link #body()}.
7.42 + *
7.43 + * @return array of the names of parameters for the method
7.44 + * in JavaScript
7.45 + */
7.46 + public String[] args();
7.47 +
7.48 + /** The actual body of the method in JavaScript. This string will be
7.49 + * put into generated header (last character is '{') and footer (e.g. '}').
7.50 + * The body can reference provided arguments. In case of non-static
7.51 + * instance method it may reference <code>this</code>.
7.52 + *
7.53 + * @return JavaScript body of a function which can access {@link #args()} and possibly
7.54 + * <code>this</code>
7.55 + */
7.56 + public String body();
7.57 +
7.58 + /** Should a special syntax for calling back into Java object be turned on?
7.59 + * The syntax begins with <b>{@code @}</b> followed by fully qualified
7.60 + * package name of the class. Now followed by <b>::</b> and a method in
7.61 + * the class followed by its parameters enclosed inside <b>(...)</b>.
7.62 + * This is the syntax one can use to call <code>run()</code>
7.63 + * method of {@link Runnable}:
7.64 + * <pre>r.@java.lang.Runnable::run()()</pre>.
7.65 + *
7.66 + * @return true, if the script should be scanned for special callback
7.67 + * syntax
7.68 + */
7.69 + public boolean javacall() default false;
7.70 +}
8.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
8.2 +++ b/boot/src/main/java/net/java/html/js/JavaScriptResource.java Wed Jun 26 18:09:25 2013 +0200
8.3 @@ -0,0 +1,42 @@
8.4 +/**
8.5 + * HTML via Java(tm) Language Bindings
8.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
8.7 + *
8.8 + * This program is free software: you can redistribute it and/or modify
8.9 + * it under the terms of the GNU General Public License as published by
8.10 + * the Free Software Foundation, version 2 of the License.
8.11 + *
8.12 + * This program is distributed in the hope that it will be useful,
8.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
8.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8.15 + * GNU General Public License for more details. apidesign.org
8.16 + * designates this particular file as subject to the
8.17 + * "Classpath" exception as provided by apidesign.org
8.18 + * in the License file that accompanied this code.
8.19 + *
8.20 + * You should have received a copy of the GNU General Public License
8.21 + * along with this program. Look for COPYING file in the top folder.
8.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
8.23 + */
8.24 +package net.java.html.js;
8.25 +
8.26 +import java.lang.annotation.ElementType;
8.27 +import java.lang.annotation.Retention;
8.28 +import java.lang.annotation.RetentionPolicy;
8.29 +import java.lang.annotation.Target;
8.30 +import net.java.html.boot.BrowserBuilder;
8.31 +
8.32 +/** When a class annotated by this annotation is loaded into the Java virtual
8.33 + * machine by {@link BrowserBuilder} classloader, the script referenced by
8.34 + * this annotation gets loaded into associated JavaScript executor environment.
8.35 + *
8.36 + * @author Jaroslav Tulach <jtulach@netbeans.org>
8.37 + */
8.38 +@Retention(RetentionPolicy.CLASS)
8.39 +@Target(ElementType.TYPE)
8.40 +public @interface JavaScriptResource {
8.41 + /** The JavaScript file to load in before associated class can execute.
8.42 + * @return relative path with respect to the annotated class
8.43 + */
8.44 + public String value();
8.45 +}
9.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
9.2 +++ b/boot/src/main/java/net/java/html/js/package.html Wed Jun 26 18:09:25 2013 +0200
9.3 @@ -0,0 +1,28 @@
9.4 +<!--
9.5 +
9.6 + HTML via Java(tm) Language Bindings
9.7 + Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
9.8 +
9.9 + This program is free software: you can redistribute it and/or modify
9.10 + it under the terms of the GNU General Public License as published by
9.11 + the Free Software Foundation, version 2 of the License.
9.12 +
9.13 + This program is distributed in the hope that it will be useful,
9.14 + but WITHOUT ANY WARRANTY; without even the implied warranty of
9.15 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9.16 + GNU General Public License for more details. apidesign.org
9.17 + designates this particular file as subject to the
9.18 + "Classpath" exception as provided by apidesign.org
9.19 + in the License file that accompanied this code.
9.20 +
9.21 + You should have received a copy of the GNU General Public License
9.22 + along with this program. Look for COPYING file in the top folder.
9.23 + If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
9.24 +
9.25 +-->
9.26 +<!DOCTYPE html>
9.27 +<html>
9.28 + <body>
9.29 + <div>Essential support for those who write <em>native</em> methods communicating directly with JavaScript</div>
9.30 + </body>
9.31 +</html>
10.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
10.2 +++ b/boot/src/main/java/org/apidesign/html/boot/impl/FindResources.java Wed Jun 26 18:09:25 2013 +0200
10.3 @@ -0,0 +1,34 @@
10.4 +/**
10.5 + * HTML via Java(tm) Language Bindings
10.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
10.7 + *
10.8 + * This program is free software: you can redistribute it and/or modify
10.9 + * it under the terms of the GNU General Public License as published by
10.10 + * the Free Software Foundation, version 2 of the License.
10.11 + *
10.12 + * This program is distributed in the hope that it will be useful,
10.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
10.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10.15 + * GNU General Public License for more details. apidesign.org
10.16 + * designates this particular file as subject to the
10.17 + * "Classpath" exception as provided by apidesign.org
10.18 + * in the License file that accompanied this code.
10.19 + *
10.20 + * You should have received a copy of the GNU General Public License
10.21 + * along with this program. Look for COPYING file in the top folder.
10.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
10.23 + */
10.24 +package org.apidesign.html.boot.impl;
10.25 +
10.26 +import java.net.URL;
10.27 +import java.util.Collection;
10.28 +
10.29 +/**
10.30 + *
10.31 + * @author Jaroslav Tulach <jtulach@netbeans.org>
10.32 + */
10.33 +public interface FindResources {
10.34 +
10.35 + public void findResources(String path, Collection<? super URL> results, boolean oneIsEnough);
10.36 +
10.37 +}
11.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
11.2 +++ b/boot/src/main/java/org/apidesign/html/boot/impl/FnUtils.java Wed Jun 26 18:09:25 2013 +0200
11.3 @@ -0,0 +1,176 @@
11.4 +/**
11.5 + * HTML via Java(tm) Language Bindings
11.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
11.7 + *
11.8 + * This program is free software: you can redistribute it and/or modify
11.9 + * it under the terms of the GNU General Public License as published by
11.10 + * the Free Software Foundation, version 2 of the License.
11.11 + *
11.12 + * This program is distributed in the hope that it will be useful,
11.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
11.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11.15 + * GNU General Public License for more details. apidesign.org
11.16 + * designates this particular file as subject to the
11.17 + * "Classpath" exception as provided by apidesign.org
11.18 + * in the License file that accompanied this code.
11.19 + *
11.20 + * You should have received a copy of the GNU General Public License
11.21 + * along with this program. Look for COPYING file in the top folder.
11.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
11.23 + */
11.24 +package org.apidesign.html.boot.impl;
11.25 +
11.26 +import java.io.InputStream;
11.27 +import java.io.InputStreamReader;
11.28 +import java.io.Reader;
11.29 +import java.lang.reflect.Method;
11.30 +import java.net.URL;
11.31 +import java.util.ArrayList;
11.32 +import java.util.Collections;
11.33 +import java.util.Enumeration;
11.34 +import java.util.List;
11.35 +import org.apidesign.html.boot.spi.Fn;
11.36 +import org.objectweb.asm.Type;
11.37 +
11.38 +/**
11.39 + *
11.40 + * @author Jaroslav Tulach <jtulach@netbeans.org>
11.41 + */
11.42 +public final class FnUtils {
11.43 + private FnUtils() {
11.44 + }
11.45 +
11.46 + public static Fn define(Class<?> caller, String code, String... names) {
11.47 + JsClassLoader cl = (JsClassLoader)caller.getClassLoader();
11.48 + return cl.defineFn(code, names);
11.49 + }
11.50 +
11.51 + public static ClassLoader newLoader(final FindResources f, final Fn.Presenter d, ClassLoader parent) {
11.52 + return new JsClassLoader(parent) {
11.53 + @Override
11.54 + protected URL findResource(String name) {
11.55 + List<URL> l = res(name, true);
11.56 + return l.isEmpty() ? null : l.get(0);
11.57 + }
11.58 +
11.59 + @Override
11.60 + protected Enumeration<URL> findResources(String name) {
11.61 + return Collections.enumeration(res(name, false));
11.62 + }
11.63 +
11.64 + private List<URL> res(String name, boolean oneIsEnough) {
11.65 + List<URL> l = new ArrayList<URL>();
11.66 + f.findResources(name, l, oneIsEnough);
11.67 + return l;
11.68 + }
11.69 +
11.70 + @Override
11.71 + protected Fn defineFn(String code, String... names) {
11.72 + return d.defineFn(code, names);
11.73 + }
11.74 +
11.75 + @Override
11.76 + protected void loadScript(Reader code) throws Exception {
11.77 + d.loadScript(code);
11.78 + }
11.79 + };
11.80 + }
11.81 +
11.82 + static String callback(String body, ClassLoader loader) {
11.83 + try {
11.84 + return callbackImpl(body, loader);
11.85 + } catch (ClassNotFoundException ex) {
11.86 + throw new IllegalStateException("Can't parse " + body, ex);
11.87 + } catch (NoSuchMethodException ex) {
11.88 + throw new IllegalStateException("Can't parse " + body, ex);
11.89 + }
11.90 + }
11.91 +
11.92 + private static String callbackImpl(String body, ClassLoader loader)
11.93 + throws ClassNotFoundException, NoSuchMethodException {
11.94 + StringBuilder sb = new StringBuilder();
11.95 + int pos = 0;
11.96 + for (;;) {
11.97 + int next = body.indexOf(".@", pos);
11.98 + if (next == -1) {
11.99 + sb.append(body.substring(pos));
11.100 + return sb.toString();
11.101 + }
11.102 + sb.append(body.substring(pos, next));
11.103 +
11.104 + int sigBeg = body.indexOf('(', next);
11.105 + int sigEnd = body.indexOf(')', sigBeg);
11.106 +
11.107 + int colon4 = body.indexOf("::", next);
11.108 +
11.109 + if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
11.110 + throw new IllegalStateException("Malformed body " + body);
11.111 + }
11.112 +
11.113 + String fqn = body.substring(next + 2, colon4);
11.114 + String method = body.substring(colon4 + 2, sigBeg);
11.115 + String params = body.substring(sigBeg, sigEnd + 1);
11.116 +
11.117 + Class<?> clazz = Class.forName(fqn, false, loader);
11.118 + final Type[] argTps = Type.getArgumentTypes(params);
11.119 + Class<?>[] argCls = new Class<?>[argTps.length];
11.120 + for (int i = 0; i < argCls.length; i++) {
11.121 + argCls[i] = toClass(argTps[i], loader);
11.122 + }
11.123 + Method m = clazz.getMethod(method, argCls);
11.124 +
11.125 + sb.append("['").append(m.getName()).append("(");
11.126 + String sep = "";
11.127 + for (Class<?> pt : m.getParameterTypes()) {
11.128 + sb.append(sep).append(pt.getName());
11.129 + sep = ",";
11.130 + }
11.131 + sb.append(")']");
11.132 +
11.133 + pos = sigEnd + 1;
11.134 + }
11.135 + }
11.136 +
11.137 + private static Class<?> toClass(final Type t, ClassLoader loader) throws ClassNotFoundException {
11.138 + if (t == Type.INT_TYPE) {
11.139 + return Integer.TYPE;
11.140 + } else if (t == Type.VOID_TYPE) {
11.141 + return Void.TYPE;
11.142 + } else if (t == Type.BOOLEAN_TYPE) {
11.143 + return Boolean.TYPE;
11.144 + } else if (t == Type.BYTE_TYPE) {
11.145 + return Byte.TYPE;
11.146 + } else if (t == Type.CHAR_TYPE) {
11.147 + return Character.TYPE;
11.148 + } else if (t == Type.SHORT_TYPE) {
11.149 + return Short.TYPE;
11.150 + } else if (t == Type.DOUBLE_TYPE) {
11.151 + return Double.TYPE;
11.152 + } else if (t == Type.FLOAT_TYPE) {
11.153 + return Float.TYPE;
11.154 + } else if (t == Type.LONG_TYPE) {
11.155 + return Long.TYPE;
11.156 + }
11.157 + return Class.forName(t.getClassName(), false, loader);
11.158 + }
11.159 +
11.160 + static void loadScript(JsClassLoader jcl, String resource) {
11.161 + final InputStream script = jcl.getResourceAsStream(resource);
11.162 + if (script == null) {
11.163 + throw new NullPointerException("Can't find " + resource);
11.164 + }
11.165 + try {
11.166 + Reader isr = null;
11.167 + try {
11.168 + isr = new InputStreamReader(script, "UTF-8");
11.169 + jcl.loadScript(isr);
11.170 + } finally {
11.171 + if (isr != null) {
11.172 + isr.close();
11.173 + }
11.174 + }
11.175 + } catch (Exception ex) {
11.176 + throw new IllegalStateException("Can't execute " + resource, ex);
11.177 + }
11.178 + }
11.179 +}
12.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
12.2 +++ b/boot/src/main/java/org/apidesign/html/boot/impl/JavaScriptProcesor.java Wed Jun 26 18:09:25 2013 +0200
12.3 @@ -0,0 +1,104 @@
12.4 +/**
12.5 + * HTML via Java(tm) Language Bindings
12.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
12.7 + *
12.8 + * This program is free software: you can redistribute it and/or modify
12.9 + * it under the terms of the GNU General Public License as published by
12.10 + * the Free Software Foundation, version 2 of the License.
12.11 + *
12.12 + * This program is distributed in the hope that it will be useful,
12.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
12.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12.15 + * GNU General Public License for more details. apidesign.org
12.16 + * designates this particular file as subject to the
12.17 + * "Classpath" exception as provided by apidesign.org
12.18 + * in the License file that accompanied this code.
12.19 + *
12.20 + * You should have received a copy of the GNU General Public License
12.21 + * along with this program. Look for COPYING file in the top folder.
12.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
12.23 + */
12.24 +package org.apidesign.html.boot.impl;
12.25 +
12.26 +import java.util.Collections;
12.27 +import java.util.HashSet;
12.28 +import java.util.List;
12.29 +import java.util.Set;
12.30 +import javax.annotation.processing.AbstractProcessor;
12.31 +import javax.annotation.processing.Completion;
12.32 +import javax.annotation.processing.Completions;
12.33 +import javax.annotation.processing.Messager;
12.34 +import javax.annotation.processing.Processor;
12.35 +import javax.annotation.processing.RoundEnvironment;
12.36 +import javax.lang.model.element.AnnotationMirror;
12.37 +import javax.lang.model.element.Element;
12.38 +import javax.lang.model.element.ElementKind;
12.39 +import javax.lang.model.element.ExecutableElement;
12.40 +import javax.lang.model.element.TypeElement;
12.41 +import javax.lang.model.element.VariableElement;
12.42 +import javax.tools.Diagnostic;
12.43 +import net.java.html.js.JavaScriptBody;
12.44 +import net.java.html.js.JavaScriptResource;
12.45 +import org.openide.util.lookup.ServiceProvider;
12.46 +
12.47 +/**
12.48 + *
12.49 + * @author Jaroslav Tulach <jtulach@netbeans.org>
12.50 + */
12.51 +@ServiceProvider(service = Processor.class)
12.52 +public final class JavaScriptProcesor extends AbstractProcessor {
12.53 + @Override
12.54 + public Set<String> getSupportedAnnotationTypes() {
12.55 + Set<String> set = new HashSet<String>();
12.56 + set.add(JavaScriptBody.class.getName());
12.57 + set.add(JavaScriptResource.class.getName());
12.58 + return set;
12.59 + }
12.60 +
12.61 + @Override
12.62 + public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
12.63 + final Messager msg = processingEnv.getMessager();
12.64 + for (Element e : roundEnv.getElementsAnnotatedWith(JavaScriptBody.class)) {
12.65 + if (e.getKind() != ElementKind.METHOD && e.getKind() != ElementKind.CONSTRUCTOR) {
12.66 + continue;
12.67 + }
12.68 + ExecutableElement ee = (ExecutableElement)e;
12.69 + List<? extends VariableElement> params = ee.getParameters();
12.70 +
12.71 + JavaScriptBody jsb = e.getAnnotation(JavaScriptBody.class);
12.72 + if (jsb == null) {
12.73 + continue;
12.74 + }
12.75 + String[] arr = jsb.args();
12.76 + if (params.size() != arr.length) {
12.77 + msg.printMessage(Diagnostic.Kind.ERROR, "Number of args arguments does not match real arguments!", e);
12.78 + }
12.79 + if (!jsb.javacall() && jsb.body().contains(".@")) {
12.80 + msg.printMessage(Diagnostic.Kind.WARNING, "Usage of .@ usually requires javacall=true", e);
12.81 + }
12.82 + }
12.83 + return true;
12.84 + }
12.85 +
12.86 + @Override
12.87 + public Iterable<? extends Completion> getCompletions(Element e,
12.88 + AnnotationMirror annotation, ExecutableElement member, String userText
12.89 + ) {
12.90 + StringBuilder sb = new StringBuilder();
12.91 + if (e.getKind() == ElementKind.METHOD && member.getSimpleName().contentEquals("args")) {
12.92 + ExecutableElement ee = (ExecutableElement) e;
12.93 + String sep = "";
12.94 + sb.append("{ ");
12.95 + for (VariableElement ve : ee.getParameters()) {
12.96 + sb.append(sep).append('"').append(ve.getSimpleName())
12.97 + .append('"');
12.98 + sep = ", ";
12.99 + }
12.100 + sb.append(" }");
12.101 + return Collections.nCopies(1, Completions.of(sb.toString()));
12.102 + }
12.103 + return null;
12.104 + }
12.105 +
12.106 +
12.107 +}
13.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
13.2 +++ b/boot/src/main/java/org/apidesign/html/boot/impl/JsClassLoader.java Wed Jun 26 18:09:25 2013 +0200
13.3 @@ -0,0 +1,464 @@
13.4 +/**
13.5 + * HTML via Java(tm) Language Bindings
13.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
13.7 + *
13.8 + * This program is free software: you can redistribute it and/or modify
13.9 + * it under the terms of the GNU General Public License as published by
13.10 + * the Free Software Foundation, version 2 of the License.
13.11 + *
13.12 + * This program is distributed in the hope that it will be useful,
13.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
13.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13.15 + * GNU General Public License for more details. apidesign.org
13.16 + * designates this particular file as subject to the
13.17 + * "Classpath" exception as provided by apidesign.org
13.18 + * in the License file that accompanied this code.
13.19 + *
13.20 + * You should have received a copy of the GNU General Public License
13.21 + * along with this program. Look for COPYING file in the top folder.
13.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
13.23 + */
13.24 +package org.apidesign.html.boot.impl;
13.25 +
13.26 +import org.apidesign.html.boot.spi.Fn;
13.27 +import java.io.IOException;
13.28 +import java.io.InputStream;
13.29 +import java.io.Reader;
13.30 +import java.net.URL;
13.31 +import java.util.ArrayList;
13.32 +import java.util.Enumeration;
13.33 +import java.util.List;
13.34 +import org.objectweb.asm.AnnotationVisitor;
13.35 +import org.objectweb.asm.ClassReader;
13.36 +import org.objectweb.asm.ClassVisitor;
13.37 +import org.objectweb.asm.ClassWriter;
13.38 +import org.objectweb.asm.Label;
13.39 +import org.objectweb.asm.MethodVisitor;
13.40 +import org.objectweb.asm.Opcodes;
13.41 +import org.objectweb.asm.Type;
13.42 +import org.objectweb.asm.signature.SignatureReader;
13.43 +import org.objectweb.asm.signature.SignatureVisitor;
13.44 +import org.objectweb.asm.signature.SignatureWriter;
13.45 +
13.46 +/**
13.47 + *
13.48 + * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
13.49 + */
13.50 +abstract class JsClassLoader extends ClassLoader {
13.51 + JsClassLoader(ClassLoader parent) {
13.52 + super(parent);
13.53 + setDefaultAssertionStatus(JsClassLoader.class.desiredAssertionStatus());
13.54 + }
13.55 +
13.56 + @Override
13.57 + protected abstract URL findResource(String name);
13.58 +
13.59 + @Override
13.60 + protected abstract Enumeration<URL> findResources(String name);
13.61 +
13.62 + @Override
13.63 + protected Class<?> findClass(String name) throws ClassNotFoundException {
13.64 + if (name.startsWith("javafx")) {
13.65 + return Class.forName(name);
13.66 + }
13.67 + if (name.startsWith("netscape")) {
13.68 + return Class.forName(name);
13.69 + }
13.70 + if (name.startsWith("com.sun")) {
13.71 + return Class.forName(name);
13.72 + }
13.73 + if (name.equals(JsClassLoader.class.getName())) {
13.74 + return JsClassLoader.class;
13.75 + }
13.76 + if (name.equals(Fn.class.getName())) {
13.77 + return Fn.class;
13.78 + }
13.79 + if (name.equals(FnUtils.class.getName())) {
13.80 + return FnUtils.class;
13.81 + }
13.82 + URL u = findResource(name.replace('.', '/') + ".class");
13.83 + if (u != null) {
13.84 + InputStream is = null;
13.85 + try {
13.86 + is = u.openStream();
13.87 + byte[] arr = new byte[is.available()];
13.88 + int len = 0;
13.89 + while (len < arr.length) {
13.90 + int read = is.read(arr, len, arr.length - len);
13.91 + if (read == -1) {
13.92 + throw new IOException("Can't read " + u);
13.93 + }
13.94 + len += read;
13.95 + }
13.96 + is.close();
13.97 + is = null;
13.98 + ClassReader cr = new ClassReader(arr);
13.99 + FindInClass tst = new FindInClass(null);
13.100 + cr.accept(tst, 0);
13.101 + if (tst.found > 0) {
13.102 + ClassWriter w = new ClassWriterEx(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
13.103 + FindInClass fic = new FindInClass(w);
13.104 + cr.accept(fic, 0);
13.105 + arr = w.toByteArray();
13.106 + }
13.107 + if (arr != null) {
13.108 + return defineClass(name, arr, 0, arr.length);
13.109 + }
13.110 + } catch (IOException ex) {
13.111 + throw new ClassNotFoundException("Can't load " + name, ex);
13.112 + } finally {
13.113 + try {
13.114 + if (is != null) is.close();
13.115 + } catch (IOException ex) {
13.116 + throw new ClassNotFoundException(null, ex);
13.117 + }
13.118 + }
13.119 + }
13.120 + if (
13.121 + name.equals("org.apidesign.html.boot.spi.Fn") ||
13.122 + name.equals("org.apidesign.html.boot.impl.FnUtils")
13.123 + ) {
13.124 + return Class.forName(name);
13.125 + }
13.126 +
13.127 + return super.findClass(name);
13.128 + }
13.129 +
13.130 + protected abstract Fn defineFn(String code, String... names);
13.131 + protected abstract void loadScript(Reader code) throws Exception;
13.132 +
13.133 + private final class FindInClass extends ClassVisitor {
13.134 + private String name;
13.135 + private int found;
13.136 +
13.137 + public FindInClass(ClassVisitor cv) {
13.138 + super(Opcodes.ASM4, cv);
13.139 + }
13.140 +
13.141 + @Override
13.142 + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
13.143 + this.name = name;
13.144 + super.visit(version, access, name, signature, superName, interfaces);
13.145 + }
13.146 +
13.147 + @Override
13.148 + public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
13.149 + if ("Lnet/java/html/js/JavaScriptResource;".equals(desc)) {
13.150 + return new LoadResource();
13.151 + }
13.152 + return super.visitAnnotation(desc, visible);
13.153 + }
13.154 +
13.155 +
13.156 + @Override
13.157 + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
13.158 + return new FindInMethod(access, name, desc,
13.159 + super.visitMethod(access & (~Opcodes.ACC_NATIVE), name, desc, signature, exceptions)
13.160 + );
13.161 + }
13.162 +
13.163 + private final class FindInMethod extends MethodVisitor {
13.164 + private final String name;
13.165 + private final String desc;
13.166 + private final int access;
13.167 + private List<String> args;
13.168 + private String body;
13.169 + private boolean bodyGenerated;
13.170 +
13.171 + public FindInMethod(int access, String name, String desc, MethodVisitor mv) {
13.172 + super(Opcodes.ASM4, mv);
13.173 + this.access = access;
13.174 + this.name = name;
13.175 + this.desc = desc;
13.176 + }
13.177 +
13.178 + @Override
13.179 + public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
13.180 + if (
13.181 + "Lnet/java/html/js/JavaScriptBody;".equals(desc) // NOI18N
13.182 + || "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;".equals(desc) // NOI18N
13.183 + ) {
13.184 + found++;
13.185 + return new FindInAnno();
13.186 + }
13.187 + return super.visitAnnotation(desc, visible);
13.188 + }
13.189 +
13.190 + private void generateJSBody(List<String> args, String body) {
13.191 + this.args = args;
13.192 + this.body = body;
13.193 + }
13.194 +
13.195 + @Override
13.196 + public void visitCode() {
13.197 + if (body == null) {
13.198 + return;
13.199 + }
13.200 + generateBody();
13.201 + }
13.202 +
13.203 + private boolean generateBody() {
13.204 + if (bodyGenerated) {
13.205 + return false;
13.206 + }
13.207 + bodyGenerated = true;
13.208 +
13.209 + super.visitFieldInsn(
13.210 + Opcodes.GETSTATIC, FindInClass.this.name,
13.211 + "$$fn$$" + name + "_" + found,
13.212 + "Lorg/apidesign/html/boot/spi/Fn;"
13.213 + );
13.214 + super.visitInsn(Opcodes.DUP);
13.215 + Label ifNotNull = new Label();
13.216 + super.visitJumpInsn(Opcodes.IFNONNULL, ifNotNull);
13.217 +
13.218 + // init Fn
13.219 + super.visitInsn(Opcodes.POP);
13.220 + super.visitLdcInsn(Type.getObjectType(FindInClass.this.name));
13.221 + super.visitLdcInsn(body);
13.222 + super.visitIntInsn(Opcodes.SIPUSH, args.size());
13.223 + super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
13.224 + for (int i = 0; i < args.size(); i++) {
13.225 + String name = args.get(i);
13.226 + super.visitInsn(Opcodes.DUP);
13.227 + super.visitIntInsn(Opcodes.BIPUSH, i);
13.228 + super.visitLdcInsn(name);
13.229 + super.visitInsn(Opcodes.AASTORE);
13.230 + }
13.231 + super.visitMethodInsn(Opcodes.INVOKESTATIC,
13.232 + "org/apidesign/html/boot/impl/FnUtils", "define",
13.233 + "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Lorg/apidesign/html/boot/spi/Fn;"
13.234 + );
13.235 + // end of Fn init
13.236 +
13.237 + super.visitLabel(ifNotNull);
13.238 +
13.239 + final int offset;
13.240 + if ((access & Opcodes.ACC_STATIC) == 0) {
13.241 + offset = 1;
13.242 + super.visitIntInsn(Opcodes.ALOAD, 0);
13.243 + } else {
13.244 + offset = 0;
13.245 + super.visitInsn(Opcodes.ACONST_NULL);
13.246 + }
13.247 +
13.248 + super.visitIntInsn(Opcodes.SIPUSH, args.size());
13.249 + super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
13.250 +
13.251 + class SV extends SignatureVisitor {
13.252 + private boolean nowReturn;
13.253 + private Type returnType;
13.254 + private int index;
13.255 +
13.256 + public SV() {
13.257 + super(Opcodes.ASM4);
13.258 + }
13.259 +
13.260 + @Override
13.261 + public void visitBaseType(char descriptor) {
13.262 + final Type t = Type.getType("" + descriptor);
13.263 + if (nowReturn) {
13.264 + returnType = t;
13.265 + return;
13.266 + }
13.267 + FindInMethod.super.visitInsn(Opcodes.DUP);
13.268 + FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
13.269 + FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), index + offset);
13.270 + String factory;
13.271 + switch (descriptor) {
13.272 + case 'I': factory = "java/lang/Integer"; break;
13.273 + case 'J': factory = "java/lang/Long"; break;
13.274 + case 'S': factory = "java/lang/Short"; break;
13.275 + case 'F': factory = "java/lang/Float"; break;
13.276 + case 'D': factory = "java/lang/Double"; break;
13.277 + case 'Z': factory = "java/lang/Boolean"; break;
13.278 + case 'C': factory = "java/lang/Character"; break;
13.279 + case 'B': factory = "java/lang/Byte"; break;
13.280 + default: throw new IllegalStateException(t.toString());
13.281 + }
13.282 + FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
13.283 + factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
13.284 + );
13.285 + FindInMethod.super.visitInsn(Opcodes.AASTORE);
13.286 + index++;
13.287 + }
13.288 +
13.289 + @Override
13.290 + public SignatureVisitor visitArrayType() {
13.291 + if (nowReturn) {
13.292 + throw new IllegalStateException("Not supported yet");
13.293 + }
13.294 + loadObject();
13.295 + return new SignatureWriter();
13.296 + }
13.297 +
13.298 + @Override
13.299 + public void visitClassType(String name) {
13.300 + if (nowReturn) {
13.301 + returnType = Type.getObjectType(name);
13.302 + return;
13.303 + }
13.304 + loadObject();
13.305 + }
13.306 +
13.307 + @Override
13.308 + public SignatureVisitor visitReturnType() {
13.309 + nowReturn = true;
13.310 + return this;
13.311 + }
13.312 +
13.313 + private void loadObject() {
13.314 + FindInMethod.super.visitInsn(Opcodes.DUP);
13.315 + FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
13.316 + FindInMethod.super.visitVarInsn(Opcodes.ALOAD, index + offset);
13.317 + FindInMethod.super.visitInsn(Opcodes.AASTORE);
13.318 + index++;
13.319 + }
13.320 +
13.321 + }
13.322 + SV sv = new SV();
13.323 + SignatureReader sr = new SignatureReader(desc);
13.324 + sr.accept(sv);
13.325 +
13.326 + super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
13.327 + "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
13.328 + );
13.329 + switch (sv.returnType.getSort()) {
13.330 + case Type.VOID:
13.331 + super.visitInsn(Opcodes.RETURN);
13.332 + break;
13.333 + case Type.ARRAY:
13.334 + case Type.OBJECT:
13.335 + super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
13.336 + super.visitInsn(Opcodes.ARETURN);
13.337 + break;
13.338 + case Type.BOOLEAN:
13.339 + super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Boolean");
13.340 + super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
13.341 + "java/lang/Boolean", "booleanValue", "()Z"
13.342 + );
13.343 + super.visitInsn(Opcodes.IRETURN);
13.344 + break;
13.345 + default:
13.346 + super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
13.347 + super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
13.348 + "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
13.349 + );
13.350 + super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
13.351 + }
13.352 + return true;
13.353 + }
13.354 +
13.355 + @Override
13.356 + public void visitEnd() {
13.357 + super.visitEnd();
13.358 + if (body != null) {
13.359 + if (generateBody()) {
13.360 + // native method
13.361 + super.visitMaxs(1, 0);
13.362 + }
13.363 + FindInClass.this.visitField(
13.364 + Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
13.365 + "$$fn$$" + name + "_" + found,
13.366 + "Lorg/apidesign/html/boot/spi/Fn;",
13.367 + null, null
13.368 + );
13.369 + }
13.370 + }
13.371 +
13.372 +
13.373 +
13.374 +
13.375 +
13.376 + private final class FindInAnno extends AnnotationVisitor {
13.377 + private List<String> args = new ArrayList<String>();
13.378 + private String body;
13.379 + private boolean javacall = false;
13.380 +
13.381 + public FindInAnno() {
13.382 + super(Opcodes.ASM4);
13.383 + }
13.384 +
13.385 + @Override
13.386 + public void visit(String name, Object value) {
13.387 + if (name == null) {
13.388 + args.add((String) value);
13.389 + return;
13.390 + }
13.391 + if (name.equals("javacall")) { // NOI18N
13.392 + javacall = (Boolean)value;
13.393 + return;
13.394 + }
13.395 + assert name.equals("body");
13.396 + body = (String) value;
13.397 + }
13.398 +
13.399 + @Override
13.400 + public AnnotationVisitor visitArray(String name) {
13.401 + return this;
13.402 + }
13.403 +
13.404 + @Override
13.405 + public void visitEnd() {
13.406 + if (body != null) {
13.407 + generateJSBody(args, javacall ?
13.408 + FnUtils.callback(body, JsClassLoader.this) :
13.409 + body
13.410 + );
13.411 + }
13.412 + }
13.413 + }
13.414 + }
13.415 +
13.416 + private final class LoadResource extends AnnotationVisitor {
13.417 + public LoadResource() {
13.418 + super(Opcodes.ASM4);
13.419 + }
13.420 +
13.421 + @Override
13.422 + public void visit(String attrName, Object value) {
13.423 + String relPath = (String) value;
13.424 + if (relPath.startsWith("/")) {
13.425 + FnUtils.loadScript(JsClassLoader.this, relPath);
13.426 + } else {
13.427 + int last = name.lastIndexOf('/');
13.428 + String fullPath = name.substring(0, last + 1) + relPath;
13.429 + FnUtils.loadScript(JsClassLoader.this, fullPath);
13.430 + }
13.431 + }
13.432 + }
13.433 + }
13.434 +
13.435 + private class ClassWriterEx extends ClassWriter {
13.436 +
13.437 + public ClassWriterEx(ClassReader classReader, int flags) {
13.438 + super(classReader, flags);
13.439 + }
13.440 +
13.441 + @Override
13.442 + protected String getCommonSuperClass(final String type1, final String type2) {
13.443 + Class<?> c, d;
13.444 + ClassLoader classLoader = JsClassLoader.this;
13.445 + try {
13.446 + c = Class.forName(type1.replace('/', '.'), false, classLoader);
13.447 + d = Class.forName(type2.replace('/', '.'), false, classLoader);
13.448 + } catch (Exception e) {
13.449 + throw new RuntimeException(e.toString());
13.450 + }
13.451 + if (c.isAssignableFrom(d)) {
13.452 + return type1;
13.453 + }
13.454 + if (d.isAssignableFrom(c)) {
13.455 + return type2;
13.456 + }
13.457 + if (c.isInterface() || d.isInterface()) {
13.458 + return "java/lang/Object";
13.459 + } else {
13.460 + do {
13.461 + c = c.getSuperclass();
13.462 + } while (!c.isAssignableFrom(d));
13.463 + return c.getName().replace('.', '/');
13.464 + }
13.465 + }
13.466 + }
13.467 +}
14.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
14.2 +++ b/boot/src/main/java/org/apidesign/html/boot/spi/Fn.java Wed Jun 26 18:09:25 2013 +0200
14.3 @@ -0,0 +1,38 @@
14.4 +/**
14.5 + * HTML via Java(tm) Language Bindings
14.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
14.7 + *
14.8 + * This program is free software: you can redistribute it and/or modify
14.9 + * it under the terms of the GNU General Public License as published by
14.10 + * the Free Software Foundation, version 2 of the License.
14.11 + *
14.12 + * This program is distributed in the hope that it will be useful,
14.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
14.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14.15 + * GNU General Public License for more details. apidesign.org
14.16 + * designates this particular file as subject to the
14.17 + * "Classpath" exception as provided by apidesign.org
14.18 + * in the License file that accompanied this code.
14.19 + *
14.20 + * You should have received a copy of the GNU General Public License
14.21 + * along with this program. Look for COPYING file in the top folder.
14.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
14.23 + */
14.24 +package org.apidesign.html.boot.spi;
14.25 +
14.26 +import java.io.Reader;
14.27 +import java.net.URL;
14.28 +
14.29 +/**
14.30 + *
14.31 + * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
14.32 + */
14.33 +public abstract class Fn {
14.34 + public abstract Object invoke(Object thiz, Object... args) throws Exception;
14.35 +
14.36 + public interface Presenter {
14.37 + public Fn defineFn(String code, String... names);
14.38 + public void displayPage(URL page, Runnable onPageLoad);
14.39 + public void loadScript(Reader code) throws Exception;
14.40 + }
14.41 +}
15.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
15.2 +++ b/boot/src/test/java/org/apidesign/html/boot/impl/Arithm.java Wed Jun 26 18:09:25 2013 +0200
15.3 @@ -0,0 +1,31 @@
15.4 +/**
15.5 + * HTML via Java(tm) Language Bindings
15.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
15.7 + *
15.8 + * This program is free software: you can redistribute it and/or modify
15.9 + * it under the terms of the GNU General Public License as published by
15.10 + * the Free Software Foundation, version 2 of the License.
15.11 + *
15.12 + * This program is distributed in the hope that it will be useful,
15.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
15.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15.15 + * GNU General Public License for more details. apidesign.org
15.16 + * designates this particular file as subject to the
15.17 + * "Classpath" exception as provided by apidesign.org
15.18 + * in the License file that accompanied this code.
15.19 + *
15.20 + * You should have received a copy of the GNU General Public License
15.21 + * along with this program. Look for COPYING file in the top folder.
15.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
15.23 + */
15.24 +package org.apidesign.html.boot.impl;
15.25 +
15.26 +/**
15.27 + *
15.28 + * @author Jaroslav Tulach <jtulach@netbeans.org>
15.29 + */
15.30 +public class Arithm {
15.31 + public int sumTwo(int a, int b) {
15.32 + return a + b;
15.33 + }
15.34 +}
16.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
16.2 +++ b/boot/src/test/java/org/apidesign/html/boot/impl/FnTest.java Wed Jun 26 18:09:25 2013 +0200
16.3 @@ -0,0 +1,119 @@
16.4 +/**
16.5 + * HTML via Java(tm) Language Bindings
16.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
16.7 + *
16.8 + * This program is free software: you can redistribute it and/or modify
16.9 + * it under the terms of the GNU General Public License as published by
16.10 + * the Free Software Foundation, version 2 of the License.
16.11 + *
16.12 + * This program is distributed in the hope that it will be useful,
16.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
16.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16.15 + * GNU General Public License for more details. apidesign.org
16.16 + * designates this particular file as subject to the
16.17 + * "Classpath" exception as provided by apidesign.org
16.18 + * in the License file that accompanied this code.
16.19 + *
16.20 + * You should have received a copy of the GNU General Public License
16.21 + * along with this program. Look for COPYING file in the top folder.
16.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
16.23 + */
16.24 +
16.25 +package org.apidesign.html.boot.impl;
16.26 +
16.27 +import java.io.Reader;
16.28 +import java.net.URL;
16.29 +import java.net.URLClassLoader;
16.30 +import java.util.ArrayList;
16.31 +import java.util.Arrays;
16.32 +import java.util.Collection;
16.33 +import java.util.List;
16.34 +import javax.script.Invocable;
16.35 +import javax.script.ScriptEngine;
16.36 +import javax.script.ScriptEngineManager;
16.37 +import javax.script.ScriptException;
16.38 +import org.apidesign.html.boot.spi.Fn;
16.39 +import org.testng.annotations.BeforeClass;
16.40 +
16.41 +/**
16.42 + *
16.43 + * @author Jaroslav Tulach <jtulach@netbeans.org>
16.44 + */
16.45 +public class FnTest extends JsClassLoaderBase {
16.46 +
16.47 + public FnTest() {
16.48 + }
16.49 +
16.50 + @BeforeClass
16.51 + public static void createClassLoader() throws Exception {
16.52 + ScriptEngineManager sem = new ScriptEngineManager();
16.53 + final ScriptEngine eng = sem.getEngineByMimeType("text/javascript");
16.54 +
16.55 + final URL my = FnTest.class.getProtectionDomain().getCodeSource().getLocation();
16.56 + ClassLoader parent = JsClassLoaderTest.class.getClassLoader().getParent();
16.57 + final URLClassLoader ul = new URLClassLoader(new URL[] { my }, parent);
16.58 +
16.59 + class Impl implements FindResources, Fn.Presenter {
16.60 + @Override
16.61 + public void findResources(String path, Collection<? super URL> results, boolean oneIsEnough) {
16.62 + URL u = ul.findResource(path);
16.63 + if (u != null) {
16.64 + results.add(u);
16.65 + }
16.66 + }
16.67 +
16.68 + @Override
16.69 + public Fn defineFn(String code, String... names) {
16.70 + StringBuilder sb = new StringBuilder();
16.71 + sb.append("(function() {");
16.72 + sb.append("return function(");
16.73 + String sep = "";
16.74 + for (String n : names) {
16.75 + sb.append(sep);
16.76 + sb.append(n);
16.77 + sep = ", ";
16.78 + }
16.79 + sb.append(") {");
16.80 + sb.append(code);
16.81 + sb.append("};");
16.82 + sb.append("})()");
16.83 + try {
16.84 + final Object val = eng.eval(sb.toString());
16.85 + return new Fn() {
16.86 + @Override
16.87 + public Object invoke(Object thiz, Object... args) throws Exception {
16.88 + List<Object> all = new ArrayList<Object>(args.length + 1);
16.89 + all.add(thiz == null ? val : thiz);
16.90 + all.addAll(Arrays.asList(args));
16.91 + Invocable inv = (Invocable)eng;
16.92 + try {
16.93 + Object ret = inv.invokeMethod(val, "call", all.toArray());
16.94 + return ret == val ? null : ret;
16.95 + } catch (ScriptException ex) {
16.96 + throw ex;
16.97 + }
16.98 + }
16.99 + };
16.100 + } catch (ScriptException ex) {
16.101 + throw new LinkageError("Can't parse: " + sb, ex);
16.102 + }
16.103 + }
16.104 +
16.105 + @Override
16.106 + public void displayPage(URL resource, Runnable r) {
16.107 + throw new UnsupportedOperationException();
16.108 + }
16.109 +
16.110 + @Override
16.111 + public void loadScript(Reader code) throws Exception {
16.112 + eng.eval(code);
16.113 + }
16.114 + }
16.115 + Impl impl = new Impl();
16.116 + ClassLoader loader = FnUtils.newLoader(impl, impl, parent);
16.117 +
16.118 +
16.119 + methodClass = loader.loadClass(JsMethods.class.getName());
16.120 + }
16.121 +
16.122 +}
17.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
17.2 +++ b/boot/src/test/java/org/apidesign/html/boot/impl/JsClassLoaderBase.java Wed Jun 26 18:09:25 2013 +0200
17.3 @@ -0,0 +1,139 @@
17.4 +/**
17.5 + * HTML via Java(tm) Language Bindings
17.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
17.7 + *
17.8 + * This program is free software: you can redistribute it and/or modify
17.9 + * it under the terms of the GNU General Public License as published by
17.10 + * the Free Software Foundation, version 2 of the License.
17.11 + *
17.12 + * This program is distributed in the hope that it will be useful,
17.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
17.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17.15 + * GNU General Public License for more details. apidesign.org
17.16 + * designates this particular file as subject to the
17.17 + * "Classpath" exception as provided by apidesign.org
17.18 + * in the License file that accompanied this code.
17.19 + *
17.20 + * You should have received a copy of the GNU General Public License
17.21 + * along with this program. Look for COPYING file in the top folder.
17.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
17.23 + */
17.24 +package org.apidesign.html.boot.impl;
17.25 +
17.26 +import java.lang.reflect.InvocationTargetException;
17.27 +import java.lang.reflect.Method;
17.28 +import java.lang.reflect.Modifier;
17.29 +import static org.testng.Assert.*;
17.30 +import org.testng.annotations.BeforeMethod;
17.31 +import org.testng.annotations.Test;
17.32 +
17.33 +/**
17.34 + *
17.35 + * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
17.36 + */
17.37 +public class JsClassLoaderBase {
17.38 + protected static Class<?> methodClass;
17.39 +
17.40 + public JsClassLoaderBase() {
17.41 + }
17.42 +
17.43 + @BeforeMethod
17.44 + public void assertClassDefined() {
17.45 + assertNotNull(methodClass, "BeforeClass set up code should provide methodClass");
17.46 + }
17.47 +
17.48 + @Test public void noParamMethod() throws Throwable {
17.49 + Method plus = methodClass.getMethod("fortyTwo");
17.50 + try {
17.51 + final Object val = plus.invoke(null);
17.52 + assertTrue(val instanceof Number, "A number returned " + val);
17.53 + assertEquals(((Number)val).intValue(), 42);
17.54 + } catch (InvocationTargetException ex) {
17.55 + throw ex.getTargetException();
17.56 + }
17.57 + }
17.58 +
17.59 + @Test public void testExecuteScript() throws Throwable {
17.60 + Method plus = methodClass.getMethod("plus", int.class, int.class);
17.61 + try {
17.62 + assertEquals(plus.invoke(null, 10, 20), 30);
17.63 + } catch (InvocationTargetException ex) {
17.64 + throw ex.getTargetException();
17.65 + }
17.66 + }
17.67 +
17.68 + @Test public void overloadedMethod() throws Throwable {
17.69 + Method plus = methodClass.getMethod("plus", int.class);
17.70 + try {
17.71 + assertEquals(plus.invoke(null, 10), 10);
17.72 + } catch (InvocationTargetException ex) {
17.73 + throw ex.getTargetException();
17.74 + }
17.75 + }
17.76 +
17.77 + @Test public void instanceMethod() throws Throwable {
17.78 + Method plus = methodClass.getMethod("plusInst", int.class);
17.79 + Object inst = methodClass.newInstance();
17.80 + try {
17.81 + assertEquals(plus.invoke(inst, 10), 10);
17.82 + } catch (InvocationTargetException ex) {
17.83 + throw ex.getTargetException();
17.84 + }
17.85 + }
17.86 +
17.87 + @Test public void staticThis() throws Throwable {
17.88 + Method st = methodClass.getMethod("staticThis");
17.89 + try {
17.90 + assertNull(st.invoke(null));
17.91 + } catch (InvocationTargetException ex) {
17.92 + throw ex.getTargetException();
17.93 + }
17.94 + }
17.95 +
17.96 + @Test public void getThis() throws Throwable {
17.97 + Object th = methodClass.newInstance();
17.98 + Method st = methodClass.getMethod("getThis");
17.99 + try {
17.100 + assertEquals(st.invoke(th), th);
17.101 + } catch (InvocationTargetException ex) {
17.102 + throw ex.getTargetException();
17.103 + }
17.104 + }
17.105 +
17.106 + @Test public void truth() throws Throwable {
17.107 + Method st = methodClass.getMethod("truth");
17.108 + assertTrue((st.getModifiers() & Modifier.STATIC) != 0, "Is static");
17.109 + assertEquals(st.invoke(null), Boolean.TRUE, "Can return boolean");
17.110 + }
17.111 +
17.112 + @Test public void callback() throws Throwable {
17.113 + class R implements Runnable {
17.114 + int cnt;
17.115 +
17.116 + @Override
17.117 + public void run() {
17.118 + cnt++;
17.119 + }
17.120 + }
17.121 + R r = new R();
17.122 +
17.123 + Method inc = methodClass.getMethod("callback", Runnable.class);
17.124 + inc.invoke(null, r);
17.125 +
17.126 + assertEquals(r.cnt, 1, "Callback happened");
17.127 + }
17.128 +
17.129 + @Test public void sumArray() throws Throwable {
17.130 + Method st = methodClass.getMethod("sumArr", int[].class);
17.131 + assertEquals(st.invoke(null, new int[] { 1, 2, 3 }), 6, "1+2+3 is six");
17.132 + }
17.133 +
17.134 + @Test public void javaScriptResource() throws Throwable {
17.135 + try {
17.136 + Method st = methodClass.getMethod("useExternalMul", int.class, int.class);
17.137 + assertEquals(st.invoke(null, 6, 7), 42, "Meaning of JavaScript?");
17.138 + } catch (InvocationTargetException ex) {
17.139 + throw ex.getTargetException();
17.140 + }
17.141 + }
17.142 +}
17.143 \ No newline at end of file
18.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
18.2 +++ b/boot/src/test/java/org/apidesign/html/boot/impl/JsClassLoaderTest.java Wed Jun 26 18:09:25 2013 +0200
18.3 @@ -0,0 +1,112 @@
18.4 +/**
18.5 + * HTML via Java(tm) Language Bindings
18.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
18.7 + *
18.8 + * This program is free software: you can redistribute it and/or modify
18.9 + * it under the terms of the GNU General Public License as published by
18.10 + * the Free Software Foundation, version 2 of the License.
18.11 + *
18.12 + * This program is distributed in the hope that it will be useful,
18.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
18.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18.15 + * GNU General Public License for more details. apidesign.org
18.16 + * designates this particular file as subject to the
18.17 + * "Classpath" exception as provided by apidesign.org
18.18 + * in the License file that accompanied this code.
18.19 + *
18.20 + * You should have received a copy of the GNU General Public License
18.21 + * along with this program. Look for COPYING file in the top folder.
18.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
18.23 + */
18.24 +package org.apidesign.html.boot.impl;
18.25 +
18.26 +import java.io.Reader;
18.27 +import org.apidesign.html.boot.spi.Fn;
18.28 +import java.net.URL;
18.29 +import java.net.URLClassLoader;
18.30 +import java.util.ArrayList;
18.31 +import java.util.Arrays;
18.32 +import java.util.Enumeration;
18.33 +import java.util.List;
18.34 +import javax.script.Invocable;
18.35 +import javax.script.ScriptEngine;
18.36 +import javax.script.ScriptEngineManager;
18.37 +import javax.script.ScriptException;
18.38 +import org.testng.annotations.AfterClass;
18.39 +import org.testng.annotations.BeforeClass;
18.40 +
18.41 +/**
18.42 + *
18.43 + * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
18.44 + */
18.45 +public class JsClassLoaderTest extends JsClassLoaderBase{
18.46 +
18.47 + @BeforeClass
18.48 + public static void setUpClass() throws Exception {
18.49 + ScriptEngineManager sem = new ScriptEngineManager();
18.50 + final ScriptEngine eng = sem.getEngineByMimeType("text/javascript");
18.51 +
18.52 + final URL my = JsClassLoaderTest.class.getProtectionDomain().getCodeSource().getLocation();
18.53 + ClassLoader parent = JsClassLoaderTest.class.getClassLoader().getParent();
18.54 + final URLClassLoader ul = new URLClassLoader(new URL[] { my }, parent);
18.55 + JsClassLoader loader = new JsClassLoader(parent) {
18.56 + @Override
18.57 + protected URL findResource(String name) {
18.58 + return ul.getResource(name);
18.59 + }
18.60 + @Override
18.61 + protected Fn defineFn(String code, String... names) {
18.62 + StringBuilder sb = new StringBuilder();
18.63 + sb.append("(function() {");
18.64 + sb.append("return function(");
18.65 + String sep = "";
18.66 + for (String n : names) {
18.67 + sb.append(sep);
18.68 + sb.append(n);
18.69 + sep = ", ";
18.70 + }
18.71 + sb.append(") {");
18.72 + sb.append(code);
18.73 + sb.append("};");
18.74 + sb.append("})()");
18.75 + try {
18.76 + final Object val = eng.eval(sb.toString());
18.77 + return new Fn() {
18.78 + @Override
18.79 + public Object invoke(Object thiz, Object... args) throws Exception {
18.80 + List<Object> all = new ArrayList<Object>(args.length + 1);
18.81 + all.add(thiz == null ? val : thiz);
18.82 + all.addAll(Arrays.asList(args));
18.83 + Invocable inv = (Invocable)eng;
18.84 + try {
18.85 + Object ret = inv.invokeMethod(val, "call", all.toArray());
18.86 + return ret == val ? null : ret;
18.87 + } catch (Exception ex) {
18.88 + throw ex;
18.89 + }
18.90 + }
18.91 + };
18.92 + } catch (ScriptException ex) {
18.93 + throw new LinkageError("Can't parse: " + sb, ex);
18.94 + }
18.95 + }
18.96 +
18.97 + @Override
18.98 + protected Enumeration<URL> findResources(String name) {
18.99 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
18.100 + }
18.101 +
18.102 + @Override
18.103 + protected void loadScript(Reader code) throws ScriptException {
18.104 + eng.eval(code);
18.105 + }
18.106 + };
18.107 +
18.108 + methodClass = loader.loadClass(JsMethods.class.getName());
18.109 + }
18.110 +
18.111 + @AfterClass
18.112 + public static void cleanUp() {
18.113 + methodClass = null;
18.114 + }
18.115 +}
18.116 \ No newline at end of file
19.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
19.2 +++ b/boot/src/test/java/org/apidesign/html/boot/impl/JsMethods.java Wed Jun 26 18:09:25 2013 +0200
19.3 @@ -0,0 +1,75 @@
19.4 +/**
19.5 + * HTML via Java(tm) Language Bindings
19.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
19.7 + *
19.8 + * This program is free software: you can redistribute it and/or modify
19.9 + * it under the terms of the GNU General Public License as published by
19.10 + * the Free Software Foundation, version 2 of the License.
19.11 + *
19.12 + * This program is distributed in the hope that it will be useful,
19.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
19.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19.15 + * GNU General Public License for more details. apidesign.org
19.16 + * designates this particular file as subject to the
19.17 + * "Classpath" exception as provided by apidesign.org
19.18 + * in the License file that accompanied this code.
19.19 + *
19.20 + * You should have received a copy of the GNU General Public License
19.21 + * along with this program. Look for COPYING file in the top folder.
19.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
19.23 + */
19.24 +package org.apidesign.html.boot.impl;
19.25 +
19.26 +import net.java.html.js.JavaScriptBody;
19.27 +import net.java.html.js.JavaScriptResource;
19.28 +
19.29 +
19.30 +/**
19.31 + *
19.32 + * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
19.33 + */
19.34 +@JavaScriptResource("jsmethods.js")
19.35 +public class JsMethods {
19.36 + @JavaScriptBody(args = {}, body = "return 42;")
19.37 + public static Object fortyTwo() {
19.38 + return -42;
19.39 + }
19.40 +
19.41 + @JavaScriptBody(args = {"x", "y" }, body = "return x + y;")
19.42 + public static native int plus(int x, int y);
19.43 +
19.44 + @JavaScriptBody(args = {"x"}, body = "return x;")
19.45 + public static native int plus(int x);
19.46 +
19.47 + @JavaScriptBody(args = {}, body = "return this;")
19.48 + public static native Object staticThis();
19.49 +
19.50 + @JavaScriptBody(args = {}, body = "return this;")
19.51 + public native Object getThis();
19.52 + @JavaScriptBody(args = {"x"}, body = "return x;")
19.53 + public native int plusInst(int x);
19.54 +
19.55 + @JavaScriptBody(args = {}, body = "return true;")
19.56 + public static boolean truth() {
19.57 + return false;
19.58 + }
19.59 +
19.60 + @JavaScriptBody(args = { "r" }, javacall=true, body = "r.@java.lang.Runnable::run()()")
19.61 + public static native void callback(Runnable r);
19.62 +
19.63 + @JavaScriptBody(args = { "at", "arr" }, javacall = true, body =
19.64 + "var a = 0;\n"
19.65 + + "for (var i = 0; i < arr.length; i++) {\n"
19.66 + + " a = at.@org.apidesign.html.boot.impl.Arithm::sumTwo(II)(a, arr[i]);\n"
19.67 + + "}\n"
19.68 + + "return a;"
19.69 + )
19.70 + private static native int sumArr(Arithm at, int... arr);
19.71 +
19.72 + public static int sumArr(int... arr) {
19.73 + return sumArr(new Arithm(), arr);
19.74 + }
19.75 +
19.76 + @JavaScriptBody(args = { "x", "y" }, body = "return mul(x, y);")
19.77 + public static native int useExternalMul(int x, int y);
19.78 +}
20.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
20.2 +++ b/boot/src/test/resources/org/apidesign/html/boot/impl/jsmethods.js Wed Jun 26 18:09:25 2013 +0200
20.3 @@ -0,0 +1,22 @@
20.4 +/*
20.5 + * HTML via Java(tm) Language Bindings
20.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
20.7 + *
20.8 + * This program is free software: you can redistribute it and/or modify
20.9 + * it under the terms of the GNU General Public License as published by
20.10 + * the Free Software Foundation, version 2 of the License.
20.11 + *
20.12 + * This program is distributed in the hope that it will be useful,
20.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
20.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20.15 + * GNU General Public License for more details. apidesign.org
20.16 + * designates this particular file as subject to the
20.17 + * "Classpath" exception as provided by apidesign.org
20.18 + * in the License file that accompanied this code.
20.19 + *
20.20 + * You should have received a copy of the GNU General Public License
20.21 + * along with this program. Look for COPYING file in the top folder.
20.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
20.23 + */
20.24 +
20.25 +function mul(x, y) { return x * y; }
21.1 --- a/context/pom.xml Wed May 29 19:36:31 2013 +0200
21.2 +++ b/context/pom.xml Wed Jun 26 18:09:25 2013 +0200
21.3 @@ -15,6 +15,18 @@
21.4 <properties>
21.5 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
21.6 </properties>
21.7 + <build>
21.8 + <plugins>
21.9 + <plugin>
21.10 + <groupId>org.apache.maven.plugins</groupId>
21.11 + <artifactId>maven-javadoc-plugin</artifactId>
21.12 + <configuration>
21.13 + <subpackages>net.java.html</subpackages>
21.14 + <skip>false</skip>
21.15 + </configuration>
21.16 + </plugin>
21.17 + </plugins>
21.18 + </build>
21.19 <dependencies>
21.20 </dependencies>
21.21 </project>
22.1 --- a/context/src/main/java/net/java/html/BrwsrCtx.java Wed May 29 19:36:31 2013 +0200
22.2 +++ b/context/src/main/java/net/java/html/BrwsrCtx.java Wed Jun 26 18:09:25 2013 +0200
22.3 @@ -25,9 +25,10 @@
22.4 import org.apidesign.html.context.impl.CtxImpl;
22.5 import org.apidesign.html.context.spi.Contexts;
22.6
22.7 -/** Represents context where the {@link Model} and other objects
22.8 +/** Represents context where the <code>net.java.html.json.Model</code>
22.9 + * and other objects
22.10 * operate in. The context is usually a particular HTML page in a browser.
22.11 - * The context is also associated with the actual HTML rendering technology
22.12 + * The context is also associated with the actual HTML technology
22.13 * in the HTML page - there is likely to be different context for
22.14 * <a href="http://knockoutjs.com">knockout.js</a> and different one
22.15 * for <a href="http://angularjs.org">angular</a>.
22.16 @@ -68,7 +69,17 @@
22.17 public static BrwsrCtx findDefault(Class<?> requestor) {
22.18 org.apidesign.html.context.spi.Contexts.Builder cb = Contexts.newBuilder();
22.19 boolean found = false;
22.20 - for (org.apidesign.html.context.spi.Contexts.Provider cp : ServiceLoader.load(org.apidesign.html.context.spi.Contexts.Provider.class)) {
22.21 +
22.22 + ClassLoader l;
22.23 + try {
22.24 + l = requestor.getClassLoader();
22.25 + } catch (SecurityException ex) {
22.26 + l = null;
22.27 + }
22.28 +
22.29 + for (org.apidesign.html.context.spi.Contexts.Provider cp : ServiceLoader.load(
22.30 + org.apidesign.html.context.spi.Contexts.Provider.class, l
22.31 + )) {
22.32 cp.fillContext(cb, requestor);
22.33 found = true;
22.34 }
23.1 --- a/json-tck/pom.xml Wed May 29 19:36:31 2013 +0200
23.2 +++ b/json-tck/pom.xml Wed Jun 26 18:09:25 2013 +0200
23.3 @@ -47,12 +47,6 @@
23.4 </exclusions>
23.5 </dependency>
23.6 <dependency>
23.7 - <groupId>org.apidesign.bck2brwsr</groupId>
23.8 - <artifactId>vmtest</artifactId>
23.9 - <version>${bck2brwsr.version}</version>
23.10 - <type>jar</type>
23.11 - </dependency>
23.12 - <dependency>
23.13 <groupId>org.netbeans.api</groupId>
23.14 <artifactId>org-openide-util</artifactId>
23.15 <scope>provided</scope>
24.1 --- a/json-tck/src/main/java/net/java/html/json/tests/ConvertTypesTest.java Wed May 29 19:36:31 2013 +0200
24.2 +++ b/json-tck/src/main/java/net/java/html/json/tests/ConvertTypesTest.java Wed Jun 26 18:09:25 2013 +0200
24.3 @@ -27,22 +27,24 @@
24.4 import java.util.Map;
24.5 import net.java.html.BrwsrCtx;
24.6 import net.java.html.json.Models;
24.7 -import org.apidesign.bck2brwsr.vmtest.BrwsrTest;
24.8 -import org.apidesign.bck2brwsr.vmtest.VMTest;
24.9 import org.apidesign.html.json.impl.JSON;
24.10 +import org.apidesign.html.json.tck.KOTest;
24.11
24.12 /**
24.13 *
24.14 * @author Jaroslav Tulach <jtulach@netbeans.org>
24.15 */
24.16 public final class ConvertTypesTest {
24.17 - private static InputStream createIS(boolean includeSex)
24.18 + private static InputStream createIS(boolean includeSex, boolean includeAddress)
24.19 throws UnsupportedEncodingException {
24.20 StringBuilder sb = new StringBuilder();
24.21 sb.append("{ \"firstName\" : \"son\",\n");
24.22 sb.append(" \"lastName\" : \"dj\" \n");
24.23 if (includeSex) {
24.24 - sb.append(", \"sex\" : \"MALE\" ");
24.25 + sb.append(", \"sex\" : \"MALE\" \n");
24.26 + }
24.27 + if (includeAddress) {
24.28 + sb.append(", \"address\" : { \"street\" : \"Schnirchova\" } \n");
24.29 }
24.30 sb.append("}\n");
24.31 return new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
24.32 @@ -55,24 +57,24 @@
24.33 if (includeSex) {
24.34 map.put("sex", "MALE");
24.35 }
24.36 - return Utils.createObject(map);
24.37 + return Utils.createObject(map, ConvertTypesTest.class);
24.38 }
24.39
24.40 - @BrwsrTest
24.41 + @KOTest
24.42 public void testConvertToPeople() throws Exception {
24.43 final Object o = createJSON(true);
24.44
24.45 - Person p = JSON.read(Utils.newContext(), Person.class, o);
24.46 + Person p = JSON.read(newContext(), Person.class, o);
24.47
24.48 assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
24.49 assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName();
24.50 assert Sex.MALE.equals(p.getSex()) : "Sex: " + p.getSex();
24.51 }
24.52
24.53 - @BrwsrTest
24.54 + @KOTest
24.55 public void parseConvertToPeople() throws Exception {
24.56 - final BrwsrCtx c = Utils.newContext();
24.57 - final InputStream o = createIS(true);
24.58 + final BrwsrCtx c = newContext();
24.59 + final InputStream o = createIS(true, false);
24.60
24.61 Person p = Models.parse(c, Person.class, o);
24.62
24.63 @@ -80,22 +82,36 @@
24.64 assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName();
24.65 assert Sex.MALE.equals(p.getSex()) : "Sex: " + p.getSex();
24.66 }
24.67 +
24.68 + @KOTest
24.69 + public void parseConvertToPeopleWithAddress() throws Exception {
24.70 + final BrwsrCtx c = newContext();
24.71 + final InputStream o = createIS(true, true);
24.72 +
24.73 + Person p = Models.parse(c, Person.class, o);
24.74 +
24.75 + assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
24.76 + assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName();
24.77 + assert Sex.MALE.equals(p.getSex()) : "Sex: " + p.getSex();
24.78 + assert p.getAddress() != null : "Some address provided";
24.79 + assert p.getAddress().getStreet().equals("Schnirchova") : "Is Schnirchova: " + p.getAddress();
24.80 + }
24.81
24.82 - @BrwsrTest
24.83 + @KOTest
24.84 public void testConvertToPeopleWithoutSex() throws Exception {
24.85 final Object o = createJSON(false);
24.86
24.87 - Person p = JSON.read(Utils.newContext(), Person.class, o);
24.88 + Person p = JSON.read(newContext(), Person.class, o);
24.89
24.90 assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
24.91 assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName();
24.92 assert p.getSex() == null : "No sex: " + p.getSex();
24.93 }
24.94
24.95 - @BrwsrTest
24.96 + @KOTest
24.97 public void parseConvertToPeopleWithoutSex() throws Exception {
24.98 - final BrwsrCtx c = Utils.newContext();
24.99 - final InputStream o = createIS(false);
24.100 + final BrwsrCtx c = newContext();
24.101 + final InputStream o = createIS(false, false);
24.102 Person p = Models.parse(c, Person.class, o);
24.103
24.104 assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
24.105 @@ -103,7 +119,7 @@
24.106 assert p.getSex() == null : "No sex: " + p.getSex();
24.107 }
24.108
24.109 - static Object[] create() {
24.110 - return VMTest.create(ConvertTypesTest.class);
24.111 + private static BrwsrCtx newContext() {
24.112 + return Utils.newContext(ConvertTypesTest.class);
24.113 }
24.114 }
24.115 \ No newline at end of file
25.1 --- a/json-tck/src/main/java/net/java/html/json/tests/JSONTest.java Wed May 29 19:36:31 2013 +0200
25.2 +++ b/json-tck/src/main/java/net/java/html/json/tests/JSONTest.java Wed Jun 26 18:09:25 2013 +0200
25.3 @@ -26,10 +26,8 @@
25.4 import net.java.html.json.Models;
25.5 import net.java.html.json.OnReceive;
25.6 import net.java.html.json.Property;
25.7 -import org.apidesign.bck2brwsr.vmtest.BrwsrTest;
25.8 -import org.apidesign.bck2brwsr.vmtest.Http;
25.9 -import org.apidesign.bck2brwsr.vmtest.VMTest;
25.10 import org.apidesign.html.json.impl.JSON;
25.11 +import org.apidesign.html.json.tck.KOTest;
25.12
25.13 /** Need to verify that models produce reasonable JSON objects.
25.14 *
25.15 @@ -44,9 +42,10 @@
25.16 public final class JSONTest {
25.17 private JSONik js;
25.18 private Integer orig;
25.19 + private String url;
25.20
25.21 - @BrwsrTest public void toJSONInABrowser() throws Throwable {
25.22 - Person p = Models.bind(new Person(), Utils.newContext());
25.23 + @KOTest public void toJSONInABrowser() throws Throwable {
25.24 + Person p = Models.bind(new Person(), newContext());
25.25 p.setSex(Sex.MALE);
25.26 p.setFirstName("Jarda");
25.27 p.setLastName("Tulach");
25.28 @@ -58,30 +57,30 @@
25.29 throw new IllegalStateException("Can't parse " + p).initCause(ex);
25.30 }
25.31
25.32 - Person p2 = JSON.read(Utils.newContext(), Person.class, json);
25.33 + Person p2 = JSON.read(newContext(), Person.class, json);
25.34
25.35 assert p2.getFirstName().equals(p.getFirstName()) :
25.36 "Should be the same: " + p.getFirstName() + " != " + p2.getFirstName();
25.37 }
25.38
25.39 - @OnReceive(url="/{url}")
25.40 + @OnReceive(url="{url}")
25.41 static void fetch(Person p, JSONik model) {
25.42 model.setFetched(p);
25.43 }
25.44
25.45 - @OnReceive(url="/{url}")
25.46 + @OnReceive(url="{url}")
25.47 static void fetchArray(Person[] p, JSONik model) {
25.48 model.setFetchedCount(p.length);
25.49 model.setFetched(p[0]);
25.50 }
25.51
25.52 - @OnReceive(url="/{url}")
25.53 + @OnReceive(url="{url}")
25.54 static void fetchPeople(People p, JSONik model) {
25.55 model.setFetchedCount(p.getInfo().size());
25.56 model.setFetched(p.getInfo().get(0));
25.57 }
25.58
25.59 - @OnReceive(url="/{url}")
25.60 + @OnReceive(url="{url}")
25.61 static void fetchPeopleAge(People p, JSONik model) {
25.62 int sum = 0;
25.63 for (int a : p.getAge()) {
25.64 @@ -90,17 +89,16 @@
25.65 model.setFetchedCount(sum);
25.66 }
25.67
25.68 - @Http(@Http.Resource(
25.69 - content = "{'firstName': 'Sitar', 'sex': 'MALE'}",
25.70 - path="/person.json",
25.71 - mimeType = "application/json"
25.72 - ))
25.73 - @BrwsrTest public void loadAndParseJSON() throws InterruptedException {
25.74 + @KOTest public void loadAndParseJSON() throws InterruptedException {
25.75 if (js == null) {
25.76 - js = Models.bind(new JSONik(), Utils.newContext());
25.77 + url = Utils.prepareURL(
25.78 + JSONTest.class, "{'firstName': 'Sitar', 'sex': 'MALE'}",
25.79 + "application/json"
25.80 + );
25.81 + js = Models.bind(new JSONik(), newContext());
25.82 js.applyBindings();
25.83
25.84 - js.fetch("person.json");
25.85 + js.fetch(url);
25.86 }
25.87
25.88 Person p = js.getFetched();
25.89 @@ -112,27 +110,25 @@
25.90 assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex();
25.91 }
25.92
25.93 - @OnReceive(url="/{url}?callme={me}", jsonp = "me")
25.94 + @OnReceive(url="{url}?callme={me}", jsonp = "me")
25.95 static void fetchViaJSONP(Person p, JSONik model) {
25.96 model.setFetched(p);
25.97 }
25.98
25.99 - @Http(@Http.Resource(
25.100 - content = "$0({'firstName': 'Mitar', 'sex': 'MALE'})",
25.101 - path="/person.json",
25.102 - mimeType = "application/javascript",
25.103 - parameters = { "callme" }
25.104 - ))
25.105 - @BrwsrTest public void loadAndParseJSONP() throws InterruptedException, Exception {
25.106 -
25.107 + @KOTest public void loadAndParseJSONP() throws InterruptedException, Exception {
25.108 if (js == null) {
25.109 + url = Utils.prepareURL(
25.110 + JSONTest.class, "$0({'firstName': 'Mitar', 'sex': 'MALE'})",
25.111 + "application/javascript",
25.112 + "callme"
25.113 + );
25.114 orig = scriptElements();
25.115 assert orig > 0 : "There should be some scripts on the page";
25.116
25.117 - js = Models.bind(new JSONik(), Utils.newContext());
25.118 + js = Models.bind(new JSONik(), newContext());
25.119 js.applyBindings();
25.120
25.121 - js.fetchViaJSONP("person.json");
25.122 + js.fetchViaJSONP(url);
25.123 }
25.124
25.125 Person p = js.getFetched();
25.126 @@ -155,23 +151,23 @@
25.127 model.setFetchedCount(1);
25.128 model.setFetchedResponse(reply);
25.129 }
25.130 - @Http(@Http.Resource(
25.131 - content = "$0\n$1",
25.132 - path="/person.json",
25.133 - mimeType = "text/plain",
25.134 - parameters = { "http.method", "http.requestBody" }
25.135 - ))
25.136 - @BrwsrTest public void putPeopleUsesRightMethod() throws InterruptedException, Exception {
25.137 +
25.138 + @KOTest public void putPeopleUsesRightMethod() throws InterruptedException, Exception {
25.139 if (js == null) {
25.140 + url = Utils.prepareURL(
25.141 + JSONTest.class, "$0\n$1",
25.142 + "text/plain",
25.143 + "http.method", "http.requestBody"
25.144 + );
25.145 orig = scriptElements();
25.146 assert orig > 0 : "There should be some scripts on the page";
25.147
25.148 - js = Models.bind(new JSONik(), Utils.newContext());
25.149 + js = Models.bind(new JSONik(), newContext());
25.150 js.applyBindings();
25.151
25.152 Person p = Models.bind(new Person(), BrwsrCtx.EMPTY);
25.153 p.setFirstName("Jarda");
25.154 - js.putPerson("person.json", p);
25.155 + js.putPerson(url, p);
25.156 }
25.157
25.158 int cnt = js.getFetchedCount();
25.159 @@ -194,24 +190,28 @@
25.160 }
25.161
25.162 private static int scriptElements() throws Exception {
25.163 - return ((Number)Utils.executeScript("return window.document.getElementsByTagName('script').length;")).intValue();
25.164 + return ((Number)Utils.executeScript(
25.165 + JSONTest.class,
25.166 + "return window.document.getElementsByTagName('script').length;")).intValue();
25.167 }
25.168
25.169 private static Object parseJSON(String s) throws Exception {
25.170 - return Utils.executeScript("return window.JSON.parse(arguments[0]);", s);
25.171 + return Utils.executeScript(
25.172 + JSONTest.class,
25.173 + "return window.JSON.parse(arguments[0]);", s);
25.174 }
25.175
25.176 - @Http(@Http.Resource(
25.177 - content = "{'firstName': 'Sitar', 'sex': 'MALE'}",
25.178 - path="/person.json",
25.179 - mimeType = "application/json"
25.180 - ))
25.181 - @BrwsrTest public void loadAndParseJSONSentToArray() throws InterruptedException {
25.182 + @KOTest public void loadAndParseJSONSentToArray() throws InterruptedException {
25.183 if (js == null) {
25.184 - js = Models.bind(new JSONik(), Utils.newContext());
25.185 + url = Utils.prepareURL(
25.186 + JSONTest.class, "{'firstName': 'Sitar', 'sex': 'MALE'}",
25.187 + "application/json"
25.188 + );
25.189 +
25.190 + js = Models.bind(new JSONik(), newContext());
25.191 js.applyBindings();
25.192
25.193 - js.fetchArray("person.json");
25.194 + js.fetchArray(url);
25.195 }
25.196
25.197 Person p = js.getFetched();
25.198 @@ -223,17 +223,16 @@
25.199 assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex();
25.200 }
25.201
25.202 - @Http(@Http.Resource(
25.203 - content = "[{'firstName': 'Gitar', 'sex': 'FEMALE'}]",
25.204 - path="/person.json",
25.205 - mimeType = "application/json"
25.206 - ))
25.207 - @BrwsrTest public void loadAndParseJSONArraySingle() throws InterruptedException {
25.208 + @KOTest public void loadAndParseJSONArraySingle() throws InterruptedException {
25.209 if (js == null) {
25.210 - js = Models.bind(new JSONik(), Utils.newContext());
25.211 + url = Utils.prepareURL(
25.212 + JSONTest.class, "[{'firstName': 'Gitar', 'sex': 'FEMALE'}]",
25.213 + "application/json"
25.214 + );
25.215 + js = Models.bind(new JSONik(), newContext());
25.216 js.applyBindings();
25.217
25.218 - js.fetch("person.json");
25.219 + js.fetch(url);
25.220 }
25.221
25.222 Person p = js.getFetched();
25.223 @@ -245,17 +244,16 @@
25.224 assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex();
25.225 }
25.226
25.227 - @Http(@Http.Resource(
25.228 - content = "{'info':[{'firstName': 'Gitar', 'sex': 'FEMALE'}]}",
25.229 - path="/people.json",
25.230 - mimeType = "application/json"
25.231 - ))
25.232 - @BrwsrTest public void loadAndParseArrayInPeople() throws InterruptedException {
25.233 + @KOTest public void loadAndParseArrayInPeople() throws InterruptedException {
25.234 if (js == null) {
25.235 - js = Models.bind(new JSONik(), Utils.newContext());
25.236 + url = Utils.prepareURL(
25.237 + JSONTest.class, "{'info':[{'firstName': 'Gitar', 'sex': 'FEMALE'}]}",
25.238 + "application/json"
25.239 + );
25.240 + js = Models.bind(new JSONik(), newContext());
25.241 js.applyBindings();
25.242
25.243 - js.fetchPeople("people.json");
25.244 + js.fetchPeople(url);
25.245 }
25.246
25.247 if (0 == js.getFetchedCount()) {
25.248 @@ -271,17 +269,16 @@
25.249 assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex();
25.250 }
25.251
25.252 - @Http(@Http.Resource(
25.253 - content = "{'age':[1, 2, 3]}",
25.254 - path="/people.json",
25.255 - mimeType = "application/json"
25.256 - ))
25.257 - @BrwsrTest public void loadAndParseArrayOfIntegers() throws InterruptedException {
25.258 + @KOTest public void loadAndParseArrayOfIntegers() throws InterruptedException {
25.259 if (js == null) {
25.260 - js = Models.bind(new JSONik(), Utils.newContext());
25.261 + url = Utils.prepareURL(
25.262 + JSONTest.class, "{'age':[1, 2, 3]}",
25.263 + "application/json"
25.264 + );
25.265 + js = Models.bind(new JSONik(), newContext());
25.266 js.applyBindings();
25.267
25.268 - js.fetchPeopleAge("people.json");
25.269 + js.fetchPeopleAge(url);
25.270 }
25.271
25.272 if (0 == js.getFetchedCount()) {
25.273 @@ -291,24 +288,22 @@
25.274 assert js.getFetchedCount() == 6 : "1 + 2 + 3 is " + js.getFetchedCount();
25.275 }
25.276
25.277 - @OnReceive(url="/{url}")
25.278 + @OnReceive(url="{url}")
25.279 static void fetchPeopleSex(People p, JSONik model) {
25.280 model.setFetchedCount(1);
25.281 model.getFetchedSex().addAll(p.getSex());
25.282 }
25.283
25.284 -
25.285 - @Http(@Http.Resource(
25.286 - content = "{'sex':['FEMALE', 'MALE', 'MALE']}",
25.287 - path="/people.json",
25.288 - mimeType = "application/json"
25.289 - ))
25.290 - @BrwsrTest public void loadAndParseArrayOfEnums() throws InterruptedException {
25.291 + @KOTest public void loadAndParseArrayOfEnums() throws InterruptedException {
25.292 if (js == null) {
25.293 - js = Models.bind(new JSONik(), Utils.newContext());
25.294 + url = Utils.prepareURL(
25.295 + JSONTest.class, "{'sex':['FEMALE', 'MALE', 'MALE']}",
25.296 + "application/json"
25.297 + );
25.298 + js = Models.bind(new JSONik(), newContext());
25.299 js.applyBindings();
25.300
25.301 - js.fetchPeopleSex("people.json");
25.302 + js.fetchPeopleSex(url);
25.303 }
25.304
25.305 if (0 == js.getFetchedCount()) {
25.306 @@ -323,18 +318,17 @@
25.307 assert js.getFetchedSex().get(2) == Sex.MALE : "male 3rd " + js.getFetchedSex();
25.308 }
25.309
25.310 - @Http(@Http.Resource(
25.311 - content = "[{'firstName': 'Gitar', 'sex': 'FEMALE'},"
25.312 - + "{'firstName': 'Peter', 'sex': 'MALE'}"
25.313 - + "]",
25.314 - path="/person.json",
25.315 - mimeType = "application/json"
25.316 - ))
25.317 - @BrwsrTest public void loadAndParseJSONArray() throws InterruptedException {
25.318 + @KOTest public void loadAndParseJSONArray() throws InterruptedException {
25.319 if (js == null) {
25.320 - js = Models.bind(new JSONik(), Utils.newContext());
25.321 + url = Utils.prepareURL(
25.322 + JSONTest.class, "[{'firstName': 'Gitar', 'sex': 'FEMALE'},"
25.323 + + "{'firstName': 'Peter', 'sex': 'MALE'}"
25.324 + + "]",
25.325 + "application/json"
25.326 + );
25.327 + js = Models.bind(new JSONik(), newContext());
25.328 js.applyBindings();
25.329 - js.fetchArray("person.json");
25.330 + js.fetchArray(url);
25.331 }
25.332
25.333
25.334 @@ -356,17 +350,17 @@
25.335 static class NandV {
25.336 }
25.337
25.338 - @BrwsrTest public void parseNullNumber() throws Exception {
25.339 + @KOTest public void parseNullNumber() throws Exception {
25.340 String txt = "{ \"name\":\"M\" }";
25.341 ByteArrayInputStream is = new ByteArrayInputStream(txt.getBytes("UTF-8"));
25.342 - NameAndValue v = Models.parse(Utils.newContext(), NameAndValue.class, is);
25.343 + NameAndValue v = Models.parse(newContext(), NameAndValue.class, is);
25.344 assert "M".equals(v.getName()) : "Name is 'M': " + v.getName();
25.345 assert 0 == v.getValue() : "Value is empty: " + v.getValue();
25.346 assert 0 == v.getSmall() : "Small value is empty: " + v.getSmall();
25.347 }
25.348 -
25.349 - static Object[] create() {
25.350 - return VMTest.create(JSONTest.class);
25.351 +
25.352 + private static BrwsrCtx newContext() {
25.353 + return Utils.newContext(JSONTest.class);
25.354 }
25.355
25.356 }
26.1 --- a/json-tck/src/main/java/net/java/html/json/tests/KnockoutTest.java Wed May 29 19:36:31 2013 +0200
26.2 +++ b/json-tck/src/main/java/net/java/html/json/tests/KnockoutTest.java Wed Jun 26 18:09:25 2013 +0200
26.3 @@ -21,14 +21,13 @@
26.4 package net.java.html.json.tests;
26.5
26.6 import java.util.List;
26.7 +import net.java.html.BrwsrCtx;
26.8 import net.java.html.json.ComputedProperty;
26.9 import net.java.html.json.Function;
26.10 import net.java.html.json.Model;
26.11 import net.java.html.json.Models;
26.12 import net.java.html.json.Property;
26.13 -import org.apidesign.bck2brwsr.vmtest.BrwsrTest;
26.14 -import org.apidesign.bck2brwsr.vmtest.HtmlFragment;
26.15 -import org.apidesign.bck2brwsr.vmtest.VMTest;
26.16 +import org.apidesign.html.json.tck.KOTest;
26.17
26.18 /**
26.19 *
26.20 @@ -43,23 +42,28 @@
26.21 })
26.22 public final class KnockoutTest {
26.23
26.24 - @HtmlFragment(
26.25 - "<h1 data-bind=\"text: helloMessage\">Loading Bck2Brwsr's Hello World...</h1>\n" +
26.26 - "Your name: <input id='input' data-bind=\"value: name\"></input>\n" +
26.27 - "<button id=\"hello\">Say Hello!</button>\n"
26.28 - )
26.29 - @BrwsrTest public void modifyValueAssertChangeInModel() throws Exception {
26.30 - KnockoutModel m = Models.bind(new KnockoutModel(), Utils.newContext());
26.31 - m.setName("Kukuc");
26.32 - m.applyBindings();
26.33 -
26.34 - String v = getSetInput(null);
26.35 - assert "Kukuc".equals(v) : "Value is really kukuc: " + v;
26.36 -
26.37 - getSetInput("Jardo");
26.38 - triggerEvent("input", "change");
26.39 -
26.40 - assert "Jardo".equals(m.getName()) : "Name property updated: " + m.getName();
26.41 + @KOTest public void modifyValueAssertChangeInModel() throws Exception {
26.42 + Object exp = Utils.exposeHTML(KnockoutTest.class,
26.43 + "<h1 data-bind=\"text: helloMessage\">Loading Bck2Brwsr's Hello World...</h1>\n" +
26.44 + "Your name: <input id='input' data-bind=\"value: name\"></input>\n" +
26.45 + "<button id=\"hello\">Say Hello!</button>\n"
26.46 + );
26.47 + try {
26.48 +
26.49 + KnockoutModel m = Models.bind(new KnockoutModel(), newContext());
26.50 + m.setName("Kukuc");
26.51 + m.applyBindings();
26.52 +
26.53 + String v = getSetInput(null);
26.54 + assert "Kukuc".equals(v) : "Value is really kukuc: " + v;
26.55 +
26.56 + getSetInput("Jardo");
26.57 + triggerEvent("input", "change");
26.58 +
26.59 + assert "Jardo".equals(m.getName()) : "Name property updated: " + m.getName();
26.60 + } finally {
26.61 + Utils.exposeHTML(KnockoutTest.class, "");
26.62 + }
26.63 }
26.64
26.65 private static String getSetInput(String value) throws Exception {
26.66 @@ -67,113 +71,133 @@
26.67 + "var n = window.document.getElementById('input'); \n "
26.68 + "if (value != null) n['value'] = value; \n "
26.69 + "return n['value'];";
26.70 - return (String)Utils.executeScript(s, value);
26.71 + return (String)Utils.executeScript(
26.72 + KnockoutTest.class,
26.73 + s, value
26.74 + );
26.75 }
26.76
26.77 public static void triggerEvent(String id, String ev) throws Exception {
26.78 Utils.executeScript(
26.79 + KnockoutTest.class,
26.80 "ko.utils.triggerEvent(window.document.getElementById(arguments[0]), arguments[1]);",
26.81 id, ev
26.82 );
26.83 }
26.84
26.85 - @HtmlFragment(
26.86 - "<ul id='ul' data-bind='foreach: results'>\n"
26.87 - + " <li data-bind='text: $data, click: $root.call'/>\n"
26.88 - + "</ul>\n"
26.89 - )
26.90 - @BrwsrTest public void displayContentOfArray() throws Exception {
26.91 - KnockoutModel m = Models.bind(new KnockoutModel(), Utils.newContext());
26.92 - m.getResults().add("Ahoj");
26.93 - m.applyBindings();
26.94 -
26.95 - int cnt = countChildren("ul");
26.96 - assert cnt == 1 : "One child, but was " + cnt;
26.97 -
26.98 - m.getResults().add("Hi");
26.99 + @KOTest public void displayContentOfArray() throws Exception {
26.100 + Object exp = Utils.exposeHTML(KnockoutTest.class,
26.101 + "<ul id='ul' data-bind='foreach: results'>\n"
26.102 + + " <li data-bind='text: $data, click: $root.call'/>\n"
26.103 + + "</ul>\n"
26.104 + );
26.105 + try {
26.106 + KnockoutModel m = Models.bind(new KnockoutModel(), newContext());
26.107 + m.getResults().add("Ahoj");
26.108 + m.applyBindings();
26.109
26.110 - cnt = countChildren("ul");
26.111 - assert cnt == 2 : "Two children now, but was " + cnt;
26.112 -
26.113 - triggerChildClick("ul", 1);
26.114 -
26.115 - assert 1 == m.getCallbackCount() : "One callback " + m.getCallbackCount();
26.116 - assert "Hi".equals(m.getName()) : "We got callback from 2nd child " + m.getName();
26.117 + int cnt = countChildren("ul");
26.118 + assert cnt == 1 : "One child, but was " + cnt;
26.119 +
26.120 + m.getResults().add("Hi");
26.121 +
26.122 + cnt = countChildren("ul");
26.123 + assert cnt == 2 : "Two children now, but was " + cnt;
26.124 +
26.125 + triggerChildClick("ul", 1);
26.126 +
26.127 + assert 1 == m.getCallbackCount() : "One callback " + m.getCallbackCount();
26.128 + assert "Hi".equals(m.getName()) : "We got callback from 2nd child " + m.getName();
26.129 + } finally {
26.130 + Utils.exposeHTML(KnockoutTest.class, "");
26.131 + }
26.132 }
26.133
26.134 - @HtmlFragment(
26.135 - "<input type='checkbox' id='b' data-bind='checked: enabled'></input>\n"
26.136 - )
26.137 - @BrwsrTest public void checkBoxToBooleanBinding() throws Exception {
26.138 - KnockoutModel m = Models.bind(new KnockoutModel(), Utils.newContext());
26.139 - m.applyBindings();
26.140 -
26.141 - assert !m.isEnabled() : "Is disabled";
26.142 + @KOTest public void checkBoxToBooleanBinding() throws Exception {
26.143 + Object exp = Utils.exposeHTML(KnockoutTest.class,
26.144 + "<input type='checkbox' id='b' data-bind='checked: enabled'></input>\n"
26.145 + );
26.146 + try {
26.147 + KnockoutModel m = Models.bind(new KnockoutModel(), newContext());
26.148 + m.applyBindings();
26.149
26.150 - triggerClick("b");
26.151 -
26.152 - assert m.isEnabled() : "Now the model is enabled";
26.153 + assert !m.isEnabled() : "Is disabled";
26.154 +
26.155 + triggerClick("b");
26.156 +
26.157 + assert m.isEnabled() : "Now the model is enabled";
26.158 + } finally {
26.159 + Utils.exposeHTML(KnockoutTest.class, "");
26.160 + }
26.161 }
26.162
26.163
26.164
26.165 - @HtmlFragment(
26.166 - "<ul id='ul' data-bind='foreach: cmpResults'>\n"
26.167 - + " <li><b data-bind='text: $data'></b></li>\n"
26.168 - + "</ul>\n"
26.169 - )
26.170 - @BrwsrTest public void displayContentOfDerivedArray() throws Exception {
26.171 - KnockoutModel m = Models.bind(new KnockoutModel(), Utils.newContext());
26.172 - m.getResults().add("Ahoj");
26.173 - m.applyBindings();
26.174 -
26.175 - int cnt = countChildren("ul");
26.176 - assert cnt == 1 : "One child, but was " + cnt;
26.177 -
26.178 - m.getResults().add("hello");
26.179 + @KOTest public void displayContentOfDerivedArray() throws Exception {
26.180 + Object exp = Utils.exposeHTML(KnockoutTest.class,
26.181 + "<ul id='ul' data-bind='foreach: cmpResults'>\n"
26.182 + + " <li><b data-bind='text: $data'></b></li>\n"
26.183 + + "</ul>\n"
26.184 + );
26.185 + try {
26.186 + KnockoutModel m = Models.bind(new KnockoutModel(), newContext());
26.187 + m.getResults().add("Ahoj");
26.188 + m.applyBindings();
26.189
26.190 - cnt = countChildren("ul");
26.191 - assert cnt == 2 : "Two children now, but was " + cnt;
26.192 + int cnt = countChildren("ul");
26.193 + assert cnt == 1 : "One child, but was " + cnt;
26.194 +
26.195 + m.getResults().add("hello");
26.196 +
26.197 + cnt = countChildren("ul");
26.198 + assert cnt == 2 : "Two children now, but was " + cnt;
26.199 + } finally {
26.200 + Utils.exposeHTML(KnockoutTest.class, "");
26.201 + }
26.202 }
26.203
26.204 - @HtmlFragment(
26.205 - "<ul id='ul' data-bind='foreach: people'>\n"
26.206 - + " <li data-bind='text: $data.firstName, click: $root.removePerson'></li>\n"
26.207 - + "</ul>\n"
26.208 - )
26.209 - @BrwsrTest public void displayContentOfArrayOfPeople() throws Exception {
26.210 - KnockoutModel m = Models.bind(new KnockoutModel(), Utils.newContext());
26.211 -
26.212 - final Person first = Models.bind(new Person(), Utils.newContext());
26.213 - first.setFirstName("first");
26.214 - m.getPeople().add(first);
26.215 -
26.216 - m.applyBindings();
26.217 -
26.218 - int cnt = countChildren("ul");
26.219 - assert cnt == 1 : "One child, but was " + cnt;
26.220 -
26.221 - final Person second = Models.bind(new Person(), Utils.newContext());
26.222 - second.setFirstName("second");
26.223 - m.getPeople().add(second);
26.224 + @KOTest public void displayContentOfArrayOfPeople() throws Exception {
26.225 + Object exp = Utils.exposeHTML(KnockoutTest.class,
26.226 + "<ul id='ul' data-bind='foreach: people'>\n"
26.227 + + " <li data-bind='text: $data.firstName, click: $root.removePerson'></li>\n"
26.228 + + "</ul>\n"
26.229 + );
26.230 + try {
26.231 + KnockoutModel m = Models.bind(new KnockoutModel(), newContext());
26.232
26.233 - cnt = countChildren("ul");
26.234 - assert cnt == 2 : "Two children now, but was " + cnt;
26.235 + final Person first = Models.bind(new Person(), newContext());
26.236 + first.setFirstName("first");
26.237 + m.getPeople().add(first);
26.238
26.239 - triggerChildClick("ul", 1);
26.240 -
26.241 - assert 1 == m.getCallbackCount() : "One callback " + m.getCallbackCount();
26.242 + m.applyBindings();
26.243
26.244 - cnt = countChildren("ul");
26.245 - assert cnt == 1 : "Again one child, but was " + cnt;
26.246 -
26.247 - String txt = childText("ul", 0);
26.248 - assert "first".equals(txt) : "Expecting 'first': " + txt;
26.249 -
26.250 - first.setFirstName("changed");
26.251 -
26.252 - txt = childText("ul", 0);
26.253 - assert "changed".equals(txt) : "Expecting 'changed': " + txt;
26.254 + int cnt = countChildren("ul");
26.255 + assert cnt == 1 : "One child, but was " + cnt;
26.256 +
26.257 + final Person second = Models.bind(new Person(), newContext());
26.258 + second.setFirstName("second");
26.259 + m.getPeople().add(second);
26.260 +
26.261 + cnt = countChildren("ul");
26.262 + assert cnt == 2 : "Two children now, but was " + cnt;
26.263 +
26.264 + triggerChildClick("ul", 1);
26.265 +
26.266 + assert 1 == m.getCallbackCount() : "One callback " + m.getCallbackCount();
26.267 +
26.268 + cnt = countChildren("ul");
26.269 + assert cnt == 1 : "Again one child, but was " + cnt;
26.270 +
26.271 + String txt = childText("ul", 0);
26.272 + assert "first".equals(txt) : "Expecting 'first': " + txt;
26.273 +
26.274 + first.setFirstName("changed");
26.275 +
26.276 + txt = childText("ul", 0);
26.277 + assert "changed".equals(txt) : "Expecting 'changed': " + txt;
26.278 + } finally {
26.279 + Utils.exposeHTML(KnockoutTest.class, "");
26.280 + }
26.281 }
26.282
26.283 @ComputedProperty
26.284 @@ -181,28 +205,36 @@
26.285 return people.isEmpty() ? null : people.get(0);
26.286 }
26.287
26.288 - @HtmlFragment(
26.289 - "<p id='ul' data-bind='with: firstPerson'>\n"
26.290 - + " <span data-bind='text: firstName, click: changeSex'></span>\n"
26.291 - + "</p>\n"
26.292 - )
26.293 - @BrwsrTest public void accessFirstPersonWithOnFunction() throws Exception {
26.294 - trasfertToFemale();
26.295 + @KOTest public void accessFirstPersonWithOnFunction() throws Exception {
26.296 + Object exp = Utils.exposeHTML(KnockoutTest.class,
26.297 + "<p id='ul' data-bind='with: firstPerson'>\n"
26.298 + + " <span data-bind='text: firstName, click: changeSex'></span>\n"
26.299 + + "</p>\n"
26.300 + );
26.301 + try {
26.302 + trasfertToFemale();
26.303 + } finally {
26.304 + Utils.exposeHTML(KnockoutTest.class, "");
26.305 + }
26.306 }
26.307
26.308 - @HtmlFragment(
26.309 - "<ul id='ul' data-bind='foreach: people'>\n"
26.310 - + " <li data-bind='text: $data.firstName, click: changeSex'></li>\n"
26.311 - + "</ul>\n"
26.312 - )
26.313 - @BrwsrTest public void onPersonFunction() throws Exception {
26.314 - trasfertToFemale();
26.315 + @KOTest public void onPersonFunction() throws Exception {
26.316 + Object exp = Utils.exposeHTML(KnockoutTest.class,
26.317 + "<ul id='ul' data-bind='foreach: people'>\n"
26.318 + + " <li data-bind='text: $data.firstName, click: changeSex'></li>\n"
26.319 + + "</ul>\n"
26.320 + );
26.321 + try {
26.322 + trasfertToFemale();
26.323 + } finally {
26.324 + Utils.exposeHTML(KnockoutTest.class, "");
26.325 + }
26.326 }
26.327
26.328 private void trasfertToFemale() throws Exception {
26.329 - KnockoutModel m = Models.bind(new KnockoutModel(), Utils.newContext());
26.330 + KnockoutModel m = Models.bind(new KnockoutModel(), newContext());
26.331
26.332 - final Person first = Models.bind(new Person(), Utils.newContext());
26.333 + final Person first = Models.bind(new Person(), newContext());
26.334 first.setFirstName("first");
26.335 first.setSex(Sex.MALE);
26.336 m.getPeople().add(first);
26.337 @@ -242,12 +274,9 @@
26.338 return results;
26.339 }
26.340
26.341 - static Object[] create() {
26.342 - return VMTest.create(KnockoutTest.class);
26.343 - }
26.344 -
26.345 private static int countChildren(String id) throws Exception {
26.346 return ((Number)Utils.executeScript(
26.347 + KnockoutTest.class,
26.348 "var e = window.document.getElementById(arguments[0]);\n "
26.349 + "if (typeof e === 'undefined') return -2;\n "
26.350 + "return e.children.length;",
26.351 @@ -261,7 +290,9 @@
26.352 + "var ev = window.document.createEvent('MouseEvents');\n "
26.353 + "ev.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n "
26.354 + "e.dispatchEvent(ev);\n ";
26.355 - Utils.executeScript(s, id);
26.356 + Utils.executeScript(
26.357 + KnockoutTest.class,
26.358 + s, id);
26.359 }
26.360 private static void triggerChildClick(String id, int pos) throws Exception {
26.361 String s = "var id = arguments[0]; var pos = arguments[1];"
26.362 @@ -269,7 +300,9 @@
26.363 + "var ev = window.document.createEvent('MouseEvents');\n "
26.364 + "ev.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n "
26.365 + "e.children[pos].dispatchEvent(ev);\n ";
26.366 - Utils.executeScript(s, id, pos);
26.367 + Utils.executeScript(
26.368 + KnockoutTest.class,
26.369 + s, id, pos);
26.370 }
26.371
26.372 private static String childText(String id, int pos) throws Exception {
26.373 @@ -277,6 +310,12 @@
26.374 + "var e = window.document.getElementById(id);\n "
26.375 + "var t = e.children[pos].innerHTML;\n "
26.376 + "return t ? t : null;";
26.377 - return (String)Utils.executeScript(s, id, pos);
26.378 + return (String)Utils.executeScript(
26.379 + KnockoutTest.class,
26.380 + s, id, pos);
26.381 + }
26.382 +
26.383 + private static BrwsrCtx newContext() {
26.384 + return Utils.newContext(KnockoutTest.class);
26.385 }
26.386 }
27.1 --- a/json-tck/src/main/java/net/java/html/json/tests/PersonImpl.java Wed May 29 19:36:31 2013 +0200
27.2 +++ b/json-tck/src/main/java/net/java/html/json/tests/PersonImpl.java Wed Jun 26 18:09:25 2013 +0200
27.3 @@ -32,7 +32,8 @@
27.4 @Model(className = "Person", properties = {
27.5 @Property(name = "firstName", type = String.class),
27.6 @Property(name = "lastName", type = String.class),
27.7 - @Property(name = "sex", type = Sex.class)
27.8 + @Property(name = "sex", type = Sex.class),
27.9 + @Property(name = "address", type = Address.class)
27.10 })
27.11 final class PersonImpl {
27.12 @ComputedProperty
27.13 @@ -62,4 +63,10 @@
27.14 })
27.15 public class PeopleImpl {
27.16 }
27.17 +
27.18 + @Model(className = "Address", properties = {
27.19 + @Property(name = "street", type = String.class)
27.20 + })
27.21 + static class Addrss {
27.22 + }
27.23 }
28.1 --- a/json-tck/src/main/java/net/java/html/json/tests/Utils.java Wed May 29 19:36:31 2013 +0200
28.2 +++ b/json-tck/src/main/java/net/java/html/json/tests/Utils.java Wed Jun 26 18:09:25 2013 +0200
28.3 @@ -20,6 +20,8 @@
28.4 */
28.5 package net.java.html.json.tests;
28.6
28.7 +import java.net.URI;
28.8 +import java.net.URL;
28.9 import java.util.Map;
28.10 import java.util.ServiceLoader;
28.11 import net.java.html.BrwsrCtx;
28.12 @@ -33,8 +35,8 @@
28.13 private Utils() {
28.14 }
28.15
28.16 - static BrwsrCtx newContext() {
28.17 - for (KnockoutTCK tck : ServiceLoader.load(KnockoutTCK.class)) {
28.18 + static BrwsrCtx newContext(Class<?> clazz) {
28.19 + for (KnockoutTCK tck : ServiceLoader.load(KnockoutTCK.class, cl(clazz))) {
28.20 BrwsrCtx c = tck.createContext();
28.21 if (c != null) {
28.22 return c;
28.23 @@ -42,8 +44,8 @@
28.24 }
28.25 throw new AssertionError("Can't find appropriate Context in ServiceLoader!");
28.26 }
28.27 - static Object createObject(Map<String,Object> values) {
28.28 - for (KnockoutTCK tck : ServiceLoader.load(KnockoutTCK.class)) {
28.29 + static Object createObject(Map<String,Object> values, Class<?> clazz) {
28.30 + for (KnockoutTCK tck : ServiceLoader.load(KnockoutTCK.class, cl(clazz))) {
28.31 Object o = tck.createJSON(values);
28.32 if (o != null) {
28.33 return o;
28.34 @@ -51,11 +53,44 @@
28.35 }
28.36 throw new AssertionError("Can't find appropriate Context in ServiceLoader!");
28.37 }
28.38 - static Object executeScript(String script, Object... arguments) throws Exception {
28.39 - for (KnockoutTCK tck : ServiceLoader.load(KnockoutTCK.class)) {
28.40 + static Object executeScript(Class<?> clazz,
28.41 + String script, Object... arguments
28.42 + ) throws Exception {
28.43 + for (KnockoutTCK tck : ServiceLoader.load(KnockoutTCK.class, cl(clazz))) {
28.44 return tck.executeScript(script, arguments);
28.45 }
28.46 throw new AssertionError("Can't find appropriate Context in ServiceLoader!");
28.47 }
28.48
28.49 + static Object exposeHTML(Class<?> clazz, String html) throws Exception {
28.50 + String s =
28.51 + "var n = window.document.getElementById('ko.test.div'); \n "
28.52 + + "if (!n) { \n"
28.53 + + " n = window.document.createElement('div'); \n "
28.54 + + " n.id = 'ko.test.div'; \n "
28.55 + + " var body = window.document.getElementsByTagName('body')[0];\n"
28.56 + + " body.appendChild(n);\n"
28.57 + + "}\n"
28.58 + + "n.innerHTML = arguments[0]; \n ";
28.59 + return executeScript(clazz, s, html);
28.60 + }
28.61 +
28.62 + static String prepareURL(
28.63 + Class<?> clazz, String content, String mimeType, String... parameters) {
28.64 + for (KnockoutTCK tck : ServiceLoader.load(KnockoutTCK.class, cl(clazz))) {
28.65 + URI o = tck.prepareURL(content, mimeType, parameters);
28.66 + if (o != null) {
28.67 + return o.toString();
28.68 + }
28.69 + }
28.70 + throw new IllegalStateException();
28.71 + }
28.72 +
28.73 + private static ClassLoader cl(Class<?> c) {
28.74 + try {
28.75 + return c.getClassLoader();
28.76 + } catch (SecurityException ex) {
28.77 + return null;
28.78 + }
28.79 + }
28.80 }
29.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
29.2 +++ b/json-tck/src/main/java/org/apidesign/html/json/tck/KOTest.java Wed Jun 26 18:09:25 2013 +0200
29.3 @@ -0,0 +1,38 @@
29.4 +/**
29.5 + * HTML via Java(tm) Language Bindings
29.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
29.7 + *
29.8 + * This program is free software: you can redistribute it and/or modify
29.9 + * it under the terms of the GNU General Public License as published by
29.10 + * the Free Software Foundation, version 2 of the License.
29.11 + *
29.12 + * This program is distributed in the hope that it will be useful,
29.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
29.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29.15 + * GNU General Public License for more details. apidesign.org
29.16 + * designates this particular file as subject to the
29.17 + * "Classpath" exception as provided by apidesign.org
29.18 + * in the License file that accompanied this code.
29.19 + *
29.20 + * You should have received a copy of the GNU General Public License
29.21 + * along with this program. Look for COPYING file in the top folder.
29.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
29.23 + */
29.24 +package org.apidesign.html.json.tck;
29.25 +
29.26 +import java.lang.annotation.ElementType;
29.27 +import java.lang.annotation.Retention;
29.28 +import java.lang.annotation.RetentionPolicy;
29.29 +import java.lang.annotation.Target;
29.30 +
29.31 +/** Annotates method that is part of {@link KnockoutTCK test compatibility kit}
29.32 + * and should be executed in appropriate environment. The method annotated by
29.33 + * this annotation will be public instance method of its class
29.34 + * with no arguments.
29.35 + *
29.36 + * @author Jaroslav Tulach <jtulach@netbeans.org>
29.37 + */
29.38 +@Retention(RetentionPolicy.RUNTIME)
29.39 +@Target(ElementType.METHOD)
29.40 +public @interface KOTest {
29.41 +}
30.1 --- a/json-tck/src/main/java/org/apidesign/html/json/tck/KnockoutTCK.java Wed May 29 19:36:31 2013 +0200
30.2 +++ b/json-tck/src/main/java/org/apidesign/html/json/tck/KnockoutTCK.java Wed Jun 26 18:09:25 2013 +0200
30.3 @@ -20,22 +20,21 @@
30.4 */
30.5 package org.apidesign.html.json.tck;
30.6
30.7 +import java.net.URI;
30.8 import java.util.Map;
30.9 import net.java.html.BrwsrCtx;
30.10 import net.java.html.json.tests.ConvertTypesTest;
30.11 import net.java.html.json.tests.KnockoutTest;
30.12 import net.java.html.json.tests.JSONTest;
30.13 -import org.apidesign.bck2brwsr.vmtest.BrwsrTest;
30.14 -import org.apidesign.bck2brwsr.vmtest.VMTest;
30.15 import org.openide.util.lookup.ServiceProvider;
30.16
30.17 /** Entry point for providers of different HTML binding technologies (like
30.18 - * Knockout.js in bck2brwsr or in JavaFX's WebView). Sample usage:
30.19 + * Knockout.js in JavaFX's WebView). Sample usage:
30.20 * <pre>
30.21 {@link ServiceProvider @ServiceProvider}(service = KnockoutTCK.class)
30.22 -public final class Bck2BrwsrKnockoutTest extends KnockoutTCK {
30.23 +public final class MyKnockoutBindingTest extends KnockoutTCK {
30.24 {@link Override @Override}
30.25 - protected Context createContext() {
30.26 + protected BrwsrCtx createContext() {
30.27 // use {@link ContextBuilder}.{@link ContextBuilder#build() build}();
30.28 }
30.29
30.30 @@ -68,9 +67,21 @@
30.31 * @return the output of the execution
30.32 */
30.33 public abstract Object executeScript(String script, Object[] arguments);
30.34 +
30.35 + /** Creates a URL which later returns content with given
30.36 + * <code>mimeType</code> and <code>content</code>. The
30.37 + * content may be processed by the provided <code>parameters</code>.
30.38 + *
30.39 + * @param content
30.40 + * @param mimeType
30.41 + * @param parameters
30.42 + * @return
30.43 + */
30.44 + public abstract URI prepareURL(String content, String mimeType, String[] parameters);
30.45
30.46 - /** Gives you list of classes included in the TCK. Send them
30.47 - * to {@link VMTest#create(java.lang.Class)} factory method.
30.48 + /** Gives you list of classes included in the TCK. Their test methods
30.49 + * are annotated by {@link KOTest} annotation. The methods are public
30.50 + * instance methods that take no arguments.
30.51 *
30.52 * @return classes with methods annotated by {@link BrwsrTest} annotation
30.53 */
30.54 @@ -82,5 +93,5 @@
30.55 };
30.56 }
30.57
30.58 -
30.59 +
30.60 }
31.1 --- a/json/src/main/java/org/apidesign/html/json/impl/JSONList.java Wed May 29 19:36:31 2013 +0200
31.2 +++ b/json/src/main/java/org/apidesign/html/json/impl/JSONList.java Wed Jun 26 18:09:25 2013 +0200
31.3 @@ -40,6 +40,10 @@
31.4 }
31.5
31.6 public void assign(Bindings model) {
31.7 + if (this.model == null && isEmpty()) {
31.8 + this.model = model;
31.9 + return;
31.10 + }
31.11 if (this.model != model) {
31.12 this.model = model;
31.13 notifyChange();
32.1 --- a/json/src/main/java/org/apidesign/html/json/impl/ModelProcessor.java Wed May 29 19:36:31 2013 +0200
32.2 +++ b/json/src/main/java/org/apidesign/html/json/impl/ModelProcessor.java Wed Jun 26 18:09:25 2013 +0200
32.3 @@ -325,7 +325,11 @@
32.4 }
32.5 w.append("ret[" + cnt + "]).");
32.6 w.append(type).append("Value();\n");
32.7 - } else {
32.8 + } else if (isModel[0]) {
32.9 + w.append(" this.prop_").append(pn).append(" = org.apidesign.html.json.impl.JSON.read");
32.10 + w.append("(c, " + type + ".class, ");
32.11 + w.append("ret[" + cnt + "]);\n");
32.12 + }else {
32.13 w.append(" this.prop_").append(pn);
32.14 w.append(" = (").append(type).append(')');
32.15 w.append("ret[" + cnt + "];\n");
33.1 --- a/ko-archetype-test/pom.xml Wed May 29 19:36:31 2013 +0200
33.2 +++ b/ko-archetype-test/pom.xml Wed Jun 26 18:09:25 2013 +0200
33.3 @@ -38,11 +38,5 @@
33.4 <version>${project.version}</version>
33.5 <scope>provided</scope>
33.6 </dependency>
33.7 - <dependency>
33.8 - <groupId>${project.groupId}</groupId>
33.9 - <artifactId>ko-bck2brwsr</artifactId>
33.10 - <version>${project.version}</version>
33.11 - <scope>provided</scope>
33.12 - </dependency>
33.13 </dependencies>
33.14 </project>
34.1 --- a/ko-archetype-test/src/test/java/org/apidesign/html/archetype/test/ArchetypeVersionTest.java Wed May 29 19:36:31 2013 +0200
34.2 +++ b/ko-archetype-test/src/test/java/org/apidesign/html/archetype/test/ArchetypeVersionTest.java Wed Jun 26 18:09:25 2013 +0200
34.3 @@ -69,39 +69,6 @@
34.4 assertEquals(arch, version, "net.java.html.json dependency needs to be on latest version");
34.5 }
34.6
34.7 - @Test public void testCheckLauncher() throws Exception {
34.8 - final ClassLoader l = ArchetypeVersionTest.class.getClassLoader();
34.9 - URL r = l.getResource("archetype-resources/pom.xml");
34.10 - assertNotNull(r, "Archetype pom found");
34.11 -
34.12 - final XPathFactory fact = XPathFactory.newInstance();
34.13 - XPathExpression xp2 = fact.newXPath().compile(
34.14 - "//properties/bck2brwsr.launcher.version/text()"
34.15 - );
34.16 -
34.17 - Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(r.openStream());
34.18 - String arch = (String) xp2.evaluate(dom, XPathConstants.STRING);
34.19 -
34.20 -
34.21 - assertTrue(arch.matches("[0-9\\.]+"), "launcher version seems valid: " + arch);
34.22 - }
34.23 -
34.24 - @Test public void testCheckBck2Brwsr() throws Exception {
34.25 - final ClassLoader l = ArchetypeVersionTest.class.getClassLoader();
34.26 - URL r = l.getResource("archetype-resources/pom.xml");
34.27 - assertNotNull(r, "Archetype pom found");
34.28 -
34.29 - final XPathFactory fact = XPathFactory.newInstance();
34.30 - XPathExpression xp2 = fact.newXPath().compile(
34.31 - "//properties/bck2brwsr.version/text()"
34.32 - );
34.33 -
34.34 - Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(r.openStream());
34.35 - String arch = (String) xp2.evaluate(dom, XPathConstants.STRING);
34.36 -
34.37 - assertTrue(arch.matches("[0-9\\.]+"), "bck2brwsr version seems valid: " + arch);
34.38 - }
34.39 -
34.40 @Test public void testNbActions() throws Exception {
34.41 final ClassLoader l = ArchetypeVersionTest.class.getClassLoader();
34.42 URL r = l.getResource("archetype-resources/nbactions.xml");
35.1 --- a/ko-archetype-test/src/test/java/org/apidesign/html/archetype/test/VerifyArchetypeTest.java Wed May 29 19:36:31 2013 +0200
35.2 +++ b/ko-archetype-test/src/test/java/org/apidesign/html/archetype/test/VerifyArchetypeTest.java Wed Jun 26 18:09:25 2013 +0200
35.3 @@ -22,7 +22,6 @@
35.4
35.5 import java.io.File;
35.6 import java.util.Properties;
35.7 -import java.util.zip.ZipFile;
35.8 import org.apache.maven.it.Verifier;
35.9 import org.testng.annotations.Test;
35.10 import static org.testng.Assert.*;
35.11 @@ -32,7 +31,7 @@
35.12 * @author Jaroslav Tulach <jtulach@netbeans.org>
35.13 */
35.14 public class VerifyArchetypeTest {
35.15 - @Test public void fxBrwsrCompiles() throws Exception {
35.16 + @Test public void projectCompiles() throws Exception {
35.17 final File dir = new File("target/tests/fxcompile/").getAbsoluteFile();
35.18 generateFromArchetype(dir);
35.19
35.20 @@ -51,50 +50,9 @@
35.21 }
35.22 }
35.23
35.24 - v.verifyTextInLog("org.apidesign.bck2brwsr.launcher.FXBrwsrLauncher");
35.25 - v.verifyTextInLog("fxcompile/o-a-test/target/o-a-test-1.0-SNAPSHOT-fxbrwsr.zip");
35.26 + v.verifyTextInLog("fxcompile/o-a-test/target/o-a-test-1.0-SNAPSHOT-html.java.net.zip");
35.27 }
35.28
35.29 - @Test public void bck2BrwsrCompiles() throws Exception {
35.30 - final File dir = new File("target/tests/b2bcompile/").getAbsoluteFile();
35.31 - generateFromArchetype(dir);
35.32 -
35.33 - File created = new File(dir, "o-a-test");
35.34 - assertTrue(created.isDirectory(), "Project created");
35.35 - assertTrue(new File(created, "pom.xml").isFile(), "Pom file is in there");
35.36 -
35.37 - Verifier v = new Verifier(created.getAbsolutePath());
35.38 - Properties sysProp = v.getSystemProperties();
35.39 - if (Boolean.getBoolean("java.awt.headless")) {
35.40 - sysProp.put("java.awt.headless", "true");
35.41 - }
35.42 - v.addCliOption("-Pbck2brwsr");
35.43 - v.executeGoal("verify");
35.44 -
35.45 - v.verifyErrorFreeLog();
35.46 -
35.47 - // does pre-compilation to JavaScript
35.48 - v.verifyTextInLog("j2js");
35.49 - // uses Bck2BrwsrLauncher
35.50 - v.verifyTextInLog("BaseHTTPLauncher stopServerAndBrwsr");
35.51 - // building zip:
35.52 - v.verifyTextInLog("b2bcompile/o-a-test/target/o-a-test-1.0-SNAPSHOT-bck2brwsr.zip");
35.53 -
35.54 - for (String l : v.loadFile(v.getBasedir(), v.getLogFileName(), false)) {
35.55 - if (l.contains("fxbrwsr")) {
35.56 - fail("No fxbrwsr:\n" + l);
35.57 - }
35.58 - }
35.59 -
35.60 - File zip = new File(new File(created, "target"), "o-a-test-1.0-SNAPSHOT-bck2brwsr.zip");
35.61 - assertTrue(zip.isFile(), "Zip file with website was created");
35.62 -
35.63 - ZipFile zf = new ZipFile(zip);
35.64 - assertNotNull(zf.getEntry("public_html/index.html"), "index.html found");
35.65 - assertNotNull(zf.getEntry("public_html/twitterExample.css"), "css file found");
35.66 -
35.67 - }
35.68 -
35.69 private Verifier generateFromArchetype(final File dir, String... params) throws Exception {
35.70 Verifier v = new Verifier(dir.getAbsolutePath());
35.71 v.setAutoclean(false);
36.1 --- a/ko-archetype/pom.xml Wed May 29 19:36:31 2013 +0200
36.2 +++ b/ko-archetype/pom.xml Wed Jun 26 18:09:25 2013 +0200
36.3 @@ -14,8 +14,8 @@
36.4 <description>
36.5 HTML page with Knockout.js bindings driven by application model
36.6 written in Java. Use your favorite language to code. Use
36.7 - HTML as a lightweight rendering toolkit. Deploy using JavaFX or
36.8 - bck2brwsr virtual machine.
36.9 + HTML as a lightweight rendering toolkit. Deploy using JavaFX and
36.10 + Java virtual machine.
36.11 </description>
36.12 <build>
36.13 <resources>
37.1 --- a/ko-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml Wed May 29 19:36:31 2013 +0200
37.2 +++ b/ko-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml Wed Jun 26 18:09:25 2013 +0200
37.3 @@ -1,5 +1,5 @@
37.4 <?xml version="1.0" encoding="UTF-8"?>
37.5 -<archetype-descriptor name="FX/Bck2Brwsr Example">
37.6 +<archetype-descriptor name="Knockout4Java Example">
37.7 <fileSets>
37.8 <fileSet filtered="true" packaged="true">
37.9 <directory>src/main/java</directory>
37.10 @@ -37,7 +37,6 @@
37.11 <directory>assembly</directory>
37.12 <includes>
37.13 <include>fxbrwsr-assembly.xml</include>
37.14 - <include>bck2brwsr-assembly.xml</include>
37.15 </includes>
37.16 </fileSet>
37.17 </fileSets>
38.1 --- a/ko-archetype/src/main/resources/archetype-resources/nbactions-bck2brwsr.xml Wed May 29 19:36:31 2013 +0200
38.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
38.3 @@ -1,14 +0,0 @@
38.4 -<?xml version="1.0" encoding="UTF-8"?>
38.5 -<actions>
38.6 - <action>
38.7 - <actionName>run</actionName>
38.8 - <goals>
38.9 - <goal>package</goal>
38.10 - <goal>bck2brwsr:brwsr</goal>
38.11 - </goals>
38.12 - <properties>
38.13 - <skipTests>true</skipTests>
38.14 - <bck2brwsr.obfuscationlevel>NONE</bck2brwsr.obfuscationlevel>
38.15 - </properties>
38.16 - </action>
38.17 -</actions>
39.1 --- a/ko-archetype/src/main/resources/archetype-resources/nbactions-fxbrwsr.xml Wed May 29 19:36:31 2013 +0200
39.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
39.3 @@ -1,20 +0,0 @@
39.4 -<?xml version="1.0" encoding="UTF-8"?>
39.5 -<actions>
39.6 - <action>
39.7 - <actionName>run</actionName>
39.8 - <goals>
39.9 - <goal>process-classes</goal>
39.10 - <goal>bck2brwsr:brwsr</goal>
39.11 - </goals>
39.12 - </action>
39.13 - <action>
39.14 - <actionName>debug</actionName>
39.15 - <goals>
39.16 - <goal>process-classes</goal>
39.17 - <goal>bck2brwsr:brwsr</goal>
39.18 - </goals>
39.19 - <properties>
39.20 - <jpda.listen>maven</jpda.listen>
39.21 - </properties>
39.22 - </action>
39.23 -</actions>
40.1 --- a/ko-archetype/src/main/resources/archetype-resources/nbactions.xml Wed May 29 19:36:31 2013 +0200
40.2 +++ b/ko-archetype/src/main/resources/archetype-resources/nbactions.xml Wed Jun 26 18:09:25 2013 +0200
40.3 @@ -4,14 +4,14 @@
40.4 <actionName>run</actionName>
40.5 <goals>
40.6 <goal>process-classes</goal>
40.7 - <goal>bck2brwsr:brwsr</goal>
40.8 + <goal>exec:java</goal>
40.9 </goals>
40.10 </action>
40.11 <action>
40.12 <actionName>debug</actionName>
40.13 <goals>
40.14 <goal>process-classes</goal>
40.15 - <goal>bck2brwsr:brwsr</goal>
40.16 + <goal>exec:java</goal>
40.17 </goals>
40.18 <properties>
40.19 <jpda.listen>maven</jpda.listen>
41.1 --- a/ko-archetype/src/main/resources/archetype-resources/pom.xml Wed May 29 19:36:31 2013 +0200
41.2 +++ b/ko-archetype/src/main/resources/archetype-resources/pom.xml Wed Jun 26 18:09:25 2013 +0200
41.3 @@ -39,30 +39,10 @@
41.4 <properties>
41.5 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
41.6 <net.java.html.version>${project.version}</net.java.html.version>
41.7 - <bck2brwsr.version>${bck2brwsr.version}</bck2brwsr.version>
41.8 - <bck2brwsr.launcher.version>${bck2brwsr.launcher.version}</bck2brwsr.launcher.version>
41.9 - <bck2brwsr.obfuscationlevel>MINIMAL</bck2brwsr.obfuscationlevel>
41.10 - <brwsr.startpage>\${package.replace('.','/')}/index.html</brwsr.startpage>
41.11 </properties>
41.12 <build>
41.13 <plugins>
41.14 <plugin>
41.15 - <groupId>org.apidesign.bck2brwsr</groupId>
41.16 - <artifactId>bck2brwsr-maven-plugin</artifactId>
41.17 - <version>\${bck2brwsr.launcher.version}</version>
41.18 - <executions>
41.19 - <execution>
41.20 - <goals>
41.21 - <goal>brwsr</goal>
41.22 - </goals>
41.23 - </execution>
41.24 - </executions>
41.25 - <configuration>
41.26 - <startpage>\${brwsr.startpage}</startpage>
41.27 - <launcher>\${brwsr}</launcher>
41.28 - </configuration>
41.29 - </plugin>
41.30 - <plugin>
41.31 <groupId>org.apache.maven.plugins</groupId>
41.32 <artifactId>maven-compiler-plugin</artifactId>
41.33 <version>2.3.2</version>
41.34 @@ -73,21 +53,12 @@
41.35 </plugin>
41.36 <plugin>
41.37 <groupId>org.apache.maven.plugins</groupId>
41.38 - <artifactId>maven-surefire-plugin</artifactId>
41.39 - <version>2.14.1</version>
41.40 - <configuration>
41.41 - <systemPropertyVariables>
41.42 - <vmtest.brwsrs>\${brwsr}</vmtest.brwsrs>
41.43 - </systemPropertyVariables>
41.44 - </configuration>
41.45 - </plugin>
41.46 - <plugin>
41.47 - <groupId>org.apache.maven.plugins</groupId>
41.48 <artifactId>maven-jar-plugin</artifactId>
41.49 <version>2.4</version>
41.50 <configuration>
41.51 <archive>
41.52 <manifest>
41.53 + <mainClass>\${package}.Main</mainClass>
41.54 <addClasspath>true</addClasspath>
41.55 <classpathPrefix>lib/</classpathPrefix>
41.56 </manifest>
41.57 @@ -95,172 +66,61 @@
41.58 </configuration>
41.59 </plugin>
41.60 <plugin>
41.61 - <groupId>org.apache.maven.plugins</groupId>
41.62 - <artifactId>maven-deploy-plugin</artifactId>
41.63 - <version>2.7</version>
41.64 + <groupId>org.codehaus.mojo</groupId>
41.65 + <artifactId>exec-maven-plugin</artifactId>
41.66 + <version>1.2.1</version>
41.67 <configuration>
41.68 - <skip>true</skip>
41.69 + <mainClass>\${package}.Main</mainClass>
41.70 </configuration>
41.71 </plugin>
41.72 + <plugin>
41.73 + <artifactId>maven-assembly-plugin</artifactId>
41.74 + <version>2.4</version>
41.75 + <executions>
41.76 + <execution>
41.77 + <id>distro-assembly</id>
41.78 + <phase>package</phase>
41.79 + <goals>
41.80 + <goal>single</goal>
41.81 + </goals>
41.82 + <configuration>
41.83 + <descriptors>
41.84 + <descriptor>src/main/assembly/html.java.net.xml</descriptor>
41.85 + </descriptors>
41.86 + </configuration>
41.87 + </execution>
41.88 + </executions>
41.89 + </plugin>
41.90 </plugins>
41.91 </build>
41.92 -
41.93 <dependencies>
41.94 <dependency>
41.95 + <groupId>org.apidesign.html</groupId>
41.96 + <artifactId>net.java.html.json</artifactId>
41.97 + <version>\${net.java.html.version}</version>
41.98 + </dependency>
41.99 + <dependency>
41.100 + <groupId>org.apidesign.html</groupId>
41.101 + <artifactId>net.java.html.boot</artifactId>
41.102 + <version>\${net.java.html.version}</version>
41.103 + </dependency>
41.104 + <dependency>
41.105 + <groupId>org.apidesign.html</groupId>
41.106 + <artifactId>ko-fx</artifactId>
41.107 + <version>\${net.java.html.version}</version>
41.108 + <scope>runtime</scope>
41.109 + </dependency>
41.110 + <dependency>
41.111 + <groupId>org.apidesign.html</groupId>
41.112 + <artifactId>boot-fx</artifactId>
41.113 + <version>\${net.java.html.version}</version>
41.114 + <scope>runtime</scope>
41.115 + </dependency>
41.116 + <dependency>
41.117 <groupId>org.testng</groupId>
41.118 <artifactId>testng</artifactId>
41.119 - <version>6.5.2</version>
41.120 + <version>6.7</version>
41.121 <scope>test</scope>
41.122 </dependency>
41.123 - <dependency>
41.124 - <groupId>org.apidesign.bck2brwsr</groupId>
41.125 - <artifactId>vmtest</artifactId>
41.126 - <version>\${bck2brwsr.version}</version>
41.127 - <scope>test</scope>
41.128 - </dependency>
41.129 - <dependency>
41.130 - <groupId>org.apidesign.html</groupId>
41.131 - <artifactId>net.java.html.json</artifactId>
41.132 - <version>\${net.java.html.version}</version>
41.133 - <type>jar</type>
41.134 - </dependency>
41.135 </dependencies>
41.136 - <profiles>
41.137 - <profile>
41.138 - <id>fxbrwsr</id>
41.139 - <activation>
41.140 - <activeByDefault>true</activeByDefault>
41.141 - </activation>
41.142 - <properties>
41.143 - <brwsr>fxbrwsr</brwsr>
41.144 - </properties>
41.145 - <build>
41.146 - <plugins>
41.147 - <plugin>
41.148 - <groupId>org.apache.maven.plugins</groupId>
41.149 - <artifactId>maven-jar-plugin</artifactId>
41.150 - <version>2.4</version>
41.151 - <configuration>
41.152 - <archive>
41.153 - <manifest>
41.154 - <mainClass>org.apidesign.bck2brwsr.launcher.FXBrwsrLauncher</mainClass>
41.155 - <addClasspath>true</addClasspath>
41.156 - <classpathPrefix>lib/</classpathPrefix>
41.157 - </manifest>
41.158 - <manifestEntries>
41.159 - <StartPage>\${brwsr.startpage}</StartPage>
41.160 - </manifestEntries>
41.161 - </archive>
41.162 - </configuration>
41.163 - </plugin>
41.164 - <plugin>
41.165 - <artifactId>maven-assembly-plugin</artifactId>
41.166 - <version>2.4</version>
41.167 - <executions>
41.168 - <execution>
41.169 - <id>distro-assembly</id>
41.170 - <phase>package</phase>
41.171 - <goals>
41.172 - <goal>single</goal>
41.173 - </goals>
41.174 - <configuration>
41.175 - <descriptors>
41.176 - <descriptor>src/main/assembly/fxbrwsr.xml</descriptor>
41.177 - </descriptors>
41.178 - </configuration>
41.179 - </execution>
41.180 - </executions>
41.181 - </plugin>
41.182 - </plugins>
41.183 - </build>
41.184 - <dependencies>
41.185 - <dependency>
41.186 - <groupId>org.apidesign.html</groupId>
41.187 - <artifactId>ko-fx</artifactId>
41.188 - <version>\${net.java.html.version}</version>
41.189 - </dependency>
41.190 - <dependency>
41.191 - <groupId>org.apidesign.bck2brwsr</groupId>
41.192 - <artifactId>launcher.fx</artifactId>
41.193 - <version>\${bck2brwsr.launcher.version}</version>
41.194 - <scope>runtime</scope>
41.195 - </dependency>
41.196 - </dependencies>
41.197 - </profile>
41.198 - <profile>
41.199 - <id>bck2brwsr</id>
41.200 - <activation>
41.201 - <property>
41.202 - <name>brwsr</name>
41.203 - <value>bck2brwsr</value>
41.204 - </property>
41.205 - </activation>
41.206 - <build>
41.207 - <plugins>
41.208 - <plugin>
41.209 - <groupId>org.apidesign.bck2brwsr</groupId>
41.210 - <artifactId>bck2brwsr-maven-plugin</artifactId>
41.211 - <executions>
41.212 - <execution>
41.213 - <goals>
41.214 - <goal>j2js</goal>
41.215 - </goals>
41.216 - </execution>
41.217 - </executions>
41.218 - <configuration>
41.219 - <javascript>\${project.build.directory}/bck2brwsr.js</javascript>
41.220 - <obfuscation>\${bck2brwsr.obfuscationlevel}</obfuscation>
41.221 - </configuration>
41.222 - </plugin>
41.223 - <plugin>
41.224 - <groupId>org.apache.maven.plugins</groupId>
41.225 - <artifactId>maven-compiler-plugin</artifactId>
41.226 - <configuration>
41.227 - <compilerArguments>
41.228 - <bootclasspath>netbeans.ignore.jdk.bootclasspath</bootclasspath>
41.229 - </compilerArguments>
41.230 - </configuration>
41.231 - </plugin>
41.232 - <plugin>
41.233 - <artifactId>maven-assembly-plugin</artifactId>
41.234 - <version>2.4</version>
41.235 - <executions>
41.236 - <execution>
41.237 - <id>distro-assembly</id>
41.238 - <phase>package</phase>
41.239 - <goals>
41.240 - <goal>single</goal>
41.241 - </goals>
41.242 - <configuration>
41.243 - <descriptors>
41.244 - <descriptor>src/main/assembly/bck2brwsr.xml</descriptor>
41.245 - </descriptors>
41.246 - </configuration>
41.247 - </execution>
41.248 - </executions>
41.249 - </plugin>
41.250 - </plugins>
41.251 - </build>
41.252 - <dependencies>
41.253 - <dependency>
41.254 - <groupId>org.apidesign.bck2brwsr</groupId>
41.255 - <artifactId>emul</artifactId>
41.256 - <version>\${bck2brwsr.version}</version>
41.257 - <classifier>rt</classifier>
41.258 - </dependency>
41.259 - <dependency>
41.260 - <groupId>org.apidesign.html</groupId>
41.261 - <artifactId>ko-bck2brwsr</artifactId>
41.262 - <version>\${net.java.html.version}</version>
41.263 - <scope>runtime</scope>
41.264 - </dependency>
41.265 - <dependency>
41.266 - <groupId>org.apidesign.bck2brwsr</groupId>
41.267 - <artifactId>launcher.http</artifactId>
41.268 - <version>\${bck2brwsr.launcher.version}</version>
41.269 - <scope>test</scope>
41.270 - </dependency>
41.271 - </dependencies>
41.272 - </profile>
41.273 - </profiles>
41.274 </project>
42.1 --- a/ko-archetype/src/main/resources/archetype-resources/src/main/assembly/bck2brwsr.xml Wed May 29 19:36:31 2013 +0200
42.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
42.3 @@ -1,43 +0,0 @@
42.4 -<?xml version="1.0"?>
42.5 -<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
42.6 - xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
42.7 -
42.8 - <id>bck2brwsr</id>
42.9 - <formats>
42.10 - <format>zip</format>
42.11 - </formats>
42.12 - <baseDirectory>public_html</baseDirectory>
42.13 - <dependencySets>
42.14 - <dependencySet>
42.15 - <useProjectArtifact>false</useProjectArtifact>
42.16 - <scope>runtime</scope>
42.17 - <outputDirectory>lib</outputDirectory>
42.18 - <includes>
42.19 - <include>*:jar</include>
42.20 - <include>*:rt</include>
42.21 - </includes>
42.22 - </dependencySet>
42.23 - </dependencySets>
42.24 - <fileSets>
42.25 - <fileSet>
42.26 - <directory>${project.build.directory}/classes/${package.replace('.','/')}/</directory>
42.27 - <includes>
42.28 - <include>**/*</include>
42.29 - </includes>
42.30 - <excludes>
42.31 - <exclude>**/*.class</exclude>
42.32 - </excludes>
42.33 - <outputDirectory>/</outputDirectory>
42.34 - </fileSet>
42.35 - </fileSets>
42.36 - <files>
42.37 - <file>
42.38 - <source>${project.build.directory}/${project.build.finalName}.jar</source>
42.39 - <outputDirectory>/</outputDirectory>
42.40 - </file>
42.41 - <file>
42.42 - <source>${project.build.directory}/bck2brwsr.js</source>
42.43 - <outputDirectory>/</outputDirectory>
42.44 - </file>
42.45 - </files>
42.46 -</assembly>
42.47 \ No newline at end of file
43.1 --- a/ko-archetype/src/main/resources/archetype-resources/src/main/assembly/fxbrwsr.xml Wed May 29 19:36:31 2013 +0200
43.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
43.3 @@ -1,23 +0,0 @@
43.4 -<?xml version="1.0"?>
43.5 -<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
43.6 - xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
43.7 -
43.8 - <id>fxbrwsr</id>
43.9 - <formats>
43.10 - <format>zip</format>
43.11 - </formats>
43.12 - <baseDirectory>${project.build.finalName}-fxbrwsr</baseDirectory>
43.13 - <dependencySets>
43.14 - <dependencySet>
43.15 - <useProjectArtifact>false</useProjectArtifact>
43.16 - <scope>runtime</scope>
43.17 - <outputDirectory>lib</outputDirectory>
43.18 - </dependencySet>
43.19 - </dependencySets>
43.20 - <files>
43.21 - <file>
43.22 - <source>${project.build.directory}/${project.build.finalName}.jar</source>
43.23 - <outputDirectory>/</outputDirectory>
43.24 - </file>
43.25 - </files>
43.26 -</assembly>
43.27 \ No newline at end of file
44.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
44.2 +++ b/ko-archetype/src/main/resources/archetype-resources/src/main/assembly/html.java.net.xml Wed Jun 26 18:09:25 2013 +0200
44.3 @@ -0,0 +1,23 @@
44.4 +<?xml version="1.0"?>
44.5 +<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
44.6 + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
44.7 +
44.8 + <id>html.java.net</id>
44.9 + <formats>
44.10 + <format>zip</format>
44.11 + </formats>
44.12 + <baseDirectory>${project.build.finalName}-fxbrwsr</baseDirectory>
44.13 + <dependencySets>
44.14 + <dependencySet>
44.15 + <useProjectArtifact>false</useProjectArtifact>
44.16 + <scope>runtime</scope>
44.17 + <outputDirectory>lib</outputDirectory>
44.18 + </dependencySet>
44.19 + </dependencySets>
44.20 + <files>
44.21 + <file>
44.22 + <source>${project.build.directory}/${project.build.finalName}.jar</source>
44.23 + <outputDirectory>/</outputDirectory>
44.24 + </file>
44.25 + </files>
44.26 +</assembly>
44.27 \ No newline at end of file
45.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
45.2 +++ b/ko-archetype/src/main/resources/archetype-resources/src/main/java/Main.java Wed Jun 26 18:09:25 2013 +0200
45.3 @@ -0,0 +1,16 @@
45.4 +package ${package};
45.5 +
45.6 +import net.java.html.boot.BrowserBuilder;
45.7 +
45.8 +public final class Main {
45.9 + private Main() {
45.10 + }
45.11 +
45.12 + public static void main(String... args) throws Exception {
45.13 + BrowserBuilder.newBrowser().
45.14 + loadPage("index.html").
45.15 + loadClass(TwitterClient.class).
45.16 + invoke("initialize", args).
45.17 + showAndWait();
45.18 + }
45.19 +}
46.1 --- a/ko-archetype/src/main/resources/archetype-resources/src/main/java/TwitterClient.java Wed May 29 19:36:31 2013 +0200
46.2 +++ b/ko-archetype/src/main/resources/archetype-resources/src/main/java/TwitterClient.java Wed Jun 26 18:09:25 2013 +0200
46.3 @@ -90,7 +90,7 @@
46.4 model.queryTweets("http://search.twitter.com", sb.toString());
46.5 }
46.6
46.7 - static {
46.8 + public static void initialize(String... args) {
46.9 final TwitterModel model = new TwitterModel();
46.10 final List<Tweeters> svdLst = model.getSavedLists();
46.11 svdLst.add(newTweeters("API Design", "JaroslavTulach"));
47.1 --- a/ko-archetype/src/main/resources/archetype-resources/src/main/resources/index.html Wed May 29 19:36:31 2013 +0200
47.2 +++ b/ko-archetype/src/main/resources/archetype-resources/src/main/resources/index.html Wed Jun 26 18:09:25 2013 +0200
47.3 @@ -8,7 +8,7 @@
47.4 <!DOCTYPE html>
47.5 <html xmlns="http://www.w3.org/1999/xhtml">
47.6 <head>
47.7 - <title>Bck2Brwsr's Twitter</title>
47.8 + <title>Knockout in Java Twitter</title>
47.9 </head>
47.10 <body>
47.11 <link href='twitterExample.css' rel='Stylesheet' ></link>
47.12 @@ -19,7 +19,7 @@
47.13 </style>
47.14
47.15
47.16 - <h2>Bck2Brwsr's Twitter</h2>
47.17 + <h2>Knockout in Java Twitter</h2>
47.18
47.19 <p>
47.20 This code is based on original
47.21 @@ -33,11 +33,8 @@
47.22 dense and shorter than the original JavaScript model.
47.23 </p>
47.24 <p>
47.25 - The project has two profiles. Either it executes in real Java virtual
47.26 - machine and renders using JavaFX's WebView (use <code>fxbrwsr</code> profile
47.27 - - the default). It can also run directly in a browser via
47.28 - <a href="http://bck2brwsr.apidesign.org">Bck2Brwsr</a> virtual machine
47.29 - (use <code>bck2brwsr</code> profile).
47.30 + The project executes in real Java virtual
47.31 + machine and renders using JavaFX's WebView.
47.32 </p>
47.33
47.34 <div class='liveExample'>
47.35 @@ -78,13 +75,5 @@
47.36 </table>
47.37 </div>
47.38 </div>
47.39 -
47.40 - <script src="bck2brwsr.js"></script>
47.41 - <script type="text/javascript">
47.42 - var vm = bck2brwsr('${artifactId}-${version}.jar');
47.43 - vm.loadClass('${package}.TwitterClient');
47.44 - </script>
47.45 -
47.46 -
47.47 </body>
47.48 </html>
48.1 --- a/ko-archetype/src/main/resources/archetype-resources/src/test/java/IntegrationTest.java Wed May 29 19:36:31 2013 +0200
48.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
48.3 @@ -1,31 +0,0 @@
48.4 -package ${package};
48.5 -
48.6 -import org.apidesign.bck2brwsr.vmtest.BrwsrTest;
48.7 -import org.apidesign.bck2brwsr.vmtest.HtmlFragment;
48.8 -import org.apidesign.bck2brwsr.vmtest.VMTest;
48.9 -import org.testng.annotations.Factory;
48.10 -
48.11 -/** Sometimes it is useful to run tests inside of the real browser.
48.12 - * To do that just annotate your method with {@link org.apidesign.bck2brwsr.vmtest.BrwsrTest}
48.13 - * and that is it. If your code references elements on the HTML page,
48.14 - * you can pass in an {@link org.apidesign.bck2brwsr.vmtest.HtmlFragment} which
48.15 - * will be made available on the page before your test starts.
48.16 - */
48.17 -public class IntegrationTest {
48.18 -
48.19 - /** Write to testing code here. Use <code>assert</code> (but not TestNG's
48.20 - * Assert, as TestNG is not compiled with target 1.6 yet).
48.21 - */
48.22 - @HtmlFragment(
48.23 - "<h1>Put this snippet on the HTML page</h1>\n"
48.24 - )
48.25 - @BrwsrTest
48.26 - public void runThisTestInABrowser() {
48.27 - }
48.28 -
48.29 - @Factory
48.30 - public static Object[] create() {
48.31 - return VMTest.create(IntegrationTest.class);
48.32 - }
48.33 -
48.34 -}
49.1 --- a/ko-archetype/src/main/resources/archetype-resources/src/test/java/TwitterProtocolTest.java Wed May 29 19:36:31 2013 +0200
49.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
49.3 @@ -1,73 +0,0 @@
49.4 -package ${package};
49.5 -
49.6 -import org.apidesign.bck2brwsr.vmtest.BrwsrTest;
49.7 -import org.apidesign.bck2brwsr.vmtest.Http;
49.8 -import org.apidesign.bck2brwsr.vmtest.VMTest;
49.9 -import org.testng.annotations.Factory;
49.10 -
49.11 -public class TwitterProtocolTest {
49.12 - private TwitterModel page;
49.13 - @Http(@Http.Resource(
49.14 - path = "/search.json",
49.15 - mimeType = "application/json",
49.16 - parameters = {"callback"},
49.17 - content = "$0({\"completed_in\":0.04,\"max_id\":320055706885689344,\"max_id_str\""
49.18 - + ":\"320055706885689344\",\"page\":1,\"query\":\"from%3AJaroslavTulach\",\"refresh_url\":"
49.19 - + "\"?since_id=320055706885689344&q=from%3AJaroslavTulach\","
49.20 - + "\"results\":[{\"created_at\":\"Fri, 05 Apr 2013 06:10:01 +0000\","
49.21 - + "\"from_user\":\"JaroslavTulach\",\"from_user_id\":420944648,\"from_user_id_str\":"
49.22 - + "\"420944648\",\"from_user_name\":\"Jaroslav Tulach\",\"geo\":null,\"id\":320055706885689344,"
49.23 - + "\"id_str\":\"320055706885689344\",\"iso_language_code\":\"en\",\"metadata\":{\"result_type\":"
49.24 - + "\"recent\"},\"profile_image_url\":\"http:\\/\\/a0.twimg.com\\/profile_images\\/1656828312\\/jst_normal.gif\","
49.25 - + "\"profile_image_url_https\":\"https:\\/\\/si0.twimg.com\\/profile_images\\/1656828312\\/jst_normal.gif\","
49.26 - + "\"source\":\"<a href="http:\\/\\/twitter.com\\/">web<\\/a>\",\"text\":"
49.27 - + "\"@tom_enebo Amzng! Not that I would like #ruby, but I am really glad you guys stabilized the plugin + "
49.28 - + "made it work in #netbeans 7.3! Gd wrk.\",\"to_user\":\"tom_enebo\",\"to_user_id\":14498747,"
49.29 - + "\"to_user_id_str\":\"14498747\",\"to_user_name\":\"tom_enebo\",\"in_reply_to_status_id\":319832359509839872,"
49.30 - + "\"in_reply_to_status_id_str\":\"319832359509839872\"},{\"created_at\":\"Thu, 04 Apr 2013 07:33:06 +0000\","
49.31 - + "\"from_user\":\"JaroslavTulach\",\"from_user_id\":420944648,\"from_user_id_str\":"
49.32 - + "\"420944648\",\"from_user_name\":\"Jaroslav Tulach\",\"geo\":null,\"id\":319714227088678913,"
49.33 - + "\"id_str\":\"319714227088678913\",\"iso_language_code\":\"en\",\"metadata\":{\"result_type\":"
49.34 - + "\"recent\"},\"profile_image_url\":\"http:\\/\\/a0.twimg.com\\/profile_images\\/1656828312\\/jst_normal.gif\","
49.35 - + "\"profile_image_url_https\":\"https:\\/\\/si0.twimg.com\\/profile_images\\/1656828312\\/jst_normal.gif\","
49.36 - + "\"source\":\"<a href="http:\\/\\/twitter.com\\/">web<\\/a>\",\"text\":"
49.37 - + "\"RT @drkrab: At #erlangfactory @joerl: Frameworks grow in complexity until nobody can use them.\"},"
49.38 - + "{\"created_at\":\"Tue, 02 Apr 2013 07:44:34 +0000\",\"from_user\":\"JaroslavTulach\","
49.39 - + "\"from_user_id\":420944648,\"from_user_id_str\":\"420944648\",\"from_user_name\":\"Jaroslav Tulach\","
49.40 - + "\"geo\":null,\"id\":318992336145248256,\"id_str\":\"318992336145248256\",\"iso_language_code\":\"en\","
49.41 - + "\"metadata\":{\"result_type\":\"recent\"},\"profile_image_url\":"
49.42 - + "\"http:\\/\\/a0.twimg.com\\/profile_images\\/1656828312\\/jst_normal.gif\","
49.43 - + "\"profile_image_url_https\":\"https:\\/\\/si0.twimg.com\\/profile_images\\/1656828312\\/jst_normal.gif\","
49.44 - + "\"source\":\"<a href="http:\\/\\/twitter.com\\/">web<\\/a>\",\"text\":"
49.45 - + "\"Twitter renamed to twttr http:\\/\\/t.co\\/tqaN4T1xlZ - good, I don't have to rename #bck2brwsr!\"},"
49.46 - + "{\"created_at\":\"Sun, 31 Mar 2013 03:52:04 +0000\",\"from_user\":\"JaroslavTulach\",\"from_user_id\":420944648,"
49.47 - + "\"from_user_id_str\":\"420944648\",\"from_user_name\":\"Jaroslav Tulach\",\"geo\":null,"
49.48 - + "\"id\":318209051223789568,\"id_str\":\"318209051223789568\",\"iso_language_code\":\"en\",\"metadata\":"
49.49 - + "{\"result_type\":\"recent\"},\"profile_image_url\":"
49.50 - + "\"http:\\/\\/a0.twimg.com\\/profile_images\\/1656828312\\/jst_normal.gif\","
49.51 - + "\"profile_image_url_https\":\"https:\\/\\/si0.twimg.com\\/profile_images\\/1656828312\\/jst_normal.gif\","
49.52 - + "\"source\":\"<a href="http:\\/\\/twitter.com\\/">web<\\/a>\",\"text\":"
49.53 - + "\"Math proofs without words. Ingenious: http:\\/\\/t.co\\/sz7yVbfpGw\"}],\"results_per_page\":100,"
49.54 - + "\"since_id\":0,\"since_id_str\":\"0\"})"
49.55 - ))
49.56 - @BrwsrTest public void readFromTwttr() throws InterruptedException {
49.57 - if (page == null) {
49.58 - page = new TwitterModel();
49.59 - page.applyBindings();
49.60 - page.queryTweets("", "q=xyz");
49.61 - }
49.62 -
49.63 - if (page.getCurrentTweets().isEmpty()) {
49.64 - throw new InterruptedException();
49.65 - }
49.66 -
49.67 - assert 4 == page.getCurrentTweets().size() : "Four tweets: " + page.getCurrentTweets();
49.68 -
49.69 - String firstDate = page.getCurrentTweets().get(0).getCreated_at();
49.70 - assert "Fri, 05 Apr 2013 06:10:01 +0000".equals(firstDate) : "Date is OK: " + firstDate;
49.71 - }
49.72 -
49.73 - @Factory public static Object[] create() {
49.74 - return VMTest.create(TwitterProtocolTest.class);
49.75 - }
49.76 -}
50.1 --- a/ko-bck2brwsr/pom.xml Wed May 29 19:36:31 2013 +0200
50.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
50.3 @@ -1,96 +0,0 @@
50.4 -<?xml version="1.0"?>
50.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">
50.6 - <modelVersion>4.0.0</modelVersion>
50.7 - <parent>
50.8 - <groupId>org.apidesign</groupId>
50.9 - <artifactId>html</artifactId>
50.10 - <version>0.4-SNAPSHOT</version>
50.11 - </parent>
50.12 - <groupId>org.apidesign.html</groupId>
50.13 - <artifactId>ko-bck2brwsr</artifactId>
50.14 - <version>0.4-SNAPSHOT</version>
50.15 - <name>Knockout.b2b</name>
50.16 - <url>http://maven.apache.org</url>
50.17 - <build>
50.18 - <plugins>
50.19 - <plugin>
50.20 - <groupId>org.apache.maven.plugins</groupId>
50.21 - <artifactId>maven-compiler-plugin</artifactId>
50.22 - <version>2.3.2</version>
50.23 - <configuration>
50.24 - <source>1.7</source>
50.25 - <target>1.7</target>
50.26 - </configuration>
50.27 - </plugin>
50.28 - <plugin>
50.29 - <groupId>org.apache.maven.plugins</groupId>
50.30 - <artifactId>maven-javadoc-plugin</artifactId>
50.31 - <configuration>
50.32 - <skip>false</skip>
50.33 - </configuration>
50.34 - </plugin>
50.35 - </plugins>
50.36 - </build>
50.37 - <dependencies>
50.38 - <dependency>
50.39 - <groupId>org.testng</groupId>
50.40 - <artifactId>testng</artifactId>
50.41 - <scope>test</scope>
50.42 - <exclusions>
50.43 - <exclusion>
50.44 - <artifactId>junit</artifactId>
50.45 - <groupId>junit</groupId>
50.46 - </exclusion>
50.47 - </exclusions>
50.48 - </dependency>
50.49 - <dependency>
50.50 - <groupId>org.netbeans.api</groupId>
50.51 - <artifactId>org-openide-util-lookup</artifactId>
50.52 - <scope>provided</scope>
50.53 - </dependency>
50.54 - <dependency>
50.55 - <groupId>org.apidesign.bck2brwsr</groupId>
50.56 - <artifactId>emul</artifactId>
50.57 - <version>${bck2brwsr.version}</version>
50.58 - <classifier>rt</classifier>
50.59 - <type>jar</type>
50.60 - <scope>compile</scope>
50.61 - </dependency>
50.62 - <dependency>
50.63 - <groupId>org.apidesign.bck2brwsr</groupId>
50.64 - <artifactId>vm4brwsr</artifactId>
50.65 - <version>${bck2brwsr.version}</version>
50.66 - <type>jar</type>
50.67 - <scope>test</scope>
50.68 - </dependency>
50.69 - <dependency>
50.70 - <groupId>org.apidesign.bck2brwsr</groupId>
50.71 - <artifactId>vmtest</artifactId>
50.72 - <version>${bck2brwsr.version}</version>
50.73 - <scope>test</scope>
50.74 - </dependency>
50.75 - <dependency>
50.76 - <groupId>org.apidesign.bck2brwsr</groupId>
50.77 - <artifactId>launcher.http</artifactId>
50.78 - <version>${bck2brwsr.launcher.version}</version>
50.79 - <scope>test</scope>
50.80 - </dependency>
50.81 - <dependency>
50.82 - <groupId>org.apidesign.html</groupId>
50.83 - <artifactId>net.java.html.json</artifactId>
50.84 - <version>0.4-SNAPSHOT</version>
50.85 - </dependency>
50.86 - <dependency>
50.87 - <groupId>org.apidesign.html</groupId>
50.88 - <artifactId>net.java.html.json.tck</artifactId>
50.89 - <version>0.4-SNAPSHOT</version>
50.90 - <scope>test</scope>
50.91 - </dependency>
50.92 - <dependency>
50.93 - <groupId>org.apidesign.bck2brwsr</groupId>
50.94 - <artifactId>core</artifactId>
50.95 - <version>${bck2brwsr.version}</version>
50.96 - <type>jar</type>
50.97 - </dependency>
50.98 - </dependencies>
50.99 -</project>
51.1 --- a/ko-bck2brwsr/src/main/java/org/apidesign/html/ko2brwsr/BrwsrCtxImpl.java Wed May 29 19:36:31 2013 +0200
51.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
51.3 @@ -1,129 +0,0 @@
51.4 -/**
51.5 - * HTML via Java(tm) Language Bindings
51.6 - * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
51.7 - *
51.8 - * This program is free software: you can redistribute it and/or modify
51.9 - * it under the terms of the GNU General Public License as published by
51.10 - * the Free Software Foundation, version 2 of the License.
51.11 - *
51.12 - * This program is distributed in the hope that it will be useful,
51.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
51.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
51.15 - * GNU General Public License for more details. apidesign.org
51.16 - * designates this particular file as subject to the
51.17 - * "Classpath" exception as provided by apidesign.org
51.18 - * in the License file that accompanied this code.
51.19 - *
51.20 - * You should have received a copy of the GNU General Public License
51.21 - * along with this program. Look for COPYING file in the top folder.
51.22 - * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
51.23 - */
51.24 -package org.apidesign.html.ko2brwsr;
51.25 -
51.26 -import java.io.ByteArrayOutputStream;
51.27 -import java.io.IOException;
51.28 -import java.io.InputStream;
51.29 -import java.io.InputStreamReader;
51.30 -import net.java.html.BrwsrCtx;
51.31 -import org.apidesign.html.context.spi.Contexts;
51.32 -import org.apidesign.html.json.spi.FunctionBinding;
51.33 -import org.apidesign.html.json.spi.JSONCall;
51.34 -import org.apidesign.html.json.spi.PropertyBinding;
51.35 -import org.apidesign.html.json.spi.Technology;
51.36 -import org.apidesign.html.json.spi.Transfer;
51.37 -
51.38 -/**
51.39 - *
51.40 - * @author Jaroslav Tulach <jtulach@netbeans.org>
51.41 - */
51.42 -final class BrwsrCtxImpl implements Technology<Object>, Transfer {
51.43 - private BrwsrCtxImpl() {}
51.44 -
51.45 - public static final BrwsrCtxImpl DEFAULT = new BrwsrCtxImpl();
51.46 -
51.47 - @Override
51.48 - public void extract(Object obj, String[] props, Object[] values) {
51.49 - ConvertTypes.extractJSON(obj, props, values);
51.50 - }
51.51 -
51.52 - @Override
51.53 - public void loadJSON(final JSONCall call) {
51.54 - class R implements Runnable {
51.55 - Object[] arr = { null };
51.56 - @Override
51.57 - public void run() {
51.58 - call.notifySuccess(arr[0]);
51.59 - }
51.60 - }
51.61 - R r = new R();
51.62 - if (call.isJSONP()) {
51.63 - String me = ConvertTypes.createJSONP(r.arr, r);
51.64 - ConvertTypes.loadJSONP(call.composeURL(me), me);
51.65 - } else {
51.66 - String data = null;
51.67 - if (call.isDoOutput()) {
51.68 - try {
51.69 - ByteArrayOutputStream bos = new ByteArrayOutputStream();
51.70 - call.writeData(bos);
51.71 - data = new String(bos.toByteArray(), "UTF-8");
51.72 - } catch (IOException ex) {
51.73 - call.notifyError(ex);
51.74 - }
51.75 - }
51.76 - ConvertTypes.loadJSON(call.composeURL(null), r.arr, r, call.getMethod(), data);
51.77 - }
51.78 - }
51.79 -
51.80 - @Override
51.81 - public Object wrapModel(Object model) {
51.82 - return model;
51.83 - }
51.84 -
51.85 - @Override
51.86 - public void bind(PropertyBinding b, Object model, Object data) {
51.87 - Knockout.bind(data, b, b.getPropertyName(),
51.88 - "getValue__Ljava_lang_Object_2",
51.89 - b.isReadOnly() ? null : "setValue__VLjava_lang_Object_2",
51.90 - false, false
51.91 - );
51.92 - }
51.93 -
51.94 - @Override
51.95 - public void valueHasMutated(Object data, String propertyName) {
51.96 - Knockout.valueHasMutated(data, propertyName);
51.97 - }
51.98 -
51.99 - @Override
51.100 - public void expose(FunctionBinding fb, Object model, Object d) {
51.101 - Knockout.expose(d, fb, fb.getFunctionName(), "call__VLjava_lang_Object_2Ljava_lang_Object_2");
51.102 - }
51.103 -
51.104 - @Override
51.105 - public void applyBindings(Object data) {
51.106 - Knockout.applyBindings(data);
51.107 - }
51.108 -
51.109 - @Override
51.110 - public Object wrapArray(Object[] arr) {
51.111 - return arr;
51.112 - }
51.113 -
51.114 - @Override
51.115 - public <M> M toModel(Class<M> modelClass, Object data) {
51.116 - return modelClass.cast(data);
51.117 - }
51.118 -
51.119 - @Override
51.120 - public Object toJSON(InputStream is) throws IOException {
51.121 - StringBuilder sb = new StringBuilder();
51.122 - InputStreamReader r = new InputStreamReader(is);
51.123 - for (;;) {
51.124 - int ch = r.read();
51.125 - if (ch == -1) {
51.126 - break;
51.127 - }
51.128 - sb.append((char)ch);
51.129 - }
51.130 - return ConvertTypes.parse(sb.toString());
51.131 - }
51.132 -}
52.1 --- a/ko-bck2brwsr/src/main/java/org/apidesign/html/ko2brwsr/BrwsrCtxPrvdr.java Wed May 29 19:36:31 2013 +0200
52.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
52.3 @@ -1,54 +0,0 @@
52.4 -/**
52.5 - * HTML via Java(tm) Language Bindings
52.6 - * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
52.7 - *
52.8 - * This program is free software: you can redistribute it and/or modify
52.9 - * it under the terms of the GNU General Public License as published by
52.10 - * the Free Software Foundation, version 2 of the License.
52.11 - *
52.12 - * This program is distributed in the hope that it will be useful,
52.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
52.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
52.15 - * GNU General Public License for more details. apidesign.org
52.16 - * designates this particular file as subject to the
52.17 - * "Classpath" exception as provided by apidesign.org
52.18 - * in the License file that accompanied this code.
52.19 - *
52.20 - * You should have received a copy of the GNU General Public License
52.21 - * along with this program. Look for COPYING file in the top folder.
52.22 - * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
52.23 - */
52.24 -package org.apidesign.html.ko2brwsr;
52.25 -
52.26 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
52.27 -import org.apidesign.html.context.spi.Contexts;
52.28 -import org.apidesign.html.json.spi.Technology;
52.29 -import org.apidesign.html.json.spi.Transfer;
52.30 -import org.openide.util.lookup.ServiceProvider;
52.31 -
52.32 -/** This is an implementation package - just
52.33 - * include its JAR on classpath and use official {@link Context} API
52.34 - * to access the functionality.
52.35 - * <p>
52.36 - * Provides binding between models and <a href="http://bck2brwsr.apidesign.org">
52.37 - * Bck2Brwsr</a> VM.
52.38 - * Registers {@link ContextProvider}, so {@link ServiceLoader} can find it.
52.39 - *
52.40 - * @author Jaroslav Tulach <jtulach@netbeans.org>
52.41 - */
52.42 -@ServiceProvider(service = Contexts.Provider.class)
52.43 -public final class BrwsrCtxPrvdr implements Contexts.Provider {
52.44 -
52.45 - @Override
52.46 - public void fillContext(Contexts.Builder context, Class<?> requestor) {
52.47 - if (bck2BrwsrVM()) {
52.48 - context.register(Technology.class, BrwsrCtxImpl.DEFAULT, 50).
52.49 - register(Transfer.class, BrwsrCtxImpl.DEFAULT, 50);
52.50 - }
52.51 - }
52.52 -
52.53 - @JavaScriptBody(args = { }, body = "return true;")
52.54 - private static boolean bck2BrwsrVM() {
52.55 - return false;
52.56 - }
52.57 -}
53.1 --- a/ko-bck2brwsr/src/main/java/org/apidesign/html/ko2brwsr/ConvertTypes.java Wed May 29 19:36:31 2013 +0200
53.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
53.3 @@ -1,155 +0,0 @@
53.4 -/**
53.5 - * HTML via Java(tm) Language Bindings
53.6 - * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
53.7 - *
53.8 - * This program is free software: you can redistribute it and/or modify
53.9 - * it under the terms of the GNU General Public License as published by
53.10 - * the Free Software Foundation, version 2 of the License.
53.11 - *
53.12 - * This program is distributed in the hope that it will be useful,
53.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
53.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
53.15 - * GNU General Public License for more details. apidesign.org
53.16 - * designates this particular file as subject to the
53.17 - * "Classpath" exception as provided by apidesign.org
53.18 - * in the License file that accompanied this code.
53.19 - *
53.20 - * You should have received a copy of the GNU General Public License
53.21 - * along with this program. Look for COPYING file in the top folder.
53.22 - * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
53.23 - */
53.24 -package org.apidesign.html.ko2brwsr;
53.25 -
53.26 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
53.27 -
53.28 -/**
53.29 - *
53.30 - * @author Jaroslav Tulach <jtulach@netbeans.org>
53.31 - */
53.32 -final class ConvertTypes {
53.33 - ConvertTypes() {
53.34 - }
53.35 -
53.36 - public static String toString(Object object, String property) {
53.37 - Object ret = getProperty(object, property);
53.38 - return ret == null ? null : ret.toString();
53.39 - }
53.40 -
53.41 - public static double toDouble(Object object, String property) {
53.42 - Object ret = getProperty(object, property);
53.43 - return ret instanceof Number ? ((Number)ret).doubleValue() : Double.NaN;
53.44 - }
53.45 -
53.46 - public static int toInt(Object object, String property) {
53.47 - Object ret = getProperty(object, property);
53.48 - return ret instanceof Number ? ((Number)ret).intValue() : Integer.MIN_VALUE;
53.49 - }
53.50 -
53.51 - public static <T> T toModel(Class<T> modelClass, Object object, String property) {
53.52 - Object ret = getProperty(object, property);
53.53 - if (ret == null || modelClass.isInstance(ret)) {
53.54 - return modelClass.cast(ret);
53.55 - }
53.56 - throw new IllegalStateException("Value " + ret + " is not of type " + modelClass);
53.57 - }
53.58 -
53.59 - public static String toJSON(Object value) {
53.60 - if (value == null) {
53.61 - return "null";
53.62 - }
53.63 - if (value instanceof Enum) {
53.64 - value = value.toString();
53.65 - }
53.66 - if (value instanceof String) {
53.67 - return '"' +
53.68 - ((String)value).
53.69 - replace("\"", "\\\"").
53.70 - replace("\n", "\\n").
53.71 - replace("\r", "\\r").
53.72 - replace("\t", "\\t")
53.73 - + '"';
53.74 - }
53.75 - return value.toString();
53.76 - }
53.77 -
53.78 - @JavaScriptBody(args = { "object", "property" },
53.79 - body = "if (property === null) return object;\n"
53.80 - + "var p = object[property]; return p ? p : null;"
53.81 - )
53.82 - private static Object getProperty(Object object, String property) {
53.83 - return null;
53.84 - }
53.85 -
53.86 - public static String createJSONP(Object[] jsonResult, Runnable whenDone) {
53.87 - int h = whenDone.hashCode();
53.88 - String name;
53.89 - for (;;) {
53.90 - name = "jsonp" + Integer.toHexString(h);
53.91 - if (defineIfUnused(name, jsonResult, whenDone)) {
53.92 - return name;
53.93 - }
53.94 - h++;
53.95 - }
53.96 - }
53.97 -
53.98 - @JavaScriptBody(args = { "name", "arr", "run" }, body =
53.99 - "if (window[name]) return false;\n "
53.100 - + "window[name] = function(data) {\n "
53.101 - + " delete window[name];\n"
53.102 - + " var el = window.document.getElementById(name);\n"
53.103 - + " el.parentNode.removeChild(el);\n"
53.104 - + " arr[0] = data;\n"
53.105 - + " run.run__V();\n"
53.106 - + "};\n"
53.107 - + "return true;\n"
53.108 - )
53.109 - private static boolean defineIfUnused(String name, Object[] arr, Runnable run) {
53.110 - return true;
53.111 - }
53.112 -
53.113 - @JavaScriptBody(args = { "s" }, body = "return eval('(' + s + ')');")
53.114 - static Object parse(String s) {
53.115 - return s;
53.116 - }
53.117 -
53.118 - @JavaScriptBody(args = { "url", "arr", "callback", "method", "data" }, body = ""
53.119 - + "var request = new XMLHttpRequest();\n"
53.120 - + "if (!method) method = 'GET';\n"
53.121 - + "request.open(method, url, true);\n"
53.122 - + "request.setRequestHeader('Content-Type', 'application/json; charset=utf-8');\n"
53.123 - + "request.onreadystatechange = function() {\n"
53.124 - + " if (this.readyState!==4) return;\n"
53.125 - + " try {\n"
53.126 - + " arr[0] = eval('(' + this.response + ')');\n"
53.127 - + " } catch (error) {;\n"
53.128 - + " arr[0] = this.response;\n"
53.129 - + " }\n"
53.130 - + " callback.run__V();\n"
53.131 - + "};"
53.132 - + "if (data) request.send(data);"
53.133 - + "else request.send();"
53.134 - )
53.135 - static void loadJSON(
53.136 - String url, Object[] jsonResult, Runnable whenDone, String method, String data
53.137 - ) {
53.138 - }
53.139 -
53.140 - @JavaScriptBody(args = { "url", "jsonp" }, body =
53.141 - "var scrpt = window.document.createElement('script');\n "
53.142 - + "scrpt.setAttribute('src', url);\n "
53.143 - + "scrpt.setAttribute('id', jsonp);\n "
53.144 - + "scrpt.setAttribute('type', 'text/javascript');\n "
53.145 - + "var body = document.getElementsByTagName('body')[0];\n "
53.146 - + "body.appendChild(scrpt);\n"
53.147 - )
53.148 - static void loadJSONP(String url, String jsonp) {
53.149 -
53.150 - }
53.151 -
53.152 - public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
53.153 - for (int i = 0; i < props.length; i++) {
53.154 - values[i] = getProperty(jsonObject, props[i]);
53.155 - }
53.156 - }
53.157 -
53.158 -}
54.1 --- a/ko-bck2brwsr/src/main/java/org/apidesign/html/ko2brwsr/Knockout.java Wed May 29 19:36:31 2013 +0200
54.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
54.3 @@ -1,134 +0,0 @@
54.4 -/**
54.5 - * HTML via Java(tm) Language Bindings
54.6 - * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
54.7 - *
54.8 - * This program is free software: you can redistribute it and/or modify
54.9 - * it under the terms of the GNU General Public License as published by
54.10 - * the Free Software Foundation, version 2 of the License.
54.11 - *
54.12 - * This program is distributed in the hope that it will be useful,
54.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
54.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
54.15 - * GNU General Public License for more details. apidesign.org
54.16 - * designates this particular file as subject to the
54.17 - * "Classpath" exception as provided by apidesign.org
54.18 - * in the License file that accompanied this code.
54.19 - *
54.20 - * You should have received a copy of the GNU General Public License
54.21 - * along with this program. Look for COPYING file in the top folder.
54.22 - * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
54.23 - */
54.24 -package org.apidesign.html.ko2brwsr;
54.25 -
54.26 -import java.lang.reflect.Method;
54.27 -import java.util.List;
54.28 -import org.apidesign.bck2brwsr.core.ExtraJavaScript;
54.29 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
54.30 -
54.31 -/** Provides binding between models and bck2brwsr VM.
54.32 - *
54.33 - * @author Jaroslav Tulach <jtulach@netbeans.org>
54.34 - */
54.35 -@ExtraJavaScript(resource = "/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js")
54.36 -final class Knockout {
54.37 - /** used by tests */
54.38 - static Knockout next;
54.39 - private final Object model;
54.40 -
54.41 - Knockout(Object model) {
54.42 - this.model = model == null ? this : model;
54.43 - }
54.44 -
54.45 - public static <M> Knockout applyBindings(
54.46 - Object model, String[] propsGettersAndSetters,
54.47 - String[] methodsAndSignatures
54.48 - ) {
54.49 - applyImpl(propsGettersAndSetters, model.getClass(), model, model, methodsAndSignatures);
54.50 - return new Knockout(model);
54.51 - }
54.52 - public static <M> Knockout applyBindings(
54.53 - Class<M> modelClass, M model, String[] propsGettersAndSetters,
54.54 - String[] methodsAndSignatures
54.55 - ) {
54.56 - Knockout bindings = next;
54.57 - next = null;
54.58 - if (bindings == null) {
54.59 - bindings = new Knockout(null);
54.60 - }
54.61 - applyImpl(propsGettersAndSetters, modelClass, bindings, model, methodsAndSignatures);
54.62 - applyBindings(bindings);
54.63 - return bindings;
54.64 - }
54.65 -
54.66 - public void valueHasMutated(String prop) {
54.67 - valueHasMutated(model, prop);
54.68 - }
54.69 - @JavaScriptBody(args = { "self", "prop" }, body =
54.70 - "var p = self[prop]; if (p) p.valueHasMutated();"
54.71 - )
54.72 - public static void valueHasMutated(Object self, String prop) {
54.73 - }
54.74 -
54.75 -
54.76 - @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
54.77 - public static void triggerEvent(String id, String ev) {
54.78 - }
54.79 -
54.80 - @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
54.81 - "var bnd = {\n"
54.82 - + " 'read': function() {\n"
54.83 - + " var v = model[getter]();\n"
54.84 - + " if (array) v = v.koArray(); else if (v !== null) v = v.valueOf();\n"
54.85 - + " return v;\n"
54.86 - + " },\n"
54.87 - + " 'owner': bindings\n"
54.88 - + "};\n"
54.89 - + "if (setter != null) {\n"
54.90 - + " bnd['write'] = function(val) {\n"
54.91 - + " var v = val === null ? null : val.valueOf();"
54.92 - + " model[setter](v);\n"
54.93 - + " };\n"
54.94 - + "}\n"
54.95 - + "bindings[prop] = ko['computed'](bnd);"
54.96 - )
54.97 - static void bind(
54.98 - Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
54.99 - ) {
54.100 - }
54.101 -
54.102 - @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body =
54.103 - "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
54.104 - )
54.105 - static void expose(
54.106 - Object bindings, Object model, String prop, String sig
54.107 - ) {
54.108 - }
54.109 -
54.110 - @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
54.111 - static void applyBindings(Object bindings) {}
54.112 -
54.113 - private static void applyImpl(
54.114 - String[] propsGettersAndSetters,
54.115 - Class<?> modelClass,
54.116 - Object bindings,
54.117 - Object model,
54.118 - String[] methodsAndSignatures
54.119 - ) throws IllegalStateException, SecurityException {
54.120 - for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
54.121 - try {
54.122 - Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
54.123 - bind(bindings, model, propsGettersAndSetters[i],
54.124 - propsGettersAndSetters[i + 1],
54.125 - propsGettersAndSetters[i + 2],
54.126 - getter.getReturnType().isPrimitive(),
54.127 - List.class.isAssignableFrom(getter.getReturnType()));
54.128 - } catch (NoSuchMethodException ex) {
54.129 - throw new IllegalStateException(ex.getMessage());
54.130 - }
54.131 - }
54.132 - for (int i = 0; i < methodsAndSignatures.length; i += 2) {
54.133 - expose(
54.134 - bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);
54.135 - }
54.136 - }
54.137 -}
55.1 --- a/ko-bck2brwsr/src/main/resources/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js Wed May 29 19:36:31 2013 +0200
55.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
55.3 @@ -1,3614 +0,0 @@
55.4 -/*
55.5 - * HTML via Java(tm) Language Bindings
55.6 - * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
55.7 - *
55.8 - * This program is free software: you can redistribute it and/or modify
55.9 - * it under the terms of the GNU General Public License as published by
55.10 - * the Free Software Foundation, version 2 of the License.
55.11 - *
55.12 - * This program is distributed in the hope that it will be useful,
55.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
55.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
55.15 - * GNU General Public License for more details. apidesign.org
55.16 - * designates this particular file as subject to the
55.17 - * "Classpath" exception as provided by apidesign.org
55.18 - * in the License file that accompanied this code.
55.19 - *
55.20 - * You should have received a copy of the GNU General Public License
55.21 - * along with this program. Look for COPYING file in the top folder.
55.22 - * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
55.23 - */
55.24 -// Knockout JavaScript library v2.2.1
55.25 -// (c) Steven Sanderson - http://knockoutjs.com/
55.26 -// License: MIT (http://www.opensource.org/licenses/mit-license.php)
55.27 -
55.28 -(function(){
55.29 -var DEBUG=true;
55.30 -(function(window,document,navigator,jQuery,undefined){
55.31 -!function(factory) {
55.32 - // Support three module loading scenarios
55.33 - if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
55.34 - // [1] CommonJS/Node.js
55.35 - var target = module['exports'] || exports; // module.exports is for Node.js
55.36 - factory(target);
55.37 - } else if (typeof define === 'function' && define['amd']) {
55.38 - // [2] AMD anonymous module
55.39 - define(['exports'], factory);
55.40 - } else {
55.41 - // [3] No module loader (plain <script> tag) - put directly in global namespace
55.42 - factory(window['ko'] = {});
55.43 - }
55.44 -}(function(koExports){
55.45 -// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
55.46 -// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
55.47 -var ko = typeof koExports !== 'undefined' ? koExports : {};
55.48 -// Google Closure Compiler helpers (used only to make the minified file smaller)
55.49 -ko.exportSymbol = function(koPath, object) {
55.50 - var tokens = koPath.split(".");
55.51 -
55.52 - // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
55.53 - // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
55.54 - var target = ko;
55.55 -
55.56 - for (var i = 0; i < tokens.length - 1; i++)
55.57 - target = target[tokens[i]];
55.58 - target[tokens[tokens.length - 1]] = object;
55.59 -};
55.60 -ko.exportProperty = function(owner, publicName, object) {
55.61 - owner[publicName] = object;
55.62 -};
55.63 -ko.version = "2.2.1";
55.64 -
55.65 -ko.exportSymbol('version', ko.version);
55.66 -ko.utils = new (function () {
55.67 - var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
55.68 -
55.69 - // 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)
55.70 - var knownEvents = {}, knownEventTypesByEventName = {};
55.71 - var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
55.72 - knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
55.73 - knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
55.74 - for (var eventType in knownEvents) {
55.75 - var knownEventsForType = knownEvents[eventType];
55.76 - if (knownEventsForType.length) {
55.77 - for (var i = 0, j = knownEventsForType.length; i < j; i++)
55.78 - knownEventTypesByEventName[knownEventsForType[i]] = eventType;
55.79 - }
55.80 - }
55.81 - var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
55.82 -
55.83 - // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
55.84 - // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
55.85 - // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
55.86 - // If there is a future need to detect specific versions of IE10+, we will amend this.
55.87 - var ieVersion = (function() {
55.88 - var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
55.89 -
55.90 - // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
55.91 - while (
55.92 - div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
55.93 - iElems[0]
55.94 - );
55.95 - return version > 4 ? version : undefined;
55.96 - }());
55.97 - var isIe6 = ieVersion === 6,
55.98 - isIe7 = ieVersion === 7;
55.99 -
55.100 - function isClickOnCheckableElement(element, eventType) {
55.101 - if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
55.102 - if (eventType.toLowerCase() != "click") return false;
55.103 - var inputType = element.type;
55.104 - return (inputType == "checkbox") || (inputType == "radio");
55.105 - }
55.106 -
55.107 - return {
55.108 - fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
55.109 -
55.110 - arrayForEach: function (array, action) {
55.111 - for (var i = 0, j = array.length; i < j; i++)
55.112 - action(array[i]);
55.113 - },
55.114 -
55.115 - arrayIndexOf: function (array, item) {
55.116 - if (typeof Array.prototype.indexOf == "function")
55.117 - return Array.prototype.indexOf.call(array, item);
55.118 - for (var i = 0, j = array.length; i < j; i++)
55.119 - if (array[i] === item)
55.120 - return i;
55.121 - return -1;
55.122 - },
55.123 -
55.124 - arrayFirst: function (array, predicate, predicateOwner) {
55.125 - for (var i = 0, j = array.length; i < j; i++)
55.126 - if (predicate.call(predicateOwner, array[i]))
55.127 - return array[i];
55.128 - return null;
55.129 - },
55.130 -
55.131 - arrayRemoveItem: function (array, itemToRemove) {
55.132 - var index = ko.utils.arrayIndexOf(array, itemToRemove);
55.133 - if (index >= 0)
55.134 - array.splice(index, 1);
55.135 - },
55.136 -
55.137 - arrayGetDistinctValues: function (array) {
55.138 - array = array || [];
55.139 - var result = [];
55.140 - for (var i = 0, j = array.length; i < j; i++) {
55.141 - if (ko.utils.arrayIndexOf(result, array[i]) < 0)
55.142 - result.push(array[i]);
55.143 - }
55.144 - return result;
55.145 - },
55.146 -
55.147 - arrayMap: function (array, mapping) {
55.148 - array = array || [];
55.149 - var result = [];
55.150 - for (var i = 0, j = array.length; i < j; i++)
55.151 - result.push(mapping(array[i]));
55.152 - return result;
55.153 - },
55.154 -
55.155 - arrayFilter: function (array, predicate) {
55.156 - array = array || [];
55.157 - var result = [];
55.158 - for (var i = 0, j = array.length; i < j; i++)
55.159 - if (predicate(array[i]))
55.160 - result.push(array[i]);
55.161 - return result;
55.162 - },
55.163 -
55.164 - arrayPushAll: function (array, valuesToPush) {
55.165 - if (valuesToPush instanceof Array)
55.166 - array.push.apply(array, valuesToPush);
55.167 - else
55.168 - for (var i = 0, j = valuesToPush.length; i < j; i++)
55.169 - array.push(valuesToPush[i]);
55.170 - return array;
55.171 - },
55.172 -
55.173 - extend: function (target, source) {
55.174 - if (source) {
55.175 - for(var prop in source) {
55.176 - if(source.hasOwnProperty(prop)) {
55.177 - target[prop] = source[prop];
55.178 - }
55.179 - }
55.180 - }
55.181 - return target;
55.182 - },
55.183 -
55.184 - emptyDomNode: function (domNode) {
55.185 - while (domNode.firstChild) {
55.186 - ko.removeNode(domNode.firstChild);
55.187 - }
55.188 - },
55.189 -
55.190 - moveCleanedNodesToContainerElement: function(nodes) {
55.191 - // Ensure it's a real array, as we're about to reparent the nodes and
55.192 - // we don't want the underlying collection to change while we're doing that.
55.193 - var nodesArray = ko.utils.makeArray(nodes);
55.194 -
55.195 - var container = document.createElement('div');
55.196 - for (var i = 0, j = nodesArray.length; i < j; i++) {
55.197 - container.appendChild(ko.cleanNode(nodesArray[i]));
55.198 - }
55.199 - return container;
55.200 - },
55.201 -
55.202 - cloneNodes: function (nodesArray, shouldCleanNodes) {
55.203 - for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
55.204 - var clonedNode = nodesArray[i].cloneNode(true);
55.205 - newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
55.206 - }
55.207 - return newNodesArray;
55.208 - },
55.209 -
55.210 - setDomNodeChildren: function (domNode, childNodes) {
55.211 - ko.utils.emptyDomNode(domNode);
55.212 - if (childNodes) {
55.213 - for (var i = 0, j = childNodes.length; i < j; i++)
55.214 - domNode.appendChild(childNodes[i]);
55.215 - }
55.216 - },
55.217 -
55.218 - replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
55.219 - var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
55.220 - if (nodesToReplaceArray.length > 0) {
55.221 - var insertionPoint = nodesToReplaceArray[0];
55.222 - var parent = insertionPoint.parentNode;
55.223 - for (var i = 0, j = newNodesArray.length; i < j; i++)
55.224 - parent.insertBefore(newNodesArray[i], insertionPoint);
55.225 - for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
55.226 - ko.removeNode(nodesToReplaceArray[i]);
55.227 - }
55.228 - }
55.229 - },
55.230 -
55.231 - setOptionNodeSelectionState: function (optionNode, isSelected) {
55.232 - // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
55.233 - if (ieVersion < 7)
55.234 - optionNode.setAttribute("selected", isSelected);
55.235 - else
55.236 - optionNode.selected = isSelected;
55.237 - },
55.238 -
55.239 - stringTrim: function (string) {
55.240 - return (string || "").replace(stringTrimRegex, "");
55.241 - },
55.242 -
55.243 - stringTokenize: function (string, delimiter) {
55.244 - var result = [];
55.245 - var tokens = (string || "").split(delimiter);
55.246 - for (var i = 0, j = tokens.length; i < j; i++) {
55.247 - var trimmed = ko.utils.stringTrim(tokens[i]);
55.248 - if (trimmed !== "")
55.249 - result.push(trimmed);
55.250 - }
55.251 - return result;
55.252 - },
55.253 -
55.254 - stringStartsWith: function (string, startsWith) {
55.255 - string = string || "";
55.256 - if (startsWith.length > string.length)
55.257 - return false;
55.258 - return string.substring(0, startsWith.length) === startsWith;
55.259 - },
55.260 -
55.261 - domNodeIsContainedBy: function (node, containedByNode) {
55.262 - if (containedByNode.compareDocumentPosition)
55.263 - return (containedByNode.compareDocumentPosition(node) & 16) == 16;
55.264 - while (node != null) {
55.265 - if (node == containedByNode)
55.266 - return true;
55.267 - node = node.parentNode;
55.268 - }
55.269 - return false;
55.270 - },
55.271 -
55.272 - domNodeIsAttachedToDocument: function (node) {
55.273 - return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
55.274 - },
55.275 -
55.276 - tagNameLower: function(element) {
55.277 - // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
55.278 - // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
55.279 - // we don't need to do the .toLowerCase() as it will always be lower case anyway.
55.280 - return element && element.tagName && element.tagName.toLowerCase();
55.281 - },
55.282 -
55.283 - registerEventHandler: function (element, eventType, handler) {
55.284 - var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
55.285 - if (!mustUseAttachEvent && typeof jQuery != "undefined") {
55.286 - if (isClickOnCheckableElement(element, eventType)) {
55.287 - // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
55.288 - // it toggles the element checked state *after* the click event handlers run, whereas native
55.289 - // click events toggle the checked state *before* the event handler.
55.290 - // Fix this by intecepting the handler and applying the correct checkedness before it runs.
55.291 - var originalHandler = handler;
55.292 - handler = function(event, eventData) {
55.293 - var jQuerySuppliedCheckedState = this.checked;
55.294 - if (eventData)
55.295 - this.checked = eventData.checkedStateBeforeEvent !== true;
55.296 - originalHandler.call(this, event);
55.297 - this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
55.298 - };
55.299 - }
55.300 - jQuery(element)['bind'](eventType, handler);
55.301 - } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
55.302 - element.addEventListener(eventType, handler, false);
55.303 - else if (typeof element.attachEvent != "undefined")
55.304 - element.attachEvent("on" + eventType, function (event) {
55.305 - handler.call(element, event);
55.306 - });
55.307 - else
55.308 - throw new Error("Browser doesn't support addEventListener or attachEvent");
55.309 - },
55.310 -
55.311 - triggerEvent: function (element, eventType) {
55.312 - if (!(element && element.nodeType))
55.313 - throw new Error("element must be a DOM node when calling triggerEvent");
55.314 -
55.315 - if (typeof jQuery != "undefined") {
55.316 - var eventData = [];
55.317 - if (isClickOnCheckableElement(element, eventType)) {
55.318 - // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
55.319 - eventData.push({ checkedStateBeforeEvent: element.checked });
55.320 - }
55.321 - jQuery(element)['trigger'](eventType, eventData);
55.322 - } else if (typeof document.createEvent == "function") {
55.323 - if (typeof element.dispatchEvent == "function") {
55.324 - var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
55.325 - var event = document.createEvent(eventCategory);
55.326 - event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
55.327 - element.dispatchEvent(event);
55.328 - }
55.329 - else
55.330 - throw new Error("The supplied element doesn't support dispatchEvent");
55.331 - } else if (typeof element.fireEvent != "undefined") {
55.332 - // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
55.333 - // so to make it consistent, we'll do it manually here
55.334 - if (isClickOnCheckableElement(element, eventType))
55.335 - element.checked = element.checked !== true;
55.336 - element.fireEvent("on" + eventType);
55.337 - }
55.338 - else
55.339 - throw new Error("Browser doesn't support triggering events");
55.340 - },
55.341 -
55.342 - unwrapObservable: function (value) {
55.343 - return ko.isObservable(value) ? value() : value;
55.344 - },
55.345 -
55.346 - peekObservable: function (value) {
55.347 - return ko.isObservable(value) ? value.peek() : value;
55.348 - },
55.349 -
55.350 - toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
55.351 - if (classNames) {
55.352 - var cssClassNameRegex = /[\w-]+/g,
55.353 - currentClassNames = node.className.match(cssClassNameRegex) || [];
55.354 - ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
55.355 - var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
55.356 - if (indexOfClass >= 0) {
55.357 - if (!shouldHaveClass)
55.358 - currentClassNames.splice(indexOfClass, 1);
55.359 - } else {
55.360 - if (shouldHaveClass)
55.361 - currentClassNames.push(className);
55.362 - }
55.363 - });
55.364 - node.className = currentClassNames.join(" ");
55.365 - }
55.366 - },
55.367 -
55.368 - setTextContent: function(element, textContent) {
55.369 - var value = ko.utils.unwrapObservable(textContent);
55.370 - if ((value === null) || (value === undefined))
55.371 - value = "";
55.372 -
55.373 - if (element.nodeType === 3) {
55.374 - element.data = value;
55.375 - } else {
55.376 - // We need there to be exactly one child: a text node.
55.377 - // If there are no children, more than one, or if it's not a text node,
55.378 - // we'll clear everything and create a single text node.
55.379 - var innerTextNode = ko.virtualElements.firstChild(element);
55.380 - if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
55.381 - ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
55.382 - } else {
55.383 - innerTextNode.data = value;
55.384 - }
55.385 -
55.386 - ko.utils.forceRefresh(element);
55.387 - }
55.388 - },
55.389 -
55.390 - setElementName: function(element, name) {
55.391 - element.name = name;
55.392 -
55.393 - // Workaround IE 6/7 issue
55.394 - // - https://github.com/SteveSanderson/knockout/issues/197
55.395 - // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
55.396 - if (ieVersion <= 7) {
55.397 - try {
55.398 - element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
55.399 - }
55.400 - catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
55.401 - }
55.402 - },
55.403 -
55.404 - forceRefresh: function(node) {
55.405 - // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
55.406 - if (ieVersion >= 9) {
55.407 - // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
55.408 - var elem = node.nodeType == 1 ? node : node.parentNode;
55.409 - if (elem.style)
55.410 - elem.style.zoom = elem.style.zoom;
55.411 - }
55.412 - },
55.413 -
55.414 - ensureSelectElementIsRenderedCorrectly: function(selectElement) {
55.415 - // 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.
55.416 - // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
55.417 - if (ieVersion >= 9) {
55.418 - var originalWidth = selectElement.style.width;
55.419 - selectElement.style.width = 0;
55.420 - selectElement.style.width = originalWidth;
55.421 - }
55.422 - },
55.423 -
55.424 - range: function (min, max) {
55.425 - min = ko.utils.unwrapObservable(min);
55.426 - max = ko.utils.unwrapObservable(max);
55.427 - var result = [];
55.428 - for (var i = min; i <= max; i++)
55.429 - result.push(i);
55.430 - return result;
55.431 - },
55.432 -
55.433 - makeArray: function(arrayLikeObject) {
55.434 - var result = [];
55.435 - for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
55.436 - result.push(arrayLikeObject[i]);
55.437 - };
55.438 - return result;
55.439 - },
55.440 -
55.441 - isIe6 : isIe6,
55.442 - isIe7 : isIe7,
55.443 - ieVersion : ieVersion,
55.444 -
55.445 - getFormFields: function(form, fieldName) {
55.446 - var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
55.447 - var isMatchingField = (typeof fieldName == 'string')
55.448 - ? function(field) { return field.name === fieldName }
55.449 - : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
55.450 - var matches = [];
55.451 - for (var i = fields.length - 1; i >= 0; i--) {
55.452 - if (isMatchingField(fields[i]))
55.453 - matches.push(fields[i]);
55.454 - };
55.455 - return matches;
55.456 - },
55.457 -
55.458 - parseJson: function (jsonString) {
55.459 - if (typeof jsonString == "string") {
55.460 - jsonString = ko.utils.stringTrim(jsonString);
55.461 - if (jsonString) {
55.462 - if (window.JSON && window.JSON.parse) // Use native parsing where available
55.463 - return window.JSON.parse(jsonString);
55.464 - return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
55.465 - }
55.466 - }
55.467 - return null;
55.468 - },
55.469 -
55.470 - stringifyJson: function (data, replacer, space) { // replacer and space are optional
55.471 - if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
55.472 - 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");
55.473 - return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
55.474 - },
55.475 -
55.476 - postJson: function (urlOrForm, data, options) {
55.477 - options = options || {};
55.478 - var params = options['params'] || {};
55.479 - var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
55.480 - var url = urlOrForm;
55.481 -
55.482 - // If we were given a form, use its 'action' URL and pick out any requested field values
55.483 - if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
55.484 - var originalForm = urlOrForm;
55.485 - url = originalForm.action;
55.486 - for (var i = includeFields.length - 1; i >= 0; i--) {
55.487 - var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
55.488 - for (var j = fields.length - 1; j >= 0; j--)
55.489 - params[fields[j].name] = fields[j].value;
55.490 - }
55.491 - }
55.492 -
55.493 - data = ko.utils.unwrapObservable(data);
55.494 - var form = document.createElement("form");
55.495 - form.style.display = "none";
55.496 - form.action = url;
55.497 - form.method = "post";
55.498 - for (var key in data) {
55.499 - var input = document.createElement("input");
55.500 - input.name = key;
55.501 - input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
55.502 - form.appendChild(input);
55.503 - }
55.504 - for (var key in params) {
55.505 - var input = document.createElement("input");
55.506 - input.name = key;
55.507 - input.value = params[key];
55.508 - form.appendChild(input);
55.509 - }
55.510 - document.body.appendChild(form);
55.511 - options['submitter'] ? options['submitter'](form) : form.submit();
55.512 - setTimeout(function () { form.parentNode.removeChild(form); }, 0);
55.513 - }
55.514 - }
55.515 -})();
55.516 -
55.517 -ko.exportSymbol('utils', ko.utils);
55.518 -ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
55.519 -ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
55.520 -ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
55.521 -ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
55.522 -ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
55.523 -ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
55.524 -ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
55.525 -ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
55.526 -ko.exportSymbol('utils.extend', ko.utils.extend);
55.527 -ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
55.528 -ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
55.529 -ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
55.530 -ko.exportSymbol('utils.postJson', ko.utils.postJson);
55.531 -ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
55.532 -ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
55.533 -ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
55.534 -ko.exportSymbol('utils.range', ko.utils.range);
55.535 -ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
55.536 -ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
55.537 -ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
55.538 -
55.539 -if (!Function.prototype['bind']) {
55.540 - // 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)
55.541 - // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
55.542 - Function.prototype['bind'] = function (object) {
55.543 - var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
55.544 - return function () {
55.545 - return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
55.546 - };
55.547 - };
55.548 -}
55.549 -
55.550 -ko.utils.domData = new (function () {
55.551 - var uniqueId = 0;
55.552 - var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
55.553 - var dataStore = {};
55.554 - return {
55.555 - get: function (node, key) {
55.556 - var allDataForNode = ko.utils.domData.getAll(node, false);
55.557 - return allDataForNode === undefined ? undefined : allDataForNode[key];
55.558 - },
55.559 - set: function (node, key, value) {
55.560 - if (value === undefined) {
55.561 - // Make sure we don't actually create a new domData key if we are actually deleting a value
55.562 - if (ko.utils.domData.getAll(node, false) === undefined)
55.563 - return;
55.564 - }
55.565 - var allDataForNode = ko.utils.domData.getAll(node, true);
55.566 - allDataForNode[key] = value;
55.567 - },
55.568 - getAll: function (node, createIfNotFound) {
55.569 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
55.570 - var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
55.571 - if (!hasExistingDataStore) {
55.572 - if (!createIfNotFound)
55.573 - return undefined;
55.574 - dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
55.575 - dataStore[dataStoreKey] = {};
55.576 - }
55.577 - return dataStore[dataStoreKey];
55.578 - },
55.579 - clear: function (node) {
55.580 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
55.581 - if (dataStoreKey) {
55.582 - delete dataStore[dataStoreKey];
55.583 - node[dataStoreKeyExpandoPropertyName] = null;
55.584 - return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
55.585 - }
55.586 - return false;
55.587 - }
55.588 - }
55.589 -})();
55.590 -
55.591 -ko.exportSymbol('utils.domData', ko.utils.domData);
55.592 -ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
55.593 -
55.594 -ko.utils.domNodeDisposal = new (function () {
55.595 - var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
55.596 - var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
55.597 - var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
55.598 -
55.599 - function getDisposeCallbacksCollection(node, createIfNotFound) {
55.600 - var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
55.601 - if ((allDisposeCallbacks === undefined) && createIfNotFound) {
55.602 - allDisposeCallbacks = [];
55.603 - ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
55.604 - }
55.605 - return allDisposeCallbacks;
55.606 - }
55.607 - function destroyCallbacksCollection(node) {
55.608 - ko.utils.domData.set(node, domDataKey, undefined);
55.609 - }
55.610 -
55.611 - function cleanSingleNode(node) {
55.612 - // Run all the dispose callbacks
55.613 - var callbacks = getDisposeCallbacksCollection(node, false);
55.614 - if (callbacks) {
55.615 - callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
55.616 - for (var i = 0; i < callbacks.length; i++)
55.617 - callbacks[i](node);
55.618 - }
55.619 -
55.620 - // Also erase the DOM data
55.621 - ko.utils.domData.clear(node);
55.622 -
55.623 - // Special support for jQuery here because it's so commonly used.
55.624 - // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
55.625 - // so notify it to tear down any resources associated with the node & descendants here.
55.626 - if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
55.627 - jQuery['cleanData']([node]);
55.628 -
55.629 - // Also clear any immediate-child comment nodes, as these wouldn't have been found by
55.630 - // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
55.631 - if (cleanableNodeTypesWithDescendants[node.nodeType])
55.632 - cleanImmediateCommentTypeChildren(node);
55.633 - }
55.634 -
55.635 - function cleanImmediateCommentTypeChildren(nodeWithChildren) {
55.636 - var child, nextChild = nodeWithChildren.firstChild;
55.637 - while (child = nextChild) {
55.638 - nextChild = child.nextSibling;
55.639 - if (child.nodeType === 8)
55.640 - cleanSingleNode(child);
55.641 - }
55.642 - }
55.643 -
55.644 - return {
55.645 - addDisposeCallback : function(node, callback) {
55.646 - if (typeof callback != "function")
55.647 - throw new Error("Callback must be a function");
55.648 - getDisposeCallbacksCollection(node, true).push(callback);
55.649 - },
55.650 -
55.651 - removeDisposeCallback : function(node, callback) {
55.652 - var callbacksCollection = getDisposeCallbacksCollection(node, false);
55.653 - if (callbacksCollection) {
55.654 - ko.utils.arrayRemoveItem(callbacksCollection, callback);
55.655 - if (callbacksCollection.length == 0)
55.656 - destroyCallbacksCollection(node);
55.657 - }
55.658 - },
55.659 -
55.660 - cleanNode : function(node) {
55.661 - // First clean this node, where applicable
55.662 - if (cleanableNodeTypes[node.nodeType]) {
55.663 - cleanSingleNode(node);
55.664 -
55.665 - // ... then its descendants, where applicable
55.666 - if (cleanableNodeTypesWithDescendants[node.nodeType]) {
55.667 - // Clone the descendants list in case it changes during iteration
55.668 - var descendants = [];
55.669 - ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
55.670 - for (var i = 0, j = descendants.length; i < j; i++)
55.671 - cleanSingleNode(descendants[i]);
55.672 - }
55.673 - }
55.674 - return node;
55.675 - },
55.676 -
55.677 - removeNode : function(node) {
55.678 - ko.cleanNode(node);
55.679 - if (node.parentNode)
55.680 - node.parentNode.removeChild(node);
55.681 - }
55.682 - }
55.683 -})();
55.684 -ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
55.685 -ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
55.686 -ko.exportSymbol('cleanNode', ko.cleanNode);
55.687 -ko.exportSymbol('removeNode', ko.removeNode);
55.688 -ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
55.689 -ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
55.690 -ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
55.691 -(function () {
55.692 - var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
55.693 -
55.694 - function simpleHtmlParse(html) {
55.695 - // Based on jQuery's "clean" function, but only accounting for table-related elements.
55.696 - // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
55.697 -
55.698 - // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
55.699 - // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
55.700 - // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
55.701 - // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
55.702 -
55.703 - // Trim whitespace, otherwise indexOf won't work as expected
55.704 - var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
55.705 -
55.706 - // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
55.707 - var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
55.708 - !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
55.709 - (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
55.710 - /* anything else */ [0, "", ""];
55.711 -
55.712 - // Go to html and back, then peel off extra wrappers
55.713 - // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
55.714 - var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
55.715 - if (typeof window['innerShiv'] == "function") {
55.716 - div.appendChild(window['innerShiv'](markup));
55.717 - } else {
55.718 - div.innerHTML = markup;
55.719 - }
55.720 -
55.721 - // Move to the right depth
55.722 - while (wrap[0]--)
55.723 - div = div.lastChild;
55.724 -
55.725 - return ko.utils.makeArray(div.lastChild.childNodes);
55.726 - }
55.727 -
55.728 - function jQueryHtmlParse(html) {
55.729 - // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
55.730 - if (jQuery['parseHTML']) {
55.731 - return jQuery['parseHTML'](html);
55.732 - } else {
55.733 - // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
55.734 - var elems = jQuery['clean']([html]);
55.735 -
55.736 - // 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.
55.737 - // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
55.738 - // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
55.739 - if (elems && elems[0]) {
55.740 - // Find the top-most parent element that's a direct child of a document fragment
55.741 - var elem = elems[0];
55.742 - while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
55.743 - elem = elem.parentNode;
55.744 - // ... then detach it
55.745 - if (elem.parentNode)
55.746 - elem.parentNode.removeChild(elem);
55.747 - }
55.748 -
55.749 - return elems;
55.750 - }
55.751 - }
55.752 -
55.753 - ko.utils.parseHtmlFragment = function(html) {
55.754 - return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
55.755 - : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
55.756 - };
55.757 -
55.758 - ko.utils.setHtml = function(node, html) {
55.759 - ko.utils.emptyDomNode(node);
55.760 -
55.761 - // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
55.762 - html = ko.utils.unwrapObservable(html);
55.763 -
55.764 - if ((html !== null) && (html !== undefined)) {
55.765 - if (typeof html != 'string')
55.766 - html = html.toString();
55.767 -
55.768 - // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
55.769 - // for example <tr> elements which are not normally allowed to exist on their own.
55.770 - // If you've referenced jQuery we'll use that rather than duplicating its code.
55.771 - if (typeof jQuery != 'undefined') {
55.772 - jQuery(node)['html'](html);
55.773 - } else {
55.774 - // ... otherwise, use KO's own parsing logic.
55.775 - var parsedNodes = ko.utils.parseHtmlFragment(html);
55.776 - for (var i = 0; i < parsedNodes.length; i++)
55.777 - node.appendChild(parsedNodes[i]);
55.778 - }
55.779 - }
55.780 - };
55.781 -})();
55.782 -
55.783 -ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
55.784 -ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
55.785 -
55.786 -ko.memoization = (function () {
55.787 - var memos = {};
55.788 -
55.789 - function randomMax8HexChars() {
55.790 - return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
55.791 - }
55.792 - function generateRandomId() {
55.793 - return randomMax8HexChars() + randomMax8HexChars();
55.794 - }
55.795 - function findMemoNodes(rootNode, appendToArray) {
55.796 - if (!rootNode)
55.797 - return;
55.798 - if (rootNode.nodeType == 8) {
55.799 - var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
55.800 - if (memoId != null)
55.801 - appendToArray.push({ domNode: rootNode, memoId: memoId });
55.802 - } else if (rootNode.nodeType == 1) {
55.803 - for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
55.804 - findMemoNodes(childNodes[i], appendToArray);
55.805 - }
55.806 - }
55.807 -
55.808 - return {
55.809 - memoize: function (callback) {
55.810 - if (typeof callback != "function")
55.811 - throw new Error("You can only pass a function to ko.memoization.memoize()");
55.812 - var memoId = generateRandomId();
55.813 - memos[memoId] = callback;
55.814 - return "<!--[ko_memo:" + memoId + "]-->";
55.815 - },
55.816 -
55.817 - unmemoize: function (memoId, callbackParams) {
55.818 - var callback = memos[memoId];
55.819 - if (callback === undefined)
55.820 - throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
55.821 - try {
55.822 - callback.apply(null, callbackParams || []);
55.823 - return true;
55.824 - }
55.825 - finally { delete memos[memoId]; }
55.826 - },
55.827 -
55.828 - unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
55.829 - var memos = [];
55.830 - findMemoNodes(domNode, memos);
55.831 - for (var i = 0, j = memos.length; i < j; i++) {
55.832 - var node = memos[i].domNode;
55.833 - var combinedParams = [node];
55.834 - if (extraCallbackParamsArray)
55.835 - ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
55.836 - ko.memoization.unmemoize(memos[i].memoId, combinedParams);
55.837 - node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
55.838 - if (node.parentNode)
55.839 - 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)
55.840 - }
55.841 - },
55.842 -
55.843 - parseMemoText: function (memoText) {
55.844 - var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
55.845 - return match ? match[1] : null;
55.846 - }
55.847 - };
55.848 -})();
55.849 -
55.850 -ko.exportSymbol('memoization', ko.memoization);
55.851 -ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
55.852 -ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
55.853 -ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
55.854 -ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
55.855 -ko.extenders = {
55.856 - 'throttle': function(target, timeout) {
55.857 - // Throttling means two things:
55.858 -
55.859 - // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
55.860 - // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
55.861 - target['throttleEvaluation'] = timeout;
55.862 -
55.863 - // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
55.864 - // so the target cannot change value synchronously or faster than a certain rate
55.865 - var writeTimeoutInstance = null;
55.866 - return ko.dependentObservable({
55.867 - 'read': target,
55.868 - 'write': function(value) {
55.869 - clearTimeout(writeTimeoutInstance);
55.870 - writeTimeoutInstance = setTimeout(function() {
55.871 - target(value);
55.872 - }, timeout);
55.873 - }
55.874 - });
55.875 - },
55.876 -
55.877 - 'notify': function(target, notifyWhen) {
55.878 - target["equalityComparer"] = notifyWhen == "always"
55.879 - ? function() { return false } // Treat all values as not equal
55.880 - : ko.observable["fn"]["equalityComparer"];
55.881 - return target;
55.882 - }
55.883 -};
55.884 -
55.885 -function applyExtenders(requestedExtenders) {
55.886 - var target = this;
55.887 - if (requestedExtenders) {
55.888 - for (var key in requestedExtenders) {
55.889 - var extenderHandler = ko.extenders[key];
55.890 - if (typeof extenderHandler == 'function') {
55.891 - target = extenderHandler(target, requestedExtenders[key]);
55.892 - }
55.893 - }
55.894 - }
55.895 - return target;
55.896 -}
55.897 -
55.898 -ko.exportSymbol('extenders', ko.extenders);
55.899 -
55.900 -ko.subscription = function (target, callback, disposeCallback) {
55.901 - this.target = target;
55.902 - this.callback = callback;
55.903 - this.disposeCallback = disposeCallback;
55.904 - ko.exportProperty(this, 'dispose', this.dispose);
55.905 -};
55.906 -ko.subscription.prototype.dispose = function () {
55.907 - this.isDisposed = true;
55.908 - this.disposeCallback();
55.909 -};
55.910 -
55.911 -ko.subscribable = function () {
55.912 - this._subscriptions = {};
55.913 -
55.914 - ko.utils.extend(this, ko.subscribable['fn']);
55.915 - ko.exportProperty(this, 'subscribe', this.subscribe);
55.916 - ko.exportProperty(this, 'extend', this.extend);
55.917 - ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
55.918 -}
55.919 -
55.920 -var defaultEvent = "change";
55.921 -
55.922 -ko.subscribable['fn'] = {
55.923 - subscribe: function (callback, callbackTarget, event) {
55.924 - event = event || defaultEvent;
55.925 - var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
55.926 -
55.927 - var subscription = new ko.subscription(this, boundCallback, function () {
55.928 - ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
55.929 - }.bind(this));
55.930 -
55.931 - if (!this._subscriptions[event])
55.932 - this._subscriptions[event] = [];
55.933 - this._subscriptions[event].push(subscription);
55.934 - return subscription;
55.935 - },
55.936 -
55.937 - "notifySubscribers": function (valueToNotify, event) {
55.938 - event = event || defaultEvent;
55.939 - if (this._subscriptions[event]) {
55.940 - ko.dependencyDetection.ignore(function() {
55.941 - ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
55.942 - // In case a subscription was disposed during the arrayForEach cycle, check
55.943 - // for isDisposed on each subscription before invoking its callback
55.944 - if (subscription && (subscription.isDisposed !== true))
55.945 - subscription.callback(valueToNotify);
55.946 - });
55.947 - }, this);
55.948 - }
55.949 - },
55.950 -
55.951 - getSubscriptionsCount: function () {
55.952 - var total = 0;
55.953 - for (var eventName in this._subscriptions) {
55.954 - if (this._subscriptions.hasOwnProperty(eventName))
55.955 - total += this._subscriptions[eventName].length;
55.956 - }
55.957 - return total;
55.958 - },
55.959 -
55.960 - extend: applyExtenders
55.961 -};
55.962 -
55.963 -
55.964 -ko.isSubscribable = function (instance) {
55.965 - return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
55.966 -};
55.967 -
55.968 -ko.exportSymbol('subscribable', ko.subscribable);
55.969 -ko.exportSymbol('isSubscribable', ko.isSubscribable);
55.970 -
55.971 -ko.dependencyDetection = (function () {
55.972 - var _frames = [];
55.973 -
55.974 - return {
55.975 - begin: function (callback) {
55.976 - _frames.push({ callback: callback, distinctDependencies:[] });
55.977 - },
55.978 -
55.979 - end: function () {
55.980 - _frames.pop();
55.981 - },
55.982 -
55.983 - registerDependency: function (subscribable) {
55.984 - if (!ko.isSubscribable(subscribable))
55.985 - throw new Error("Only subscribable things can act as dependencies");
55.986 - if (_frames.length > 0) {
55.987 - var topFrame = _frames[_frames.length - 1];
55.988 - if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
55.989 - return;
55.990 - topFrame.distinctDependencies.push(subscribable);
55.991 - topFrame.callback(subscribable);
55.992 - }
55.993 - },
55.994 -
55.995 - ignore: function(callback, callbackTarget, callbackArgs) {
55.996 - try {
55.997 - _frames.push(null);
55.998 - return callback.apply(callbackTarget, callbackArgs || []);
55.999 - } finally {
55.1000 - _frames.pop();
55.1001 - }
55.1002 - }
55.1003 - };
55.1004 -})();
55.1005 -var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
55.1006 -
55.1007 -ko.observable = function (initialValue) {
55.1008 - var _latestValue = initialValue;
55.1009 -
55.1010 - function observable() {
55.1011 - if (arguments.length > 0) {
55.1012 - // Write
55.1013 -
55.1014 - // Ignore writes if the value hasn't changed
55.1015 - if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
55.1016 - observable.valueWillMutate();
55.1017 - _latestValue = arguments[0];
55.1018 - if (DEBUG) observable._latestValue = _latestValue;
55.1019 - observable.valueHasMutated();
55.1020 - }
55.1021 - return this; // Permits chained assignments
55.1022 - }
55.1023 - else {
55.1024 - // Read
55.1025 - ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
55.1026 - return _latestValue;
55.1027 - }
55.1028 - }
55.1029 - if (DEBUG) observable._latestValue = _latestValue;
55.1030 - ko.subscribable.call(observable);
55.1031 - observable.peek = function() { return _latestValue };
55.1032 - observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
55.1033 - observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
55.1034 - ko.utils.extend(observable, ko.observable['fn']);
55.1035 -
55.1036 - ko.exportProperty(observable, 'peek', observable.peek);
55.1037 - ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
55.1038 - ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
55.1039 -
55.1040 - return observable;
55.1041 -}
55.1042 -
55.1043 -ko.observable['fn'] = {
55.1044 - "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
55.1045 - var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
55.1046 - return oldValueIsPrimitive ? (a === b) : false;
55.1047 - }
55.1048 -};
55.1049 -
55.1050 -var protoProperty = ko.observable.protoProperty = "__ko_proto__";
55.1051 -ko.observable['fn'][protoProperty] = ko.observable;
55.1052 -
55.1053 -ko.hasPrototype = function(instance, prototype) {
55.1054 - if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
55.1055 - if (instance[protoProperty] === prototype) return true;
55.1056 - return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
55.1057 -};
55.1058 -
55.1059 -ko.isObservable = function (instance) {
55.1060 - return ko.hasPrototype(instance, ko.observable);
55.1061 -}
55.1062 -ko.isWriteableObservable = function (instance) {
55.1063 - // Observable
55.1064 - if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
55.1065 - return true;
55.1066 - // Writeable dependent observable
55.1067 - if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
55.1068 - return true;
55.1069 - // Anything else
55.1070 - return false;
55.1071 -}
55.1072 -
55.1073 -
55.1074 -ko.exportSymbol('observable', ko.observable);
55.1075 -ko.exportSymbol('isObservable', ko.isObservable);
55.1076 -ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
55.1077 -ko.observableArray = function (initialValues) {
55.1078 - if (arguments.length == 0) {
55.1079 - // Zero-parameter constructor initializes to empty array
55.1080 - initialValues = [];
55.1081 - }
55.1082 - if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
55.1083 - throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
55.1084 -
55.1085 - var result = ko.observable(initialValues);
55.1086 - ko.utils.extend(result, ko.observableArray['fn']);
55.1087 - return result;
55.1088 -}
55.1089 -
55.1090 -ko.observableArray['fn'] = {
55.1091 - 'remove': function (valueOrPredicate) {
55.1092 - var underlyingArray = this.peek();
55.1093 - var removedValues = [];
55.1094 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
55.1095 - for (var i = 0; i < underlyingArray.length; i++) {
55.1096 - var value = underlyingArray[i];
55.1097 - if (predicate(value)) {
55.1098 - if (removedValues.length === 0) {
55.1099 - this.valueWillMutate();
55.1100 - }
55.1101 - removedValues.push(value);
55.1102 - underlyingArray.splice(i, 1);
55.1103 - i--;
55.1104 - }
55.1105 - }
55.1106 - if (removedValues.length) {
55.1107 - this.valueHasMutated();
55.1108 - }
55.1109 - return removedValues;
55.1110 - },
55.1111 -
55.1112 - 'removeAll': function (arrayOfValues) {
55.1113 - // If you passed zero args, we remove everything
55.1114 - if (arrayOfValues === undefined) {
55.1115 - var underlyingArray = this.peek();
55.1116 - var allValues = underlyingArray.slice(0);
55.1117 - this.valueWillMutate();
55.1118 - underlyingArray.splice(0, underlyingArray.length);
55.1119 - this.valueHasMutated();
55.1120 - return allValues;
55.1121 - }
55.1122 - // If you passed an arg, we interpret it as an array of entries to remove
55.1123 - if (!arrayOfValues)
55.1124 - return [];
55.1125 - return this['remove'](function (value) {
55.1126 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
55.1127 - });
55.1128 - },
55.1129 -
55.1130 - 'destroy': function (valueOrPredicate) {
55.1131 - var underlyingArray = this.peek();
55.1132 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
55.1133 - this.valueWillMutate();
55.1134 - for (var i = underlyingArray.length - 1; i >= 0; i--) {
55.1135 - var value = underlyingArray[i];
55.1136 - if (predicate(value))
55.1137 - underlyingArray[i]["_destroy"] = true;
55.1138 - }
55.1139 - this.valueHasMutated();
55.1140 - },
55.1141 -
55.1142 - 'destroyAll': function (arrayOfValues) {
55.1143 - // If you passed zero args, we destroy everything
55.1144 - if (arrayOfValues === undefined)
55.1145 - return this['destroy'](function() { return true });
55.1146 -
55.1147 - // If you passed an arg, we interpret it as an array of entries to destroy
55.1148 - if (!arrayOfValues)
55.1149 - return [];
55.1150 - return this['destroy'](function (value) {
55.1151 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
55.1152 - });
55.1153 - },
55.1154 -
55.1155 - 'indexOf': function (item) {
55.1156 - var underlyingArray = this();
55.1157 - return ko.utils.arrayIndexOf(underlyingArray, item);
55.1158 - },
55.1159 -
55.1160 - 'replace': function(oldItem, newItem) {
55.1161 - var index = this['indexOf'](oldItem);
55.1162 - if (index >= 0) {
55.1163 - this.valueWillMutate();
55.1164 - this.peek()[index] = newItem;
55.1165 - this.valueHasMutated();
55.1166 - }
55.1167 - }
55.1168 -}
55.1169 -
55.1170 -// Populate ko.observableArray.fn with read/write functions from native arrays
55.1171 -// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
55.1172 -// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
55.1173 -ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
55.1174 - ko.observableArray['fn'][methodName] = function () {
55.1175 - // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
55.1176 - // (for consistency with mutating regular observables)
55.1177 - var underlyingArray = this.peek();
55.1178 - this.valueWillMutate();
55.1179 - var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
55.1180 - this.valueHasMutated();
55.1181 - return methodCallResult;
55.1182 - };
55.1183 -});
55.1184 -
55.1185 -// Populate ko.observableArray.fn with read-only functions from native arrays
55.1186 -ko.utils.arrayForEach(["slice"], function (methodName) {
55.1187 - ko.observableArray['fn'][methodName] = function () {
55.1188 - var underlyingArray = this();
55.1189 - return underlyingArray[methodName].apply(underlyingArray, arguments);
55.1190 - };
55.1191 -});
55.1192 -
55.1193 -ko.exportSymbol('observableArray', ko.observableArray);
55.1194 -ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
55.1195 - var _latestValue,
55.1196 - _hasBeenEvaluated = false,
55.1197 - _isBeingEvaluated = false,
55.1198 - readFunction = evaluatorFunctionOrOptions;
55.1199 -
55.1200 - if (readFunction && typeof readFunction == "object") {
55.1201 - // Single-parameter syntax - everything is on this "options" param
55.1202 - options = readFunction;
55.1203 - readFunction = options["read"];
55.1204 - } else {
55.1205 - // Multi-parameter syntax - construct the options according to the params passed
55.1206 - options = options || {};
55.1207 - if (!readFunction)
55.1208 - readFunction = options["read"];
55.1209 - }
55.1210 - if (typeof readFunction != "function")
55.1211 - throw new Error("Pass a function that returns the value of the ko.computed");
55.1212 -
55.1213 - function addSubscriptionToDependency(subscribable) {
55.1214 - _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
55.1215 - }
55.1216 -
55.1217 - function disposeAllSubscriptionsToDependencies() {
55.1218 - ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
55.1219 - subscription.dispose();
55.1220 - });
55.1221 - _subscriptionsToDependencies = [];
55.1222 - }
55.1223 -
55.1224 - function evaluatePossiblyAsync() {
55.1225 - var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
55.1226 - if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
55.1227 - clearTimeout(evaluationTimeoutInstance);
55.1228 - evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
55.1229 - } else
55.1230 - evaluateImmediate();
55.1231 - }
55.1232 -
55.1233 - function evaluateImmediate() {
55.1234 - if (_isBeingEvaluated) {
55.1235 - // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
55.1236 - // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
55.1237 - // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
55.1238 - // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
55.1239 - return;
55.1240 - }
55.1241 -
55.1242 - // Don't dispose on first evaluation, because the "disposeWhen" callback might
55.1243 - // e.g., dispose when the associated DOM element isn't in the doc, and it's not
55.1244 - // going to be in the doc until *after* the first evaluation
55.1245 - if (_hasBeenEvaluated && disposeWhen()) {
55.1246 - dispose();
55.1247 - return;
55.1248 - }
55.1249 -
55.1250 - _isBeingEvaluated = true;
55.1251 - try {
55.1252 - // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
55.1253 - // Then, during evaluation, we cross off any that are in fact still being used.
55.1254 - var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
55.1255 -
55.1256 - ko.dependencyDetection.begin(function(subscribable) {
55.1257 - var inOld;
55.1258 - if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
55.1259 - disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
55.1260 - else
55.1261 - addSubscriptionToDependency(subscribable); // Brand new subscription - add it
55.1262 - });
55.1263 -
55.1264 - var newValue = readFunction.call(evaluatorFunctionTarget);
55.1265 -
55.1266 - // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
55.1267 - for (var i = disposalCandidates.length - 1; i >= 0; i--) {
55.1268 - if (disposalCandidates[i])
55.1269 - _subscriptionsToDependencies.splice(i, 1)[0].dispose();
55.1270 - }
55.1271 - _hasBeenEvaluated = true;
55.1272 -
55.1273 - dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
55.1274 - _latestValue = newValue;
55.1275 - if (DEBUG) dependentObservable._latestValue = _latestValue;
55.1276 - } finally {
55.1277 - ko.dependencyDetection.end();
55.1278 - }
55.1279 -
55.1280 - dependentObservable["notifySubscribers"](_latestValue);
55.1281 - _isBeingEvaluated = false;
55.1282 - if (!_subscriptionsToDependencies.length)
55.1283 - dispose();
55.1284 - }
55.1285 -
55.1286 - function dependentObservable() {
55.1287 - if (arguments.length > 0) {
55.1288 - if (typeof writeFunction === "function") {
55.1289 - // Writing a value
55.1290 - writeFunction.apply(evaluatorFunctionTarget, arguments);
55.1291 - } else {
55.1292 - 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.");
55.1293 - }
55.1294 - return this; // Permits chained assignments
55.1295 - } else {
55.1296 - // Reading the value
55.1297 - if (!_hasBeenEvaluated)
55.1298 - evaluateImmediate();
55.1299 - ko.dependencyDetection.registerDependency(dependentObservable);
55.1300 - return _latestValue;
55.1301 - }
55.1302 - }
55.1303 -
55.1304 - function peek() {
55.1305 - if (!_hasBeenEvaluated)
55.1306 - evaluateImmediate();
55.1307 - return _latestValue;
55.1308 - }
55.1309 -
55.1310 - function isActive() {
55.1311 - return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
55.1312 - }
55.1313 -
55.1314 - // By here, "options" is always non-null
55.1315 - var writeFunction = options["write"],
55.1316 - disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
55.1317 - disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
55.1318 - dispose = disposeAllSubscriptionsToDependencies,
55.1319 - _subscriptionsToDependencies = [],
55.1320 - evaluationTimeoutInstance = null;
55.1321 -
55.1322 - if (!evaluatorFunctionTarget)
55.1323 - evaluatorFunctionTarget = options["owner"];
55.1324 -
55.1325 - dependentObservable.peek = peek;
55.1326 - dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
55.1327 - dependentObservable.hasWriteFunction = typeof options["write"] === "function";
55.1328 - dependentObservable.dispose = function () { dispose(); };
55.1329 - dependentObservable.isActive = isActive;
55.1330 - dependentObservable.valueHasMutated = function() {
55.1331 - _hasBeenEvaluated = false;
55.1332 - evaluateImmediate();
55.1333 - };
55.1334 -
55.1335 - ko.subscribable.call(dependentObservable);
55.1336 - ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
55.1337 -
55.1338 - ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
55.1339 - ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
55.1340 - ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
55.1341 - ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
55.1342 -
55.1343 - // Evaluate, unless deferEvaluation is true
55.1344 - if (options['deferEvaluation'] !== true)
55.1345 - evaluateImmediate();
55.1346 -
55.1347 - // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
55.1348 - // But skip if isActive is false (there will never be any dependencies to dispose).
55.1349 - // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
55.1350 - // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
55.1351 - if (disposeWhenNodeIsRemoved && isActive()) {
55.1352 - dispose = function() {
55.1353 - ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
55.1354 - disposeAllSubscriptionsToDependencies();
55.1355 - };
55.1356 - ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
55.1357 - var existingDisposeWhenFunction = disposeWhen;
55.1358 - disposeWhen = function () {
55.1359 - return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
55.1360 - }
55.1361 - }
55.1362 -
55.1363 - return dependentObservable;
55.1364 -};
55.1365 -
55.1366 -ko.isComputed = function(instance) {
55.1367 - return ko.hasPrototype(instance, ko.dependentObservable);
55.1368 -};
55.1369 -
55.1370 -var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
55.1371 -ko.dependentObservable[protoProp] = ko.observable;
55.1372 -
55.1373 -ko.dependentObservable['fn'] = {};
55.1374 -ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
55.1375 -
55.1376 -ko.exportSymbol('dependentObservable', ko.dependentObservable);
55.1377 -ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
55.1378 -ko.exportSymbol('isComputed', ko.isComputed);
55.1379 -
55.1380 -(function() {
55.1381 - var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
55.1382 -
55.1383 - ko.toJS = function(rootObject) {
55.1384 - if (arguments.length == 0)
55.1385 - throw new Error("When calling ko.toJS, pass the object you want to convert.");
55.1386 -
55.1387 - // We just unwrap everything at every level in the object graph
55.1388 - return mapJsObjectGraph(rootObject, function(valueToMap) {
55.1389 - // Loop because an observable's value might in turn be another observable wrapper
55.1390 - for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
55.1391 - valueToMap = valueToMap();
55.1392 - return valueToMap;
55.1393 - });
55.1394 - };
55.1395 -
55.1396 - ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
55.1397 - var plainJavaScriptObject = ko.toJS(rootObject);
55.1398 - return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
55.1399 - };
55.1400 -
55.1401 - function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
55.1402 - visitedObjects = visitedObjects || new objectLookup();
55.1403 -
55.1404 - rootObject = mapInputCallback(rootObject);
55.1405 - var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
55.1406 - if (!canHaveProperties)
55.1407 - return rootObject;
55.1408 -
55.1409 - var outputProperties = rootObject instanceof Array ? [] : {};
55.1410 - visitedObjects.save(rootObject, outputProperties);
55.1411 -
55.1412 - visitPropertiesOrArrayEntries(rootObject, function(indexer) {
55.1413 - var propertyValue = mapInputCallback(rootObject[indexer]);
55.1414 -
55.1415 - switch (typeof propertyValue) {
55.1416 - case "boolean":
55.1417 - case "number":
55.1418 - case "string":
55.1419 - case "function":
55.1420 - outputProperties[indexer] = propertyValue;
55.1421 - break;
55.1422 - case "object":
55.1423 - case "undefined":
55.1424 - var previouslyMappedValue = visitedObjects.get(propertyValue);
55.1425 - outputProperties[indexer] = (previouslyMappedValue !== undefined)
55.1426 - ? previouslyMappedValue
55.1427 - : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
55.1428 - break;
55.1429 - }
55.1430 - });
55.1431 -
55.1432 - return outputProperties;
55.1433 - }
55.1434 -
55.1435 - function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
55.1436 - if (rootObject instanceof Array) {
55.1437 - for (var i = 0; i < rootObject.length; i++)
55.1438 - visitorCallback(i);
55.1439 -
55.1440 - // For arrays, also respect toJSON property for custom mappings (fixes #278)
55.1441 - if (typeof rootObject['toJSON'] == 'function')
55.1442 - visitorCallback('toJSON');
55.1443 - } else {
55.1444 - for (var propertyName in rootObject)
55.1445 - visitorCallback(propertyName);
55.1446 - }
55.1447 - };
55.1448 -
55.1449 - function objectLookup() {
55.1450 - var keys = [];
55.1451 - var values = [];
55.1452 - this.save = function(key, value) {
55.1453 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
55.1454 - if (existingIndex >= 0)
55.1455 - values[existingIndex] = value;
55.1456 - else {
55.1457 - keys.push(key);
55.1458 - values.push(value);
55.1459 - }
55.1460 - };
55.1461 - this.get = function(key) {
55.1462 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
55.1463 - return (existingIndex >= 0) ? values[existingIndex] : undefined;
55.1464 - };
55.1465 - };
55.1466 -})();
55.1467 -
55.1468 -ko.exportSymbol('toJS', ko.toJS);
55.1469 -ko.exportSymbol('toJSON', ko.toJSON);
55.1470 -(function () {
55.1471 - var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
55.1472 -
55.1473 - // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
55.1474 - // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
55.1475 - // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
55.1476 - ko.selectExtensions = {
55.1477 - readValue : function(element) {
55.1478 - switch (ko.utils.tagNameLower(element)) {
55.1479 - case 'option':
55.1480 - if (element[hasDomDataExpandoProperty] === true)
55.1481 - return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
55.1482 - return ko.utils.ieVersion <= 7
55.1483 - ? (element.getAttributeNode('value').specified ? element.value : element.text)
55.1484 - : element.value;
55.1485 - case 'select':
55.1486 - return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
55.1487 - default:
55.1488 - return element.value;
55.1489 - }
55.1490 - },
55.1491 -
55.1492 - writeValue: function(element, value) {
55.1493 - switch (ko.utils.tagNameLower(element)) {
55.1494 - case 'option':
55.1495 - switch(typeof value) {
55.1496 - case "string":
55.1497 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
55.1498 - if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
55.1499 - delete element[hasDomDataExpandoProperty];
55.1500 - }
55.1501 - element.value = value;
55.1502 - break;
55.1503 - default:
55.1504 - // Store arbitrary object using DomData
55.1505 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
55.1506 - element[hasDomDataExpandoProperty] = true;
55.1507 -
55.1508 - // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
55.1509 - element.value = typeof value === "number" ? value : "";
55.1510 - break;
55.1511 - }
55.1512 - break;
55.1513 - case 'select':
55.1514 - for (var i = element.options.length - 1; i >= 0; i--) {
55.1515 - if (ko.selectExtensions.readValue(element.options[i]) == value) {
55.1516 - element.selectedIndex = i;
55.1517 - break;
55.1518 - }
55.1519 - }
55.1520 - break;
55.1521 - default:
55.1522 - if ((value === null) || (value === undefined))
55.1523 - value = "";
55.1524 - element.value = value;
55.1525 - break;
55.1526 - }
55.1527 - }
55.1528 - };
55.1529 -})();
55.1530 -
55.1531 -ko.exportSymbol('selectExtensions', ko.selectExtensions);
55.1532 -ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
55.1533 -ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
55.1534 -ko.expressionRewriting = (function () {
55.1535 - var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
55.1536 - var javaScriptReservedWords = ["true", "false"];
55.1537 -
55.1538 - // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
55.1539 - // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
55.1540 - var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
55.1541 -
55.1542 - function restoreTokens(string, tokens) {
55.1543 - var prevValue = null;
55.1544 - while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
55.1545 - prevValue = string;
55.1546 - string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
55.1547 - return tokens[tokenIndex];
55.1548 - });
55.1549 - }
55.1550 - return string;
55.1551 - }
55.1552 -
55.1553 - function getWriteableValue(expression) {
55.1554 - if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
55.1555 - return false;
55.1556 - var match = expression.match(javaScriptAssignmentTarget);
55.1557 - return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
55.1558 - }
55.1559 -
55.1560 - function ensureQuoted(key) {
55.1561 - var trimmedKey = ko.utils.stringTrim(key);
55.1562 - switch (trimmedKey.length && trimmedKey.charAt(0)) {
55.1563 - case "'":
55.1564 - case '"':
55.1565 - return key;
55.1566 - default:
55.1567 - return "'" + trimmedKey + "'";
55.1568 - }
55.1569 - }
55.1570 -
55.1571 - return {
55.1572 - bindingRewriteValidators: [],
55.1573 -
55.1574 - parseObjectLiteral: function(objectLiteralString) {
55.1575 - // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
55.1576 - // that is sufficient just to split an object literal string into a set of top-level key-value pairs
55.1577 -
55.1578 - var str = ko.utils.stringTrim(objectLiteralString);
55.1579 - if (str.length < 3)
55.1580 - return [];
55.1581 - if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
55.1582 - str = str.substring(1, str.length - 1);
55.1583 -
55.1584 - // Pull out any string literals and regex literals
55.1585 - var tokens = [];
55.1586 - var tokenStart = null, tokenEndChar;
55.1587 - for (var position = 0; position < str.length; position++) {
55.1588 - var c = str.charAt(position);
55.1589 - if (tokenStart === null) {
55.1590 - switch (c) {
55.1591 - case '"':
55.1592 - case "'":
55.1593 - case "/":
55.1594 - tokenStart = position;
55.1595 - tokenEndChar = c;
55.1596 - break;
55.1597 - }
55.1598 - } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
55.1599 - var token = str.substring(tokenStart, position + 1);
55.1600 - tokens.push(token);
55.1601 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
55.1602 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
55.1603 - position -= (token.length - replacement.length);
55.1604 - tokenStart = null;
55.1605 - }
55.1606 - }
55.1607 -
55.1608 - // Next pull out balanced paren, brace, and bracket blocks
55.1609 - tokenStart = null;
55.1610 - tokenEndChar = null;
55.1611 - var tokenDepth = 0, tokenStartChar = null;
55.1612 - for (var position = 0; position < str.length; position++) {
55.1613 - var c = str.charAt(position);
55.1614 - if (tokenStart === null) {
55.1615 - switch (c) {
55.1616 - case "{": tokenStart = position; tokenStartChar = c;
55.1617 - tokenEndChar = "}";
55.1618 - break;
55.1619 - case "(": tokenStart = position; tokenStartChar = c;
55.1620 - tokenEndChar = ")";
55.1621 - break;
55.1622 - case "[": tokenStart = position; tokenStartChar = c;
55.1623 - tokenEndChar = "]";
55.1624 - break;
55.1625 - }
55.1626 - }
55.1627 -
55.1628 - if (c === tokenStartChar)
55.1629 - tokenDepth++;
55.1630 - else if (c === tokenEndChar) {
55.1631 - tokenDepth--;
55.1632 - if (tokenDepth === 0) {
55.1633 - var token = str.substring(tokenStart, position + 1);
55.1634 - tokens.push(token);
55.1635 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
55.1636 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
55.1637 - position -= (token.length - replacement.length);
55.1638 - tokenStart = null;
55.1639 - }
55.1640 - }
55.1641 - }
55.1642 -
55.1643 - // Now we can safely split on commas to get the key/value pairs
55.1644 - var result = [];
55.1645 - var keyValuePairs = str.split(",");
55.1646 - for (var i = 0, j = keyValuePairs.length; i < j; i++) {
55.1647 - var pair = keyValuePairs[i];
55.1648 - var colonPos = pair.indexOf(":");
55.1649 - if ((colonPos > 0) && (colonPos < pair.length - 1)) {
55.1650 - var key = pair.substring(0, colonPos);
55.1651 - var value = pair.substring(colonPos + 1);
55.1652 - result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
55.1653 - } else {
55.1654 - result.push({ 'unknown': restoreTokens(pair, tokens) });
55.1655 - }
55.1656 - }
55.1657 - return result;
55.1658 - },
55.1659 -
55.1660 - preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
55.1661 - var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
55.1662 - ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
55.1663 - : objectLiteralStringOrKeyValueArray;
55.1664 - var resultStrings = [], propertyAccessorResultStrings = [];
55.1665 -
55.1666 - var keyValueEntry;
55.1667 - for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
55.1668 - if (resultStrings.length > 0)
55.1669 - resultStrings.push(",");
55.1670 -
55.1671 - if (keyValueEntry['key']) {
55.1672 - var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
55.1673 - resultStrings.push(quotedKey);
55.1674 - resultStrings.push(":");
55.1675 - resultStrings.push(val);
55.1676 -
55.1677 - if (val = getWriteableValue(ko.utils.stringTrim(val))) {
55.1678 - if (propertyAccessorResultStrings.length > 0)
55.1679 - propertyAccessorResultStrings.push(", ");
55.1680 - propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
55.1681 - }
55.1682 - } else if (keyValueEntry['unknown']) {
55.1683 - resultStrings.push(keyValueEntry['unknown']);
55.1684 - }
55.1685 - }
55.1686 -
55.1687 - var combinedResult = resultStrings.join("");
55.1688 - if (propertyAccessorResultStrings.length > 0) {
55.1689 - var allPropertyAccessors = propertyAccessorResultStrings.join("");
55.1690 - combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
55.1691 - }
55.1692 -
55.1693 - return combinedResult;
55.1694 - },
55.1695 -
55.1696 - keyValueArrayContainsKey: function(keyValueArray, key) {
55.1697 - for (var i = 0; i < keyValueArray.length; i++)
55.1698 - if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
55.1699 - return true;
55.1700 - return false;
55.1701 - },
55.1702 -
55.1703 - // Internal, private KO utility for updating model properties from within bindings
55.1704 - // property: If the property being updated is (or might be) an observable, pass it here
55.1705 - // If it turns out to be a writable observable, it will be written to directly
55.1706 - // allBindingsAccessor: All bindings in the current execution context.
55.1707 - // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
55.1708 - // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
55.1709 - // value: The value to be written
55.1710 - // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
55.1711 - // it is !== existing value on that writable observable
55.1712 - writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
55.1713 - if (!property || !ko.isWriteableObservable(property)) {
55.1714 - var propWriters = allBindingsAccessor()['_ko_property_writers'];
55.1715 - if (propWriters && propWriters[key])
55.1716 - propWriters[key](value);
55.1717 - } else if (!checkIfDifferent || property.peek() !== value) {
55.1718 - property(value);
55.1719 - }
55.1720 - }
55.1721 - };
55.1722 -})();
55.1723 -
55.1724 -ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
55.1725 -ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
55.1726 -ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
55.1727 -ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
55.1728 -
55.1729 -// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
55.1730 -// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
55.1731 -ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
55.1732 -ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
55.1733 - // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
55.1734 - // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
55.1735 - // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
55.1736 - // of that virtual hierarchy
55.1737 - //
55.1738 - // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
55.1739 - // without having to scatter special cases all over the binding and templating code.
55.1740 -
55.1741 - // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
55.1742 - // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
55.1743 - // So, use node.text where available, and node.nodeValue elsewhere
55.1744 - var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
55.1745 -
55.1746 - var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
55.1747 - var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
55.1748 - var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
55.1749 -
55.1750 - function isStartComment(node) {
55.1751 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
55.1752 - }
55.1753 -
55.1754 - function isEndComment(node) {
55.1755 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
55.1756 - }
55.1757 -
55.1758 - function getVirtualChildren(startComment, allowUnbalanced) {
55.1759 - var currentNode = startComment;
55.1760 - var depth = 1;
55.1761 - var children = [];
55.1762 - while (currentNode = currentNode.nextSibling) {
55.1763 - if (isEndComment(currentNode)) {
55.1764 - depth--;
55.1765 - if (depth === 0)
55.1766 - return children;
55.1767 - }
55.1768 -
55.1769 - children.push(currentNode);
55.1770 -
55.1771 - if (isStartComment(currentNode))
55.1772 - depth++;
55.1773 - }
55.1774 - if (!allowUnbalanced)
55.1775 - throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
55.1776 - return null;
55.1777 - }
55.1778 -
55.1779 - function getMatchingEndComment(startComment, allowUnbalanced) {
55.1780 - var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
55.1781 - if (allVirtualChildren) {
55.1782 - if (allVirtualChildren.length > 0)
55.1783 - return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
55.1784 - return startComment.nextSibling;
55.1785 - } else
55.1786 - return null; // Must have no matching end comment, and allowUnbalanced is true
55.1787 - }
55.1788 -
55.1789 - function getUnbalancedChildTags(node) {
55.1790 - // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
55.1791 - // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
55.1792 - var childNode = node.firstChild, captureRemaining = null;
55.1793 - if (childNode) {
55.1794 - do {
55.1795 - if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
55.1796 - captureRemaining.push(childNode);
55.1797 - else if (isStartComment(childNode)) {
55.1798 - var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
55.1799 - if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
55.1800 - childNode = matchingEndComment;
55.1801 - else
55.1802 - captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
55.1803 - } else if (isEndComment(childNode)) {
55.1804 - captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
55.1805 - }
55.1806 - } while (childNode = childNode.nextSibling);
55.1807 - }
55.1808 - return captureRemaining;
55.1809 - }
55.1810 -
55.1811 - ko.virtualElements = {
55.1812 - allowedBindings: {},
55.1813 -
55.1814 - childNodes: function(node) {
55.1815 - return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
55.1816 - },
55.1817 -
55.1818 - emptyNode: function(node) {
55.1819 - if (!isStartComment(node))
55.1820 - ko.utils.emptyDomNode(node);
55.1821 - else {
55.1822 - var virtualChildren = ko.virtualElements.childNodes(node);
55.1823 - for (var i = 0, j = virtualChildren.length; i < j; i++)
55.1824 - ko.removeNode(virtualChildren[i]);
55.1825 - }
55.1826 - },
55.1827 -
55.1828 - setDomNodeChildren: function(node, childNodes) {
55.1829 - if (!isStartComment(node))
55.1830 - ko.utils.setDomNodeChildren(node, childNodes);
55.1831 - else {
55.1832 - ko.virtualElements.emptyNode(node);
55.1833 - var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
55.1834 - for (var i = 0, j = childNodes.length; i < j; i++)
55.1835 - endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
55.1836 - }
55.1837 - },
55.1838 -
55.1839 - prepend: function(containerNode, nodeToPrepend) {
55.1840 - if (!isStartComment(containerNode)) {
55.1841 - if (containerNode.firstChild)
55.1842 - containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
55.1843 - else
55.1844 - containerNode.appendChild(nodeToPrepend);
55.1845 - } else {
55.1846 - // Start comments must always have a parent and at least one following sibling (the end comment)
55.1847 - containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
55.1848 - }
55.1849 - },
55.1850 -
55.1851 - insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
55.1852 - if (!insertAfterNode) {
55.1853 - ko.virtualElements.prepend(containerNode, nodeToInsert);
55.1854 - } else if (!isStartComment(containerNode)) {
55.1855 - // Insert after insertion point
55.1856 - if (insertAfterNode.nextSibling)
55.1857 - containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
55.1858 - else
55.1859 - containerNode.appendChild(nodeToInsert);
55.1860 - } else {
55.1861 - // Children of start comments must always have a parent and at least one following sibling (the end comment)
55.1862 - containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
55.1863 - }
55.1864 - },
55.1865 -
55.1866 - firstChild: function(node) {
55.1867 - if (!isStartComment(node))
55.1868 - return node.firstChild;
55.1869 - if (!node.nextSibling || isEndComment(node.nextSibling))
55.1870 - return null;
55.1871 - return node.nextSibling;
55.1872 - },
55.1873 -
55.1874 - nextSibling: function(node) {
55.1875 - if (isStartComment(node))
55.1876 - node = getMatchingEndComment(node);
55.1877 - if (node.nextSibling && isEndComment(node.nextSibling))
55.1878 - return null;
55.1879 - return node.nextSibling;
55.1880 - },
55.1881 -
55.1882 - virtualNodeBindingValue: function(node) {
55.1883 - var regexMatch = isStartComment(node);
55.1884 - return regexMatch ? regexMatch[1] : null;
55.1885 - },
55.1886 -
55.1887 - normaliseVirtualElementDomStructure: function(elementVerified) {
55.1888 - // Workaround for https://github.com/SteveSanderson/knockout/issues/155
55.1889 - // (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
55.1890 - // that are direct descendants of <ul> into the preceding <li>)
55.1891 - if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
55.1892 - return;
55.1893 -
55.1894 - // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
55.1895 - // must be intended to appear *after* that child, so move them there.
55.1896 - var childNode = elementVerified.firstChild;
55.1897 - if (childNode) {
55.1898 - do {
55.1899 - if (childNode.nodeType === 1) {
55.1900 - var unbalancedTags = getUnbalancedChildTags(childNode);
55.1901 - if (unbalancedTags) {
55.1902 - // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
55.1903 - var nodeToInsertBefore = childNode.nextSibling;
55.1904 - for (var i = 0; i < unbalancedTags.length; i++) {
55.1905 - if (nodeToInsertBefore)
55.1906 - elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
55.1907 - else
55.1908 - elementVerified.appendChild(unbalancedTags[i]);
55.1909 - }
55.1910 - }
55.1911 - }
55.1912 - } while (childNode = childNode.nextSibling);
55.1913 - }
55.1914 - }
55.1915 - };
55.1916 -})();
55.1917 -ko.exportSymbol('virtualElements', ko.virtualElements);
55.1918 -ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
55.1919 -ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
55.1920 -//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
55.1921 -ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
55.1922 -//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
55.1923 -ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
55.1924 -ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
55.1925 -(function() {
55.1926 - var defaultBindingAttributeName = "data-bind";
55.1927 -
55.1928 - ko.bindingProvider = function() {
55.1929 - this.bindingCache = {};
55.1930 - };
55.1931 -
55.1932 - ko.utils.extend(ko.bindingProvider.prototype, {
55.1933 - 'nodeHasBindings': function(node) {
55.1934 - switch (node.nodeType) {
55.1935 - case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
55.1936 - case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
55.1937 - default: return false;
55.1938 - }
55.1939 - },
55.1940 -
55.1941 - 'getBindings': function(node, bindingContext) {
55.1942 - var bindingsString = this['getBindingsString'](node, bindingContext);
55.1943 - return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
55.1944 - },
55.1945 -
55.1946 - // The following function is only used internally by this default provider.
55.1947 - // It's not part of the interface definition for a general binding provider.
55.1948 - 'getBindingsString': function(node, bindingContext) {
55.1949 - switch (node.nodeType) {
55.1950 - case 1: return node.getAttribute(defaultBindingAttributeName); // Element
55.1951 - case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
55.1952 - default: return null;
55.1953 - }
55.1954 - },
55.1955 -
55.1956 - // The following function is only used internally by this default provider.
55.1957 - // It's not part of the interface definition for a general binding provider.
55.1958 - 'parseBindingsString': function(bindingsString, bindingContext, node) {
55.1959 - try {
55.1960 - var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
55.1961 - return bindingFunction(bindingContext, node);
55.1962 - } catch (ex) {
55.1963 - throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
55.1964 - }
55.1965 - }
55.1966 - });
55.1967 -
55.1968 - ko.bindingProvider['instance'] = new ko.bindingProvider();
55.1969 -
55.1970 - function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
55.1971 - var cacheKey = bindingsString;
55.1972 - return cache[cacheKey]
55.1973 - || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
55.1974 - }
55.1975 -
55.1976 - function createBindingsStringEvaluator(bindingsString) {
55.1977 - // Build the source for a function that evaluates "expression"
55.1978 - // For each scope variable, add an extra level of "with" nesting
55.1979 - // Example result: with(sc1) { with(sc0) { return (expression) } }
55.1980 - var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
55.1981 - functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
55.1982 - return new Function("$context", "$element", functionBody);
55.1983 - }
55.1984 -})();
55.1985 -
55.1986 -ko.exportSymbol('bindingProvider', ko.bindingProvider);
55.1987 -(function () {
55.1988 - ko.bindingHandlers = {};
55.1989 -
55.1990 - ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
55.1991 - if (parentBindingContext) {
55.1992 - ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
55.1993 - this['$parentContext'] = parentBindingContext;
55.1994 - this['$parent'] = parentBindingContext['$data'];
55.1995 - this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
55.1996 - this['$parents'].unshift(this['$parent']);
55.1997 - } else {
55.1998 - this['$parents'] = [];
55.1999 - this['$root'] = dataItem;
55.2000 - // Export 'ko' in the binding context so it will be available in bindings and templates
55.2001 - // even if 'ko' isn't exported as a global, such as when using an AMD loader.
55.2002 - // See https://github.com/SteveSanderson/knockout/issues/490
55.2003 - this['ko'] = ko;
55.2004 - }
55.2005 - this['$data'] = dataItem;
55.2006 - if (dataItemAlias)
55.2007 - this[dataItemAlias] = dataItem;
55.2008 - }
55.2009 - ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
55.2010 - return new ko.bindingContext(dataItem, this, dataItemAlias);
55.2011 - };
55.2012 - ko.bindingContext.prototype['extend'] = function(properties) {
55.2013 - var clone = ko.utils.extend(new ko.bindingContext(), this);
55.2014 - return ko.utils.extend(clone, properties);
55.2015 - };
55.2016 -
55.2017 - function validateThatBindingIsAllowedForVirtualElements(bindingName) {
55.2018 - var validator = ko.virtualElements.allowedBindings[bindingName];
55.2019 - if (!validator)
55.2020 - throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
55.2021 - }
55.2022 -
55.2023 - function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
55.2024 - var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
55.2025 - while (currentChild = nextInQueue) {
55.2026 - // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
55.2027 - nextInQueue = ko.virtualElements.nextSibling(currentChild);
55.2028 - applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
55.2029 - }
55.2030 - }
55.2031 -
55.2032 - function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
55.2033 - var shouldBindDescendants = true;
55.2034 -
55.2035 - // Perf optimisation: Apply bindings only if...
55.2036 - // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
55.2037 - // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
55.2038 - // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
55.2039 - var isElement = (nodeVerified.nodeType === 1);
55.2040 - if (isElement) // Workaround IE <= 8 HTML parsing weirdness
55.2041 - ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
55.2042 -
55.2043 - var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
55.2044 - || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
55.2045 - if (shouldApplyBindings)
55.2046 - shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
55.2047 -
55.2048 - if (shouldBindDescendants) {
55.2049 - // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
55.2050 - // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
55.2051 - // hence bindingContextsMayDifferFromDomParentElement is false
55.2052 - // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
55.2053 - // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
55.2054 - // hence bindingContextsMayDifferFromDomParentElement is true
55.2055 - applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
55.2056 - }
55.2057 - }
55.2058 -
55.2059 - function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
55.2060 - // Need to be sure that inits are only run once, and updates never run until all the inits have been run
55.2061 - var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
55.2062 -
55.2063 - // Each time the dependentObservable is evaluated (after data changes),
55.2064 - // the binding attribute is reparsed so that it can pick out the correct
55.2065 - // model properties in the context of the changed data.
55.2066 - // DOM event callbacks need to be able to access this changed data,
55.2067 - // so we need a single parsedBindings variable (shared by all callbacks
55.2068 - // associated with this node's bindings) that all the closures can access.
55.2069 - var parsedBindings;
55.2070 - function makeValueAccessor(bindingKey) {
55.2071 - return function () { return parsedBindings[bindingKey] }
55.2072 - }
55.2073 - function parsedBindingsAccessor() {
55.2074 - return parsedBindings;
55.2075 - }
55.2076 -
55.2077 - var bindingHandlerThatControlsDescendantBindings;
55.2078 - ko.dependentObservable(
55.2079 - function () {
55.2080 - // Ensure we have a nonnull binding context to work with
55.2081 - var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
55.2082 - ? viewModelOrBindingContext
55.2083 - : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
55.2084 - var viewModel = bindingContextInstance['$data'];
55.2085 -
55.2086 - // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
55.2087 - // we can easily recover it just by scanning up the node's ancestors in the DOM
55.2088 - // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
55.2089 - if (bindingContextMayDifferFromDomParentElement)
55.2090 - ko.storedBindingContextForNode(node, bindingContextInstance);
55.2091 -
55.2092 - // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
55.2093 - var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
55.2094 - parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
55.2095 -
55.2096 - if (parsedBindings) {
55.2097 - // First run all the inits, so bindings can register for notification on changes
55.2098 - if (initPhase === 0) {
55.2099 - initPhase = 1;
55.2100 - for (var bindingKey in parsedBindings) {
55.2101 - var binding = ko.bindingHandlers[bindingKey];
55.2102 - if (binding && node.nodeType === 8)
55.2103 - validateThatBindingIsAllowedForVirtualElements(bindingKey);
55.2104 -
55.2105 - if (binding && typeof binding["init"] == "function") {
55.2106 - var handlerInitFn = binding["init"];
55.2107 - var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
55.2108 -
55.2109 - // If this binding handler claims to control descendant bindings, make a note of this
55.2110 - if (initResult && initResult['controlsDescendantBindings']) {
55.2111 - if (bindingHandlerThatControlsDescendantBindings !== undefined)
55.2112 - 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.");
55.2113 - bindingHandlerThatControlsDescendantBindings = bindingKey;
55.2114 - }
55.2115 - }
55.2116 - }
55.2117 - initPhase = 2;
55.2118 - }
55.2119 -
55.2120 - // ... then run all the updates, which might trigger changes even on the first evaluation
55.2121 - if (initPhase === 2) {
55.2122 - for (var bindingKey in parsedBindings) {
55.2123 - var binding = ko.bindingHandlers[bindingKey];
55.2124 - if (binding && typeof binding["update"] == "function") {
55.2125 - var handlerUpdateFn = binding["update"];
55.2126 - handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
55.2127 - }
55.2128 - }
55.2129 - }
55.2130 - }
55.2131 - },
55.2132 - null,
55.2133 - { disposeWhenNodeIsRemoved : node }
55.2134 - );
55.2135 -
55.2136 - return {
55.2137 - shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
55.2138 - };
55.2139 - };
55.2140 -
55.2141 - var storedBindingContextDomDataKey = "__ko_bindingContext__";
55.2142 - ko.storedBindingContextForNode = function (node, bindingContext) {
55.2143 - if (arguments.length == 2)
55.2144 - ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
55.2145 - else
55.2146 - return ko.utils.domData.get(node, storedBindingContextDomDataKey);
55.2147 - }
55.2148 -
55.2149 - ko.applyBindingsToNode = function (node, bindings, viewModel) {
55.2150 - if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
55.2151 - ko.virtualElements.normaliseVirtualElementDomStructure(node);
55.2152 - return applyBindingsToNodeInternal(node, bindings, viewModel, true);
55.2153 - };
55.2154 -
55.2155 - ko.applyBindingsToDescendants = function(viewModel, rootNode) {
55.2156 - if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
55.2157 - applyBindingsToDescendantsInternal(viewModel, rootNode, true);
55.2158 - };
55.2159 -
55.2160 - ko.applyBindings = function (viewModel, rootNode) {
55.2161 - if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
55.2162 - throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
55.2163 - rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
55.2164 -
55.2165 - applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
55.2166 - };
55.2167 -
55.2168 - // Retrieving binding context from arbitrary nodes
55.2169 - ko.contextFor = function(node) {
55.2170 - // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
55.2171 - switch (node.nodeType) {
55.2172 - case 1:
55.2173 - case 8:
55.2174 - var context = ko.storedBindingContextForNode(node);
55.2175 - if (context) return context;
55.2176 - if (node.parentNode) return ko.contextFor(node.parentNode);
55.2177 - break;
55.2178 - }
55.2179 - return undefined;
55.2180 - };
55.2181 - ko.dataFor = function(node) {
55.2182 - var context = ko.contextFor(node);
55.2183 - return context ? context['$data'] : undefined;
55.2184 - };
55.2185 -
55.2186 - ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
55.2187 - ko.exportSymbol('applyBindings', ko.applyBindings);
55.2188 - ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
55.2189 - ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
55.2190 - ko.exportSymbol('contextFor', ko.contextFor);
55.2191 - ko.exportSymbol('dataFor', ko.dataFor);
55.2192 -})();
55.2193 -var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
55.2194 -ko.bindingHandlers['attr'] = {
55.2195 - 'update': function(element, valueAccessor, allBindingsAccessor) {
55.2196 - var value = ko.utils.unwrapObservable(valueAccessor()) || {};
55.2197 - for (var attrName in value) {
55.2198 - if (typeof attrName == "string") {
55.2199 - var attrValue = ko.utils.unwrapObservable(value[attrName]);
55.2200 -
55.2201 - // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
55.2202 - // when someProp is a "no value"-like value (strictly null, false, or undefined)
55.2203 - // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
55.2204 - var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
55.2205 - if (toRemove)
55.2206 - element.removeAttribute(attrName);
55.2207 -
55.2208 - // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
55.2209 - // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
55.2210 - // but instead of figuring out the mode, we'll just set the attribute through the Javascript
55.2211 - // property for IE <= 8.
55.2212 - if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
55.2213 - attrName = attrHtmlToJavascriptMap[attrName];
55.2214 - if (toRemove)
55.2215 - element.removeAttribute(attrName);
55.2216 - else
55.2217 - element[attrName] = attrValue;
55.2218 - } else if (!toRemove) {
55.2219 - try {
55.2220 - element.setAttribute(attrName, attrValue.toString());
55.2221 - } catch (err) {
55.2222 - // ignore for now
55.2223 - if (console) {
55.2224 - console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
55.2225 - }
55.2226 - }
55.2227 - }
55.2228 -
55.2229 - // Treat "name" specially - although you can think of it as an attribute, it also needs
55.2230 - // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
55.2231 - // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
55.2232 - // entirely, and there's no strong reason to allow for such casing in HTML.
55.2233 - if (attrName === "name") {
55.2234 - ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
55.2235 - }
55.2236 - }
55.2237 - }
55.2238 - }
55.2239 -};
55.2240 -ko.bindingHandlers['checked'] = {
55.2241 - 'init': function (element, valueAccessor, allBindingsAccessor) {
55.2242 - var updateHandler = function() {
55.2243 - var valueToWrite;
55.2244 - if (element.type == "checkbox") {
55.2245 - valueToWrite = element.checked;
55.2246 - } else if ((element.type == "radio") && (element.checked)) {
55.2247 - valueToWrite = element.value;
55.2248 - } else {
55.2249 - return; // "checked" binding only responds to checkboxes and selected radio buttons
55.2250 - }
55.2251 -
55.2252 - var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
55.2253 - if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
55.2254 - // For checkboxes bound to an array, we add/remove the checkbox value to that array
55.2255 - // This works for both observable and non-observable arrays
55.2256 - var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
55.2257 - if (element.checked && (existingEntryIndex < 0))
55.2258 - modelValue.push(element.value);
55.2259 - else if ((!element.checked) && (existingEntryIndex >= 0))
55.2260 - modelValue.splice(existingEntryIndex, 1);
55.2261 - } else {
55.2262 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
55.2263 - }
55.2264 - };
55.2265 - ko.utils.registerEventHandler(element, "click", updateHandler);
55.2266 -
55.2267 - // IE 6 won't allow radio buttons to be selected unless they have a name
55.2268 - if ((element.type == "radio") && !element.name)
55.2269 - ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
55.2270 - },
55.2271 - 'update': function (element, valueAccessor) {
55.2272 - var value = ko.utils.unwrapObservable(valueAccessor());
55.2273 -
55.2274 - if (element.type == "checkbox") {
55.2275 - if (value instanceof Array) {
55.2276 - // When bound to an array, the checkbox being checked represents its value being present in that array
55.2277 - element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
55.2278 - } else {
55.2279 - // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
55.2280 - element.checked = value;
55.2281 - }
55.2282 - } else if (element.type == "radio") {
55.2283 - element.checked = (element.value == value);
55.2284 - }
55.2285 - }
55.2286 -};
55.2287 -var classesWrittenByBindingKey = '__ko__cssValue';
55.2288 -ko.bindingHandlers['css'] = {
55.2289 - 'update': function (element, valueAccessor) {
55.2290 - var value = ko.utils.unwrapObservable(valueAccessor());
55.2291 - if (typeof value == "object") {
55.2292 - for (var className in value) {
55.2293 - var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
55.2294 - ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
55.2295 - }
55.2296 - } else {
55.2297 - value = String(value || ''); // Make sure we don't try to store or set a non-string value
55.2298 - ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
55.2299 - element[classesWrittenByBindingKey] = value;
55.2300 - ko.utils.toggleDomNodeCssClass(element, value, true);
55.2301 - }
55.2302 - }
55.2303 -};
55.2304 -ko.bindingHandlers['enable'] = {
55.2305 - 'update': function (element, valueAccessor) {
55.2306 - var value = ko.utils.unwrapObservable(valueAccessor());
55.2307 - if (value && element.disabled)
55.2308 - element.removeAttribute("disabled");
55.2309 - else if ((!value) && (!element.disabled))
55.2310 - element.disabled = true;
55.2311 - }
55.2312 -};
55.2313 -
55.2314 -ko.bindingHandlers['disable'] = {
55.2315 - 'update': function (element, valueAccessor) {
55.2316 - ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
55.2317 - }
55.2318 -};
55.2319 -// For certain common events (currently just 'click'), allow a simplified data-binding syntax
55.2320 -// e.g. click:handler instead of the usual full-length event:{click:handler}
55.2321 -function makeEventHandlerShortcut(eventName) {
55.2322 - ko.bindingHandlers[eventName] = {
55.2323 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
55.2324 - var newValueAccessor = function () {
55.2325 - var result = {};
55.2326 - result[eventName] = valueAccessor();
55.2327 - return result;
55.2328 - };
55.2329 - return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
55.2330 - }
55.2331 - }
55.2332 -}
55.2333 -
55.2334 -ko.bindingHandlers['event'] = {
55.2335 - 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
55.2336 - var eventsToHandle = valueAccessor() || {};
55.2337 - for(var eventNameOutsideClosure in eventsToHandle) {
55.2338 - (function() {
55.2339 - var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
55.2340 - if (typeof eventName == "string") {
55.2341 - ko.utils.registerEventHandler(element, eventName, function (event) {
55.2342 - var handlerReturnValue;
55.2343 - var handlerFunction = valueAccessor()[eventName];
55.2344 - if (!handlerFunction)
55.2345 - return;
55.2346 - var allBindings = allBindingsAccessor();
55.2347 -
55.2348 - try {
55.2349 - // Take all the event args, and prefix with the viewmodel
55.2350 - var argsForHandler = ko.utils.makeArray(arguments);
55.2351 - argsForHandler.unshift(viewModel);
55.2352 - handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
55.2353 - } finally {
55.2354 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
55.2355 - if (event.preventDefault)
55.2356 - event.preventDefault();
55.2357 - else
55.2358 - event.returnValue = false;
55.2359 - }
55.2360 - }
55.2361 -
55.2362 - var bubble = allBindings[eventName + 'Bubble'] !== false;
55.2363 - if (!bubble) {
55.2364 - event.cancelBubble = true;
55.2365 - if (event.stopPropagation)
55.2366 - event.stopPropagation();
55.2367 - }
55.2368 - });
55.2369 - }
55.2370 - })();
55.2371 - }
55.2372 - }
55.2373 -};
55.2374 -// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
55.2375 -// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
55.2376 -ko.bindingHandlers['foreach'] = {
55.2377 - makeTemplateValueAccessor: function(valueAccessor) {
55.2378 - return function() {
55.2379 - var modelValue = valueAccessor(),
55.2380 - unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
55.2381 -
55.2382 - // If unwrappedValue is the array, pass in the wrapped value on its own
55.2383 - // The value will be unwrapped and tracked within the template binding
55.2384 - // (See https://github.com/SteveSanderson/knockout/issues/523)
55.2385 - if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
55.2386 - return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
55.2387 -
55.2388 - // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
55.2389 - ko.utils.unwrapObservable(modelValue);
55.2390 - return {
55.2391 - 'foreach': unwrappedValue['data'],
55.2392 - 'as': unwrappedValue['as'],
55.2393 - 'includeDestroyed': unwrappedValue['includeDestroyed'],
55.2394 - 'afterAdd': unwrappedValue['afterAdd'],
55.2395 - 'beforeRemove': unwrappedValue['beforeRemove'],
55.2396 - 'afterRender': unwrappedValue['afterRender'],
55.2397 - 'beforeMove': unwrappedValue['beforeMove'],
55.2398 - 'afterMove': unwrappedValue['afterMove'],
55.2399 - 'templateEngine': ko.nativeTemplateEngine.instance
55.2400 - };
55.2401 - };
55.2402 - },
55.2403 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
55.2404 - return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
55.2405 - },
55.2406 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
55.2407 - return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
55.2408 - }
55.2409 -};
55.2410 -ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
55.2411 -ko.virtualElements.allowedBindings['foreach'] = true;
55.2412 -var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
55.2413 -ko.bindingHandlers['hasfocus'] = {
55.2414 - 'init': function(element, valueAccessor, allBindingsAccessor) {
55.2415 - var handleElementFocusChange = function(isFocused) {
55.2416 - // Where possible, ignore which event was raised and determine focus state using activeElement,
55.2417 - // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
55.2418 - // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
55.2419 - // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
55.2420 - // from calling 'blur()' on the element when it loses focus.
55.2421 - // Discussion at https://github.com/SteveSanderson/knockout/pull/352
55.2422 - element[hasfocusUpdatingProperty] = true;
55.2423 - var ownerDoc = element.ownerDocument;
55.2424 - if ("activeElement" in ownerDoc) {
55.2425 - isFocused = (ownerDoc.activeElement === element);
55.2426 - }
55.2427 - var modelValue = valueAccessor();
55.2428 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
55.2429 - element[hasfocusUpdatingProperty] = false;
55.2430 - };
55.2431 - var handleElementFocusIn = handleElementFocusChange.bind(null, true);
55.2432 - var handleElementFocusOut = handleElementFocusChange.bind(null, false);
55.2433 -
55.2434 - ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
55.2435 - ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
55.2436 - ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
55.2437 - ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
55.2438 - },
55.2439 - 'update': function(element, valueAccessor) {
55.2440 - var value = ko.utils.unwrapObservable(valueAccessor());
55.2441 - if (!element[hasfocusUpdatingProperty]) {
55.2442 - value ? element.focus() : element.blur();
55.2443 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
55.2444 - }
55.2445 - }
55.2446 -};
55.2447 -ko.bindingHandlers['html'] = {
55.2448 - 'init': function() {
55.2449 - // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
55.2450 - return { 'controlsDescendantBindings': true };
55.2451 - },
55.2452 - 'update': function (element, valueAccessor) {
55.2453 - // setHtml will unwrap the value if needed
55.2454 - ko.utils.setHtml(element, valueAccessor());
55.2455 - }
55.2456 -};
55.2457 -var withIfDomDataKey = '__ko_withIfBindingData';
55.2458 -// Makes a binding like with or if
55.2459 -function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
55.2460 - ko.bindingHandlers[bindingKey] = {
55.2461 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
55.2462 - ko.utils.domData.set(element, withIfDomDataKey, {});
55.2463 - return { 'controlsDescendantBindings': true };
55.2464 - },
55.2465 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
55.2466 - var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
55.2467 - dataValue = ko.utils.unwrapObservable(valueAccessor()),
55.2468 - shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
55.2469 - isFirstRender = !withIfData.savedNodes,
55.2470 - needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
55.2471 -
55.2472 - if (needsRefresh) {
55.2473 - if (isFirstRender) {
55.2474 - withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
55.2475 - }
55.2476 -
55.2477 - if (shouldDisplay) {
55.2478 - if (!isFirstRender) {
55.2479 - ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
55.2480 - }
55.2481 - ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
55.2482 - } else {
55.2483 - ko.virtualElements.emptyNode(element);
55.2484 - }
55.2485 -
55.2486 - withIfData.didDisplayOnLastUpdate = shouldDisplay;
55.2487 - }
55.2488 - }
55.2489 - };
55.2490 - ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
55.2491 - ko.virtualElements.allowedBindings[bindingKey] = true;
55.2492 -}
55.2493 -
55.2494 -// Construct the actual binding handlers
55.2495 -makeWithIfBinding('if');
55.2496 -makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
55.2497 -makeWithIfBinding('with', true /* isWith */, false /* isNot */,
55.2498 - function(bindingContext, dataValue) {
55.2499 - return bindingContext['createChildContext'](dataValue);
55.2500 - }
55.2501 -);
55.2502 -function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
55.2503 - if (preferModelValue) {
55.2504 - if (modelValue !== ko.selectExtensions.readValue(element))
55.2505 - ko.selectExtensions.writeValue(element, modelValue);
55.2506 - }
55.2507 -
55.2508 - // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
55.2509 - // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
55.2510 - // change the model value to match the dropdown.
55.2511 - if (modelValue !== ko.selectExtensions.readValue(element))
55.2512 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
55.2513 -};
55.2514 -
55.2515 -ko.bindingHandlers['options'] = {
55.2516 - 'update': function (element, valueAccessor, allBindingsAccessor) {
55.2517 - if (ko.utils.tagNameLower(element) !== "select")
55.2518 - throw new Error("options binding applies only to SELECT elements");
55.2519 -
55.2520 - var selectWasPreviouslyEmpty = element.length == 0;
55.2521 - var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
55.2522 - return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
55.2523 - }), function (node) {
55.2524 - return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
55.2525 - });
55.2526 - var previousScrollTop = element.scrollTop;
55.2527 -
55.2528 - var value = ko.utils.unwrapObservable(valueAccessor());
55.2529 - var selectedValue = element.value;
55.2530 -
55.2531 - // Remove all existing <option>s.
55.2532 - // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
55.2533 - while (element.length > 0) {
55.2534 - ko.cleanNode(element.options[0]);
55.2535 - element.remove(0);
55.2536 - }
55.2537 -
55.2538 - if (value) {
55.2539 - var allBindings = allBindingsAccessor(),
55.2540 - includeDestroyed = allBindings['optionsIncludeDestroyed'];
55.2541 -
55.2542 - if (typeof value.length != "number")
55.2543 - value = [value];
55.2544 - if (allBindings['optionsCaption']) {
55.2545 - var option = document.createElement("option");
55.2546 - ko.utils.setHtml(option, allBindings['optionsCaption']);
55.2547 - ko.selectExtensions.writeValue(option, undefined);
55.2548 - element.appendChild(option);
55.2549 - }
55.2550 -
55.2551 - for (var i = 0, j = value.length; i < j; i++) {
55.2552 - // Skip destroyed items
55.2553 - var arrayEntry = value[i];
55.2554 - if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
55.2555 - continue;
55.2556 -
55.2557 - var option = document.createElement("option");
55.2558 -
55.2559 - function applyToObject(object, predicate, defaultValue) {
55.2560 - var predicateType = typeof predicate;
55.2561 - if (predicateType == "function") // Given a function; run it against the data value
55.2562 - return predicate(object);
55.2563 - else if (predicateType == "string") // Given a string; treat it as a property name on the data value
55.2564 - return object[predicate];
55.2565 - else // Given no optionsText arg; use the data value itself
55.2566 - return defaultValue;
55.2567 - }
55.2568 -
55.2569 - // Apply a value to the option element
55.2570 - var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
55.2571 - ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
55.2572 -
55.2573 - // Apply some text to the option element
55.2574 - var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
55.2575 - ko.utils.setTextContent(option, optionText);
55.2576 -
55.2577 - element.appendChild(option);
55.2578 - }
55.2579 -
55.2580 - // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
55.2581 - // That's why we first added them without selection. Now it's time to set the selection.
55.2582 - var newOptions = element.getElementsByTagName("option");
55.2583 - var countSelectionsRetained = 0;
55.2584 - for (var i = 0, j = newOptions.length; i < j; i++) {
55.2585 - if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
55.2586 - ko.utils.setOptionNodeSelectionState(newOptions[i], true);
55.2587 - countSelectionsRetained++;
55.2588 - }
55.2589 - }
55.2590 -
55.2591 - element.scrollTop = previousScrollTop;
55.2592 -
55.2593 - if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
55.2594 - // Ensure consistency between model value and selected option.
55.2595 - // If the dropdown is being populated for the first time here (or was otherwise previously empty),
55.2596 - // the dropdown selection state is meaningless, so we preserve the model value.
55.2597 - ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
55.2598 - }
55.2599 -
55.2600 - // Workaround for IE9 bug
55.2601 - ko.utils.ensureSelectElementIsRenderedCorrectly(element);
55.2602 - }
55.2603 - }
55.2604 -};
55.2605 -ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
55.2606 -ko.bindingHandlers['selectedOptions'] = {
55.2607 - 'init': function (element, valueAccessor, allBindingsAccessor) {
55.2608 - ko.utils.registerEventHandler(element, "change", function () {
55.2609 - var value = valueAccessor(), valueToWrite = [];
55.2610 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
55.2611 - if (node.selected)
55.2612 - valueToWrite.push(ko.selectExtensions.readValue(node));
55.2613 - });
55.2614 - ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
55.2615 - });
55.2616 - },
55.2617 - 'update': function (element, valueAccessor) {
55.2618 - if (ko.utils.tagNameLower(element) != "select")
55.2619 - throw new Error("values binding applies only to SELECT elements");
55.2620 -
55.2621 - var newValue = ko.utils.unwrapObservable(valueAccessor());
55.2622 - if (newValue && typeof newValue.length == "number") {
55.2623 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
55.2624 - var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
55.2625 - ko.utils.setOptionNodeSelectionState(node, isSelected);
55.2626 - });
55.2627 - }
55.2628 - }
55.2629 -};
55.2630 -ko.bindingHandlers['style'] = {
55.2631 - 'update': function (element, valueAccessor) {
55.2632 - var value = ko.utils.unwrapObservable(valueAccessor() || {});
55.2633 - for (var styleName in value) {
55.2634 - if (typeof styleName == "string") {
55.2635 - var styleValue = ko.utils.unwrapObservable(value[styleName]);
55.2636 - element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
55.2637 - }
55.2638 - }
55.2639 - }
55.2640 -};
55.2641 -ko.bindingHandlers['submit'] = {
55.2642 - 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
55.2643 - if (typeof valueAccessor() != "function")
55.2644 - throw new Error("The value for a submit binding must be a function");
55.2645 - ko.utils.registerEventHandler(element, "submit", function (event) {
55.2646 - var handlerReturnValue;
55.2647 - var value = valueAccessor();
55.2648 - try { handlerReturnValue = value.call(viewModel, element); }
55.2649 - finally {
55.2650 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
55.2651 - if (event.preventDefault)
55.2652 - event.preventDefault();
55.2653 - else
55.2654 - event.returnValue = false;
55.2655 - }
55.2656 - }
55.2657 - });
55.2658 - }
55.2659 -};
55.2660 -ko.bindingHandlers['text'] = {
55.2661 - 'update': function (element, valueAccessor) {
55.2662 - ko.utils.setTextContent(element, valueAccessor());
55.2663 - }
55.2664 -};
55.2665 -ko.virtualElements.allowedBindings['text'] = true;
55.2666 -ko.bindingHandlers['uniqueName'] = {
55.2667 - 'init': function (element, valueAccessor) {
55.2668 - if (valueAccessor()) {
55.2669 - var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
55.2670 - ko.utils.setElementName(element, name);
55.2671 - }
55.2672 - }
55.2673 -};
55.2674 -ko.bindingHandlers['uniqueName'].currentIndex = 0;
55.2675 -ko.bindingHandlers['value'] = {
55.2676 - 'init': function (element, valueAccessor, allBindingsAccessor) {
55.2677 - // Always catch "change" event; possibly other events too if asked
55.2678 - var eventsToCatch = ["change"];
55.2679 - var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
55.2680 - var propertyChangedFired = false;
55.2681 - if (requestedEventsToCatch) {
55.2682 - if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
55.2683 - requestedEventsToCatch = [requestedEventsToCatch];
55.2684 - ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
55.2685 - eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
55.2686 - }
55.2687 -
55.2688 - var valueUpdateHandler = function() {
55.2689 - propertyChangedFired = false;
55.2690 - var modelValue = valueAccessor();
55.2691 - var elementValue = ko.selectExtensions.readValue(element);
55.2692 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
55.2693 - }
55.2694 -
55.2695 - // Workaround for https://github.com/SteveSanderson/knockout/issues/122
55.2696 - // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
55.2697 - var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
55.2698 - && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
55.2699 - if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
55.2700 - ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
55.2701 - ko.utils.registerEventHandler(element, "blur", function() {
55.2702 - if (propertyChangedFired) {
55.2703 - valueUpdateHandler();
55.2704 - }
55.2705 - });
55.2706 - }
55.2707 -
55.2708 - ko.utils.arrayForEach(eventsToCatch, function(eventName) {
55.2709 - // The syntax "after<eventname>" means "run the handler asynchronously after the event"
55.2710 - // This is useful, for example, to catch "keydown" events after the browser has updated the control
55.2711 - // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
55.2712 - var handler = valueUpdateHandler;
55.2713 - if (ko.utils.stringStartsWith(eventName, "after")) {
55.2714 - handler = function() { setTimeout(valueUpdateHandler, 0) };
55.2715 - eventName = eventName.substring("after".length);
55.2716 - }
55.2717 - ko.utils.registerEventHandler(element, eventName, handler);
55.2718 - });
55.2719 - },
55.2720 - 'update': function (element, valueAccessor) {
55.2721 - var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
55.2722 - var newValue = ko.utils.unwrapObservable(valueAccessor());
55.2723 - var elementValue = ko.selectExtensions.readValue(element);
55.2724 - var valueHasChanged = (newValue != elementValue);
55.2725 -
55.2726 - // 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).
55.2727 - // 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.
55.2728 - if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
55.2729 - valueHasChanged = true;
55.2730 -
55.2731 - if (valueHasChanged) {
55.2732 - var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
55.2733 - applyValueAction();
55.2734 -
55.2735 - // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
55.2736 - // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
55.2737 - // to apply the value as well.
55.2738 - var alsoApplyAsynchronously = valueIsSelectOption;
55.2739 - if (alsoApplyAsynchronously)
55.2740 - setTimeout(applyValueAction, 0);
55.2741 - }
55.2742 -
55.2743 - // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
55.2744 - // because you're not allowed to have a model value that disagrees with a visible UI selection.
55.2745 - if (valueIsSelectOption && (element.length > 0))
55.2746 - ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
55.2747 - }
55.2748 -};
55.2749 -ko.bindingHandlers['visible'] = {
55.2750 - 'update': function (element, valueAccessor) {
55.2751 - var value = ko.utils.unwrapObservable(valueAccessor());
55.2752 - var isCurrentlyVisible = !(element.style.display == "none");
55.2753 - if (value && !isCurrentlyVisible)
55.2754 - element.style.display = "";
55.2755 - else if ((!value) && isCurrentlyVisible)
55.2756 - element.style.display = "none";
55.2757 - }
55.2758 -};
55.2759 -// 'click' is just a shorthand for the usual full-length event:{click:handler}
55.2760 -makeEventHandlerShortcut('click');
55.2761 -// If you want to make a custom template engine,
55.2762 -//
55.2763 -// [1] Inherit from this class (like ko.nativeTemplateEngine does)
55.2764 -// [2] Override 'renderTemplateSource', supplying a function with this signature:
55.2765 -//
55.2766 -// function (templateSource, bindingContext, options) {
55.2767 -// // - templateSource.text() is the text of the template you should render
55.2768 -// // - bindingContext.$data is the data you should pass into the template
55.2769 -// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
55.2770 -// // and bindingContext.$root available in the template too
55.2771 -// // - options gives you access to any other properties set on "data-bind: { template: options }"
55.2772 -// //
55.2773 -// // Return value: an array of DOM nodes
55.2774 -// }
55.2775 -//
55.2776 -// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
55.2777 -//
55.2778 -// function (script) {
55.2779 -// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
55.2780 -// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
55.2781 -// }
55.2782 -//
55.2783 -// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
55.2784 -// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
55.2785 -// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
55.2786 -
55.2787 -ko.templateEngine = function () { };
55.2788 -
55.2789 -ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
55.2790 - throw new Error("Override renderTemplateSource");
55.2791 -};
55.2792 -
55.2793 -ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
55.2794 - throw new Error("Override createJavaScriptEvaluatorBlock");
55.2795 -};
55.2796 -
55.2797 -ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
55.2798 - // Named template
55.2799 - if (typeof template == "string") {
55.2800 - templateDocument = templateDocument || document;
55.2801 - var elem = templateDocument.getElementById(template);
55.2802 - if (!elem)
55.2803 - throw new Error("Cannot find template with ID " + template);
55.2804 - return new ko.templateSources.domElement(elem);
55.2805 - } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
55.2806 - // Anonymous template
55.2807 - return new ko.templateSources.anonymousTemplate(template);
55.2808 - } else
55.2809 - throw new Error("Unknown template type: " + template);
55.2810 -};
55.2811 -
55.2812 -ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
55.2813 - var templateSource = this['makeTemplateSource'](template, templateDocument);
55.2814 - return this['renderTemplateSource'](templateSource, bindingContext, options);
55.2815 -};
55.2816 -
55.2817 -ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
55.2818 - // Skip rewriting if requested
55.2819 - if (this['allowTemplateRewriting'] === false)
55.2820 - return true;
55.2821 - return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
55.2822 -};
55.2823 -
55.2824 -ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
55.2825 - var templateSource = this['makeTemplateSource'](template, templateDocument);
55.2826 - var rewritten = rewriterCallback(templateSource['text']());
55.2827 - templateSource['text'](rewritten);
55.2828 - templateSource['data']("isRewritten", true);
55.2829 -};
55.2830 -
55.2831 -ko.exportSymbol('templateEngine', ko.templateEngine);
55.2832 -
55.2833 -ko.templateRewriting = (function () {
55.2834 - var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
55.2835 - var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
55.2836 -
55.2837 - function validateDataBindValuesForRewriting(keyValueArray) {
55.2838 - var allValidators = ko.expressionRewriting.bindingRewriteValidators;
55.2839 - for (var i = 0; i < keyValueArray.length; i++) {
55.2840 - var key = keyValueArray[i]['key'];
55.2841 - if (allValidators.hasOwnProperty(key)) {
55.2842 - var validator = allValidators[key];
55.2843 -
55.2844 - if (typeof validator === "function") {
55.2845 - var possibleErrorMessage = validator(keyValueArray[i]['value']);
55.2846 - if (possibleErrorMessage)
55.2847 - throw new Error(possibleErrorMessage);
55.2848 - } else if (!validator) {
55.2849 - throw new Error("This template engine does not support the '" + key + "' binding within its templates");
55.2850 - }
55.2851 - }
55.2852 - }
55.2853 - }
55.2854 -
55.2855 - function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
55.2856 - var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
55.2857 - validateDataBindValuesForRewriting(dataBindKeyValueArray);
55.2858 - var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
55.2859 -
55.2860 - // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
55.2861 - // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
55.2862 - // extra indirection.
55.2863 - var applyBindingsToNextSiblingScript =
55.2864 - "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
55.2865 - return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
55.2866 - }
55.2867 -
55.2868 - return {
55.2869 - ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
55.2870 - if (!templateEngine['isTemplateRewritten'](template, templateDocument))
55.2871 - templateEngine['rewriteTemplate'](template, function (htmlString) {
55.2872 - return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
55.2873 - }, templateDocument);
55.2874 - },
55.2875 -
55.2876 - memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
55.2877 - return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
55.2878 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
55.2879 - }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
55.2880 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
55.2881 - });
55.2882 - },
55.2883 -
55.2884 - applyMemoizedBindingsToNextSibling: function (bindings) {
55.2885 - return ko.memoization.memoize(function (domNode, bindingContext) {
55.2886 - if (domNode.nextSibling)
55.2887 - ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
55.2888 - });
55.2889 - }
55.2890 - }
55.2891 -})();
55.2892 -
55.2893 -
55.2894 -// Exported only because it has to be referenced by string lookup from within rewritten template
55.2895 -ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
55.2896 -(function() {
55.2897 - // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
55.2898 - // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
55.2899 - //
55.2900 - // Two are provided by default:
55.2901 - // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
55.2902 - // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
55.2903 - // without reading/writing the actual element text content, since it will be overwritten
55.2904 - // with the rendered template output.
55.2905 - // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
55.2906 - // Template sources need to have the following functions:
55.2907 - // text() - returns the template text from your storage location
55.2908 - // text(value) - writes the supplied template text to your storage location
55.2909 - // data(key) - reads values stored using data(key, value) - see below
55.2910 - // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
55.2911 - //
55.2912 - // Optionally, template sources can also have the following functions:
55.2913 - // nodes() - returns a DOM element containing the nodes of this template, where available
55.2914 - // nodes(value) - writes the given DOM element to your storage location
55.2915 - // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
55.2916 - // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
55.2917 - //
55.2918 - // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
55.2919 - // using and overriding "makeTemplateSource" to return an instance of your custom template source.
55.2920 -
55.2921 - ko.templateSources = {};
55.2922 -
55.2923 - // ---- ko.templateSources.domElement -----
55.2924 -
55.2925 - ko.templateSources.domElement = function(element) {
55.2926 - this.domElement = element;
55.2927 - }
55.2928 -
55.2929 - ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
55.2930 - var tagNameLower = ko.utils.tagNameLower(this.domElement),
55.2931 - elemContentsProperty = tagNameLower === "script" ? "text"
55.2932 - : tagNameLower === "textarea" ? "value"
55.2933 - : "innerHTML";
55.2934 -
55.2935 - if (arguments.length == 0) {
55.2936 - return this.domElement[elemContentsProperty];
55.2937 - } else {
55.2938 - var valueToWrite = arguments[0];
55.2939 - if (elemContentsProperty === "innerHTML")
55.2940 - ko.utils.setHtml(this.domElement, valueToWrite);
55.2941 - else
55.2942 - this.domElement[elemContentsProperty] = valueToWrite;
55.2943 - }
55.2944 - };
55.2945 -
55.2946 - ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
55.2947 - if (arguments.length === 1) {
55.2948 - return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
55.2949 - } else {
55.2950 - ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
55.2951 - }
55.2952 - };
55.2953 -
55.2954 - // ---- ko.templateSources.anonymousTemplate -----
55.2955 - // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
55.2956 - // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
55.2957 - // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
55.2958 -
55.2959 - var anonymousTemplatesDomDataKey = "__ko_anon_template__";
55.2960 - ko.templateSources.anonymousTemplate = function(element) {
55.2961 - this.domElement = element;
55.2962 - }
55.2963 - ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
55.2964 - ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
55.2965 - if (arguments.length == 0) {
55.2966 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
55.2967 - if (templateData.textData === undefined && templateData.containerData)
55.2968 - templateData.textData = templateData.containerData.innerHTML;
55.2969 - return templateData.textData;
55.2970 - } else {
55.2971 - var valueToWrite = arguments[0];
55.2972 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
55.2973 - }
55.2974 - };
55.2975 - ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
55.2976 - if (arguments.length == 0) {
55.2977 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
55.2978 - return templateData.containerData;
55.2979 - } else {
55.2980 - var valueToWrite = arguments[0];
55.2981 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
55.2982 - }
55.2983 - };
55.2984 -
55.2985 - ko.exportSymbol('templateSources', ko.templateSources);
55.2986 - ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
55.2987 - ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
55.2988 -})();
55.2989 -(function () {
55.2990 - var _templateEngine;
55.2991 - ko.setTemplateEngine = function (templateEngine) {
55.2992 - if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
55.2993 - throw new Error("templateEngine must inherit from ko.templateEngine");
55.2994 - _templateEngine = templateEngine;
55.2995 - }
55.2996 -
55.2997 - function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
55.2998 - var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
55.2999 - while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
55.3000 - nextInQueue = ko.virtualElements.nextSibling(node);
55.3001 - if (node.nodeType === 1 || node.nodeType === 8)
55.3002 - action(node);
55.3003 - }
55.3004 - }
55.3005 -
55.3006 - function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
55.3007 - // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
55.3008 - // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
55.3009 - // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
55.3010 - // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
55.3011 - // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
55.3012 -
55.3013 - if (continuousNodeArray.length) {
55.3014 - var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
55.3015 -
55.3016 - // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
55.3017 - // whereas a regular applyBindings won't introduce new memoized nodes
55.3018 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
55.3019 - ko.applyBindings(bindingContext, node);
55.3020 - });
55.3021 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
55.3022 - ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
55.3023 - });
55.3024 - }
55.3025 - }
55.3026 -
55.3027 - function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
55.3028 - return nodeOrNodeArray.nodeType ? nodeOrNodeArray
55.3029 - : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
55.3030 - : null;
55.3031 - }
55.3032 -
55.3033 - function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
55.3034 - options = options || {};
55.3035 - var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
55.3036 - var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
55.3037 - var templateEngineToUse = (options['templateEngine'] || _templateEngine);
55.3038 - ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
55.3039 - var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
55.3040 -
55.3041 - // Loosely check result is an array of DOM nodes
55.3042 - if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
55.3043 - throw new Error("Template engine must return an array of DOM nodes");
55.3044 -
55.3045 - var haveAddedNodesToParent = false;
55.3046 - switch (renderMode) {
55.3047 - case "replaceChildren":
55.3048 - ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
55.3049 - haveAddedNodesToParent = true;
55.3050 - break;
55.3051 - case "replaceNode":
55.3052 - ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
55.3053 - haveAddedNodesToParent = true;
55.3054 - break;
55.3055 - case "ignoreTargetNode": break;
55.3056 - default:
55.3057 - throw new Error("Unknown renderMode: " + renderMode);
55.3058 - }
55.3059 -
55.3060 - if (haveAddedNodesToParent) {
55.3061 - activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
55.3062 - if (options['afterRender'])
55.3063 - ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
55.3064 - }
55.3065 -
55.3066 - return renderedNodesArray;
55.3067 - }
55.3068 -
55.3069 - ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
55.3070 - options = options || {};
55.3071 - if ((options['templateEngine'] || _templateEngine) == undefined)
55.3072 - throw new Error("Set a template engine before calling renderTemplate");
55.3073 - renderMode = renderMode || "replaceChildren";
55.3074 -
55.3075 - if (targetNodeOrNodeArray) {
55.3076 - var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
55.3077 -
55.3078 - var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
55.3079 - var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
55.3080 -
55.3081 - return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
55.3082 - function () {
55.3083 - // Ensure we've got a proper binding context to work with
55.3084 - var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
55.3085 - ? dataOrBindingContext
55.3086 - : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
55.3087 -
55.3088 - // Support selecting template as a function of the data being rendered
55.3089 - var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
55.3090 -
55.3091 - var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
55.3092 - if (renderMode == "replaceNode") {
55.3093 - targetNodeOrNodeArray = renderedNodesArray;
55.3094 - firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
55.3095 - }
55.3096 - },
55.3097 - null,
55.3098 - { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
55.3099 - );
55.3100 - } else {
55.3101 - // 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
55.3102 - return ko.memoization.memoize(function (domNode) {
55.3103 - ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
55.3104 - });
55.3105 - }
55.3106 - };
55.3107 -
55.3108 - ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
55.3109 - // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
55.3110 - // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
55.3111 - var arrayItemContext;
55.3112 -
55.3113 - // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
55.3114 - var executeTemplateForArrayItem = function (arrayValue, index) {
55.3115 - // Support selecting template as a function of the data being rendered
55.3116 - arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
55.3117 - arrayItemContext['$index'] = index;
55.3118 - var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
55.3119 - return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
55.3120 - }
55.3121 -
55.3122 - // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
55.3123 - var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
55.3124 - activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
55.3125 - if (options['afterRender'])
55.3126 - options['afterRender'](addedNodesArray, arrayValue);
55.3127 - };
55.3128 -
55.3129 - return ko.dependentObservable(function () {
55.3130 - var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
55.3131 - if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
55.3132 - unwrappedArray = [unwrappedArray];
55.3133 -
55.3134 - // Filter out any entries marked as destroyed
55.3135 - var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
55.3136 - return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
55.3137 - });
55.3138 -
55.3139 - // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
55.3140 - // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
55.3141 - ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
55.3142 -
55.3143 - }, null, { disposeWhenNodeIsRemoved: targetNode });
55.3144 - };
55.3145 -
55.3146 - var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
55.3147 - function disposeOldComputedAndStoreNewOne(element, newComputed) {
55.3148 - var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
55.3149 - if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
55.3150 - oldComputed.dispose();
55.3151 - ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
55.3152 - }
55.3153 -
55.3154 - ko.bindingHandlers['template'] = {
55.3155 - 'init': function(element, valueAccessor) {
55.3156 - // Support anonymous templates
55.3157 - var bindingValue = ko.utils.unwrapObservable(valueAccessor());
55.3158 - if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
55.3159 - // It's an anonymous template - store the element contents, then clear the element
55.3160 - var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
55.3161 - container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
55.3162 - new ko.templateSources.anonymousTemplate(element)['nodes'](container);
55.3163 - }
55.3164 - return { 'controlsDescendantBindings': true };
55.3165 - },
55.3166 - 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
55.3167 - var templateName = ko.utils.unwrapObservable(valueAccessor()),
55.3168 - options = {},
55.3169 - shouldDisplay = true,
55.3170 - dataValue,
55.3171 - templateComputed = null;
55.3172 -
55.3173 - if (typeof templateName != "string") {
55.3174 - options = templateName;
55.3175 - templateName = options['name'];
55.3176 -
55.3177 - // Support "if"/"ifnot" conditions
55.3178 - if ('if' in options)
55.3179 - shouldDisplay = ko.utils.unwrapObservable(options['if']);
55.3180 - if (shouldDisplay && 'ifnot' in options)
55.3181 - shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
55.3182 -
55.3183 - dataValue = ko.utils.unwrapObservable(options['data']);
55.3184 - }
55.3185 -
55.3186 - if ('foreach' in options) {
55.3187 - // Render once for each data point (treating data set as empty if shouldDisplay==false)
55.3188 - var dataArray = (shouldDisplay && options['foreach']) || [];
55.3189 - templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
55.3190 - } else if (!shouldDisplay) {
55.3191 - ko.virtualElements.emptyNode(element);
55.3192 - } else {
55.3193 - // Render once for this single data point (or use the viewModel if no data was provided)
55.3194 - var innerBindingContext = ('data' in options) ?
55.3195 - bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
55.3196 - bindingContext; // Given no explicit 'data' value, we retain the same binding context
55.3197 - templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
55.3198 - }
55.3199 -
55.3200 - // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
55.3201 - disposeOldComputedAndStoreNewOne(element, templateComputed);
55.3202 - }
55.3203 - };
55.3204 -
55.3205 - // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
55.3206 - ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
55.3207 - var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
55.3208 -
55.3209 - if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
55.3210 - return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
55.3211 -
55.3212 - if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
55.3213 - return null; // Named templates can be rewritten, so return "no error"
55.3214 - return "This template engine does not support anonymous templates nested within its templates";
55.3215 - };
55.3216 -
55.3217 - ko.virtualElements.allowedBindings['template'] = true;
55.3218 -})();
55.3219 -
55.3220 -ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
55.3221 -ko.exportSymbol('renderTemplate', ko.renderTemplate);
55.3222 -
55.3223 -ko.utils.compareArrays = (function () {
55.3224 - var statusNotInOld = 'added', statusNotInNew = 'deleted';
55.3225 -
55.3226 - // Simple calculation based on Levenshtein distance.
55.3227 - function compareArrays(oldArray, newArray, dontLimitMoves) {
55.3228 - oldArray = oldArray || [];
55.3229 - newArray = newArray || [];
55.3230 -
55.3231 - if (oldArray.length <= newArray.length)
55.3232 - return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
55.3233 - else
55.3234 - return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
55.3235 - }
55.3236 -
55.3237 - function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
55.3238 - var myMin = Math.min,
55.3239 - myMax = Math.max,
55.3240 - editDistanceMatrix = [],
55.3241 - smlIndex, smlIndexMax = smlArray.length,
55.3242 - bigIndex, bigIndexMax = bigArray.length,
55.3243 - compareRange = (bigIndexMax - smlIndexMax) || 1,
55.3244 - maxDistance = smlIndexMax + bigIndexMax + 1,
55.3245 - thisRow, lastRow,
55.3246 - bigIndexMaxForRow, bigIndexMinForRow;
55.3247 -
55.3248 - for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
55.3249 - lastRow = thisRow;
55.3250 - editDistanceMatrix.push(thisRow = []);
55.3251 - bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
55.3252 - bigIndexMinForRow = myMax(0, smlIndex - 1);
55.3253 - for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
55.3254 - if (!bigIndex)
55.3255 - thisRow[bigIndex] = smlIndex + 1;
55.3256 - else if (!smlIndex) // Top row - transform empty array into new array via additions
55.3257 - thisRow[bigIndex] = bigIndex + 1;
55.3258 - else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
55.3259 - thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
55.3260 - else {
55.3261 - var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
55.3262 - var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
55.3263 - thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
55.3264 - }
55.3265 - }
55.3266 - }
55.3267 -
55.3268 - var editScript = [], meMinusOne, notInSml = [], notInBig = [];
55.3269 - for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
55.3270 - meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
55.3271 - if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
55.3272 - notInSml.push(editScript[editScript.length] = { // added
55.3273 - 'status': statusNotInSml,
55.3274 - 'value': bigArray[--bigIndex],
55.3275 - 'index': bigIndex });
55.3276 - } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
55.3277 - notInBig.push(editScript[editScript.length] = { // deleted
55.3278 - 'status': statusNotInBig,
55.3279 - 'value': smlArray[--smlIndex],
55.3280 - 'index': smlIndex });
55.3281 - } else {
55.3282 - editScript.push({
55.3283 - 'status': "retained",
55.3284 - 'value': bigArray[--bigIndex] });
55.3285 - --smlIndex;
55.3286 - }
55.3287 - }
55.3288 -
55.3289 - if (notInSml.length && notInBig.length) {
55.3290 - // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
55.3291 - // smlIndexMax keeps the time complexity of this algorithm linear.
55.3292 - var limitFailedCompares = smlIndexMax * 10, failedCompares,
55.3293 - a, d, notInSmlItem, notInBigItem;
55.3294 - // Go through the items that have been added and deleted and try to find matches between them.
55.3295 - for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
55.3296 - for (d = 0; notInBigItem = notInBig[d]; d++) {
55.3297 - if (notInSmlItem['value'] === notInBigItem['value']) {
55.3298 - notInSmlItem['moved'] = notInBigItem['index'];
55.3299 - notInBigItem['moved'] = notInSmlItem['index'];
55.3300 - notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
55.3301 - failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
55.3302 - break;
55.3303 - }
55.3304 - }
55.3305 - failedCompares += d;
55.3306 - }
55.3307 - }
55.3308 - return editScript.reverse();
55.3309 - }
55.3310 -
55.3311 - return compareArrays;
55.3312 -})();
55.3313 -
55.3314 -ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
55.3315 -
55.3316 -(function () {
55.3317 - // Objective:
55.3318 - // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
55.3319 - // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
55.3320 - // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
55.3321 - // 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
55.3322 - // previously mapped - retain those nodes, and just insert/delete other ones
55.3323 -
55.3324 - // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
55.3325 - // You can use this, for example, to activate bindings on those nodes.
55.3326 -
55.3327 - function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
55.3328 - // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
55.3329 - // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
55.3330 - // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
55.3331 - // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
55.3332 - // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
55.3333 - //
55.3334 - // Rules:
55.3335 - // [A] Any leading nodes that aren't in the document any more should be ignored
55.3336 - // These most likely correspond to memoization nodes that were already removed during binding
55.3337 - // See https://github.com/SteveSanderson/knockout/pull/440
55.3338 - // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
55.3339 - // have already been removed, and include any nodes that have been inserted among the previous collection
55.3340 -
55.3341 - // Rule [A]
55.3342 - while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
55.3343 - contiguousNodeArray.splice(0, 1);
55.3344 -
55.3345 - // Rule [B]
55.3346 - if (contiguousNodeArray.length > 1) {
55.3347 - // Build up the actual new contiguous node set
55.3348 - var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
55.3349 - while (current !== last) {
55.3350 - current = current.nextSibling;
55.3351 - if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
55.3352 - return;
55.3353 - newContiguousSet.push(current);
55.3354 - }
55.3355 -
55.3356 - // ... then mutate the input array to match this.
55.3357 - // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
55.3358 - Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
55.3359 - }
55.3360 - return contiguousNodeArray;
55.3361 - }
55.3362 -
55.3363 - function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
55.3364 - // Map this array value inside a dependentObservable so we re-map when any dependency changes
55.3365 - var mappedNodes = [];
55.3366 - var dependentObservable = ko.dependentObservable(function() {
55.3367 - var newMappedNodes = mapping(valueToMap, index) || [];
55.3368 -
55.3369 - // On subsequent evaluations, just replace the previously-inserted DOM nodes
55.3370 - if (mappedNodes.length > 0) {
55.3371 - ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
55.3372 - if (callbackAfterAddingNodes)
55.3373 - ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
55.3374 - }
55.3375 -
55.3376 - // Replace the contents of the mappedNodes array, thereby updating the record
55.3377 - // of which nodes would be deleted if valueToMap was itself later removed
55.3378 - mappedNodes.splice(0, mappedNodes.length);
55.3379 - ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
55.3380 - }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
55.3381 - return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
55.3382 - }
55.3383 -
55.3384 - var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
55.3385 -
55.3386 - ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
55.3387 - // Compare the provided array against the previous one
55.3388 - array = array || [];
55.3389 - options = options || {};
55.3390 - var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
55.3391 - var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
55.3392 - var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
55.3393 - var editScript = ko.utils.compareArrays(lastArray, array);
55.3394 -
55.3395 - // Build the new mapping result
55.3396 - var newMappingResult = [];
55.3397 - var lastMappingResultIndex = 0;
55.3398 - var newMappingResultIndex = 0;
55.3399 -
55.3400 - var nodesToDelete = [];
55.3401 - var itemsToProcess = [];
55.3402 - var itemsForBeforeRemoveCallbacks = [];
55.3403 - var itemsForMoveCallbacks = [];
55.3404 - var itemsForAfterAddCallbacks = [];
55.3405 - var mapData;
55.3406 -
55.3407 - function itemMovedOrRetained(editScriptIndex, oldPosition) {
55.3408 - mapData = lastMappingResult[oldPosition];
55.3409 - if (newMappingResultIndex !== oldPosition)
55.3410 - itemsForMoveCallbacks[editScriptIndex] = mapData;
55.3411 - // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
55.3412 - mapData.indexObservable(newMappingResultIndex++);
55.3413 - fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
55.3414 - newMappingResult.push(mapData);
55.3415 - itemsToProcess.push(mapData);
55.3416 - }
55.3417 -
55.3418 - function callCallback(callback, items) {
55.3419 - if (callback) {
55.3420 - for (var i = 0, n = items.length; i < n; i++) {
55.3421 - if (items[i]) {
55.3422 - ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
55.3423 - callback(node, i, items[i].arrayEntry);
55.3424 - });
55.3425 - }
55.3426 - }
55.3427 - }
55.3428 - }
55.3429 -
55.3430 - for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
55.3431 - movedIndex = editScriptItem['moved'];
55.3432 - switch (editScriptItem['status']) {
55.3433 - case "deleted":
55.3434 - if (movedIndex === undefined) {
55.3435 - mapData = lastMappingResult[lastMappingResultIndex];
55.3436 -
55.3437 - // Stop tracking changes to the mapping for these nodes
55.3438 - if (mapData.dependentObservable)
55.3439 - mapData.dependentObservable.dispose();
55.3440 -
55.3441 - // Queue these nodes for later removal
55.3442 - nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
55.3443 - if (options['beforeRemove']) {
55.3444 - itemsForBeforeRemoveCallbacks[i] = mapData;
55.3445 - itemsToProcess.push(mapData);
55.3446 - }
55.3447 - }
55.3448 - lastMappingResultIndex++;
55.3449 - break;
55.3450 -
55.3451 - case "retained":
55.3452 - itemMovedOrRetained(i, lastMappingResultIndex++);
55.3453 - break;
55.3454 -
55.3455 - case "added":
55.3456 - if (movedIndex !== undefined) {
55.3457 - itemMovedOrRetained(i, movedIndex);
55.3458 - } else {
55.3459 - mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
55.3460 - newMappingResult.push(mapData);
55.3461 - itemsToProcess.push(mapData);
55.3462 - if (!isFirstExecution)
55.3463 - itemsForAfterAddCallbacks[i] = mapData;
55.3464 - }
55.3465 - break;
55.3466 - }
55.3467 - }
55.3468 -
55.3469 - // Call beforeMove first before any changes have been made to the DOM
55.3470 - callCallback(options['beforeMove'], itemsForMoveCallbacks);
55.3471 -
55.3472 - // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
55.3473 - ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
55.3474 -
55.3475 - // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
55.3476 - for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
55.3477 - // Get nodes for newly added items
55.3478 - if (!mapData.mappedNodes)
55.3479 - ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
55.3480 -
55.3481 - // Put nodes in the right place if they aren't there already
55.3482 - for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
55.3483 - if (node !== nextNode)
55.3484 - ko.virtualElements.insertAfter(domNode, node, lastNode);
55.3485 - }
55.3486 -
55.3487 - // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
55.3488 - if (!mapData.initialized && callbackAfterAddingNodes) {
55.3489 - callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
55.3490 - mapData.initialized = true;
55.3491 - }
55.3492 - }
55.3493 -
55.3494 - // If there's a beforeRemove callback, call it after reordering.
55.3495 - // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
55.3496 - // some sort of animation, which is why we first reorder the nodes that will be removed. If the
55.3497 - // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
55.3498 - // Perhaps we'll make that change in the future if this scenario becomes more common.
55.3499 - callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
55.3500 -
55.3501 - // Finally call afterMove and afterAdd callbacks
55.3502 - callCallback(options['afterMove'], itemsForMoveCallbacks);
55.3503 - callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
55.3504 -
55.3505 - // Store a copy of the array items we just considered so we can difference it next time
55.3506 - ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
55.3507 - }
55.3508 -})();
55.3509 -
55.3510 -ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
55.3511 -ko.nativeTemplateEngine = function () {
55.3512 - this['allowTemplateRewriting'] = false;
55.3513 -}
55.3514 -
55.3515 -ko.nativeTemplateEngine.prototype = new ko.templateEngine();
55.3516 -ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
55.3517 - var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
55.3518 - templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
55.3519 - templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
55.3520 -
55.3521 - if (templateNodes) {
55.3522 - return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
55.3523 - } else {
55.3524 - var templateText = templateSource['text']();
55.3525 - return ko.utils.parseHtmlFragment(templateText);
55.3526 - }
55.3527 -};
55.3528 -
55.3529 -ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
55.3530 -ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
55.3531 -
55.3532 -ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
55.3533 -(function() {
55.3534 - ko.jqueryTmplTemplateEngine = function () {
55.3535 - // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
55.3536 - // doesn't expose a version number, so we have to infer it.
55.3537 - // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
55.3538 - // which KO internally refers to as version "2", so older versions are no longer detected.
55.3539 - var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
55.3540 - if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
55.3541 - return 0;
55.3542 - // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
55.3543 - try {
55.3544 - if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
55.3545 - // Since 1.0.0pre, custom tags should append markup to an array called "__"
55.3546 - return 2; // Final version of jquery.tmpl
55.3547 - }
55.3548 - } catch(ex) { /* Apparently not the version we were looking for */ }
55.3549 -
55.3550 - return 1; // Any older version that we don't support
55.3551 - })();
55.3552 -
55.3553 - function ensureHasReferencedJQueryTemplates() {
55.3554 - if (jQueryTmplVersion < 2)
55.3555 - throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
55.3556 - }
55.3557 -
55.3558 - function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
55.3559 - return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
55.3560 - }
55.3561 -
55.3562 - this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
55.3563 - options = options || {};
55.3564 - ensureHasReferencedJQueryTemplates();
55.3565 -
55.3566 - // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
55.3567 - var precompiled = templateSource['data']('precompiled');
55.3568 - if (!precompiled) {
55.3569 - var templateText = templateSource['text']() || "";
55.3570 - // Wrap in "with($whatever.koBindingContext) { ... }"
55.3571 - templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
55.3572 -
55.3573 - precompiled = jQuery['template'](null, templateText);
55.3574 - templateSource['data']('precompiled', precompiled);
55.3575 - }
55.3576 -
55.3577 - var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
55.3578 - var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
55.3579 -
55.3580 - var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
55.3581 - resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
55.3582 -
55.3583 - jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
55.3584 - return resultNodes;
55.3585 - };
55.3586 -
55.3587 - this['createJavaScriptEvaluatorBlock'] = function(script) {
55.3588 - return "{{ko_code ((function() { return " + script + " })()) }}";
55.3589 - };
55.3590 -
55.3591 - this['addTemplate'] = function(templateName, templateMarkup) {
55.3592 - document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
55.3593 - };
55.3594 -
55.3595 - if (jQueryTmplVersion > 0) {
55.3596 - jQuery['tmpl']['tag']['ko_code'] = {
55.3597 - open: "__.push($1 || '');"
55.3598 - };
55.3599 - jQuery['tmpl']['tag']['ko_with'] = {
55.3600 - open: "with($1) {",
55.3601 - close: "} "
55.3602 - };
55.3603 - }
55.3604 - };
55.3605 -
55.3606 - ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
55.3607 -
55.3608 - // Use this one by default *only if jquery.tmpl is referenced*
55.3609 - var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
55.3610 - if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
55.3611 - ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
55.3612 -
55.3613 - ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
55.3614 -})();
55.3615 -});
55.3616 -})(window,document,navigator,window["jQuery"]);
55.3617 -})();
55.3618 \ No newline at end of file
56.1 --- a/ko-bck2brwsr/src/test/java/org/apidesign/html/ko2brwsr/Bck2BrwsrKnockoutTest.java Wed May 29 19:36:31 2013 +0200
56.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
56.3 @@ -1,81 +0,0 @@
56.4 -/**
56.5 - * HTML via Java(tm) Language Bindings
56.6 - * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
56.7 - *
56.8 - * This program is free software: you can redistribute it and/or modify
56.9 - * it under the terms of the GNU General Public License as published by
56.10 - * the Free Software Foundation, version 2 of the License.
56.11 - *
56.12 - * This program is distributed in the hope that it will be useful,
56.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
56.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
56.15 - * GNU General Public License for more details. apidesign.org
56.16 - * designates this particular file as subject to the
56.17 - * "Classpath" exception as provided by apidesign.org
56.18 - * in the License file that accompanied this code.
56.19 - *
56.20 - * You should have received a copy of the GNU General Public License
56.21 - * along with this program. Look for COPYING file in the top folder.
56.22 - * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
56.23 - */
56.24 -package org.apidesign.html.ko2brwsr;
56.25 -
56.26 -import java.util.Map;
56.27 -import net.java.html.BrwsrCtx;
56.28 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
56.29 -import org.apidesign.bck2brwsr.vmtest.VMTest;
56.30 -import org.apidesign.html.context.spi.Contexts;
56.31 -import org.apidesign.html.json.spi.Technology;
56.32 -import org.apidesign.html.json.spi.Transfer;
56.33 -import org.apidesign.html.json.tck.KnockoutTCK;
56.34 -import org.openide.util.lookup.ServiceProvider;
56.35 -import org.testng.annotations.Factory;
56.36 -
56.37 -/**
56.38 - *
56.39 - * @author Jaroslav Tulach <jtulach@netbeans.org>
56.40 - */
56.41 -@ServiceProvider(service = KnockoutTCK.class)
56.42 -public final class Bck2BrwsrKnockoutTest extends KnockoutTCK {
56.43 - @Factory public static Object[] create() {
56.44 - return VMTest.newTests().
56.45 - withClasses(testClasses()).
56.46 - withLaunchers("bck2brwsr").
56.47 - build();
56.48 - }
56.49 -
56.50 - @Override
56.51 - public BrwsrCtx createContext() {
56.52 - return Contexts.newBuilder().
56.53 - register(Transfer.class, BrwsrCtxImpl.DEFAULT, 9).
56.54 - register(Technology.class, BrwsrCtxImpl.DEFAULT, 9).build();
56.55 - }
56.56 -
56.57 -
56.58 -
56.59 - @Override
56.60 - public Object createJSON(Map<String, Object> values) {
56.61 - Object json = createJSON();
56.62 -
56.63 - for (Map.Entry<String, Object> entry : values.entrySet()) {
56.64 - putValue(json, entry.getKey(), entry.getValue());
56.65 - }
56.66 - return json;
56.67 - }
56.68 -
56.69 - @JavaScriptBody(args = {}, body = "return new Object();")
56.70 - private static native Object createJSON();
56.71 -
56.72 - @JavaScriptBody(args = { "json", "key", "value" }, body = "json[key] = value;")
56.73 - private static native void putValue(Object json, String key, Object value);
56.74 -
56.75 - @Override
56.76 - public Object executeScript(String script, Object[] arguments) {
56.77 - return execScript(script, arguments);
56.78 - }
56.79 -
56.80 - @JavaScriptBody(args = { "s", "args" }, body =
56.81 - "var f = new Function(s); return f.apply(null, args);"
56.82 - )
56.83 - private static native Object execScript(String s, Object[] arguments);
56.84 -}
57.1 --- a/ko-fx/pom.xml Wed May 29 19:36:31 2013 +0200
57.2 +++ b/ko-fx/pom.xml Wed Jun 26 18:09:25 2013 +0200
57.3 @@ -43,12 +43,11 @@
57.4 <dependency>
57.5 <groupId>org.apidesign.html</groupId>
57.6 <artifactId>net.java.html.json</artifactId>
57.7 - <version>0.4-SNAPSHOT</version>
57.8 + <version>${project.version}</version>
57.9 </dependency>
57.10 <dependency>
57.11 <groupId>org.testng</groupId>
57.12 <artifactId>testng</artifactId>
57.13 - <version>6.5.2</version>
57.14 <scope>test</scope>
57.15 </dependency>
57.16 <dependency>
57.17 @@ -63,9 +62,21 @@
57.18 <scope>provided</scope>
57.19 </dependency>
57.20 <dependency>
57.21 - <groupId>org.apidesign.bck2brwsr</groupId>
57.22 - <artifactId>launcher.fx</artifactId>
57.23 - <version>${bck2brwsr.launcher.version}</version>
57.24 + <groupId>org.apidesign.html</groupId>
57.25 + <artifactId>net.java.html.boot</artifactId>
57.26 + <version>${project.version}</version>
57.27 + <type>jar</type>
57.28 + </dependency>
57.29 + <dependency>
57.30 + <groupId>${project.groupId}</groupId>
57.31 + <artifactId>boot-fx</artifactId>
57.32 + <version>${project.version}</version>
57.33 + <scope>test</scope>
57.34 + </dependency>
57.35 + <dependency>
57.36 + <groupId>org.glassfish.grizzly</groupId>
57.37 + <artifactId>grizzly-http-server</artifactId>
57.38 + <version>2.3.3</version>
57.39 <scope>test</scope>
57.40 </dependency>
57.41 </dependencies>
58.1 --- a/ko-fx/src/main/java/org/apidesign/html/kofx/Console.java Wed May 29 19:36:31 2013 +0200
58.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/Console.java Wed Jun 26 18:09:25 2013 +0200
58.3 @@ -21,8 +21,7 @@
58.4 package org.apidesign.html.kofx;
58.5
58.6 import java.util.logging.Logger;
58.7 -import javafx.scene.web.WebEngine;
58.8 -import netscape.javascript.JSObject;
58.9 +import net.java.html.js.JavaScriptBody;
58.10
58.11 /** This is an implementation package - just
58.12 * include its JAR on classpath and use official {@link Context} API
58.13 @@ -38,14 +37,18 @@
58.14 private Console() {
58.15 }
58.16
58.17 - static void register(WebEngine web) {
58.18 - ((JSObject)web.executeScript("window")).setMember("jconsole", new Console());
58.19 - web.executeScript("console.log = function(m) { jconsole.log(m); };");
58.20 - web.executeScript("console.info = function(m) { jconsole.log(m); };");
58.21 - web.executeScript("console.error = function(m) { jconsole.log(m); };");
58.22 - web.executeScript("console.warn = function(m) { jconsole.log(m); };");
58.23 + static void register() {
58.24 + registerImpl(new Console());
58.25 }
58.26
58.27 + @JavaScriptBody(args = { "jconsole" }, body =
58.28 + "console.log = function(m) { jconsole.log(m); };" +
58.29 + "console.info = function(m) { jconsole.log(m); };" +
58.30 + "console.error = function(m) { jconsole.log(m); };" +
58.31 + "console.warn = function(m) { jconsole.log(m); };"
58.32 + )
58.33 + private static native void registerImpl(Console c);
58.34 +
58.35 public void log(String msg) {
58.36 LOG.info(msg);
58.37 }
59.1 --- a/ko-fx/src/main/java/org/apidesign/html/kofx/FXContext.java Wed May 29 19:36:31 2013 +0200
59.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/FXContext.java Wed Jun 26 18:09:25 2013 +0200
59.3 @@ -24,6 +24,7 @@
59.4 import java.io.InputStream;
59.5 import java.util.ServiceLoader;
59.6 import java.util.logging.Logger;
59.7 +import net.java.html.js.JavaScriptBody;
59.8 import netscape.javascript.JSObject;
59.9 import org.apidesign.html.context.spi.Contexts;
59.10 import org.apidesign.html.json.spi.FunctionBinding;
59.11 @@ -45,10 +46,15 @@
59.12 public final class FXContext
59.13 implements Technology<JSObject>, Transfer, Contexts.Provider {
59.14 static final Logger LOG = Logger.getLogger(FXContext.class.getName());
59.15 +
59.16 + @JavaScriptBody(args = {}, body = "return true;")
59.17 + private static boolean isJavaScriptEnabled() {
59.18 + return false;
59.19 + }
59.20
59.21 @Override
59.22 public void fillContext(Contexts.Builder context, Class<?> requestor) {
59.23 - if (Knockout.web() != null) {
59.24 + if (isJavaScriptEnabled()) {
59.25 context.register(Technology.class, this, 100);
59.26 context.register(Transfer.class, this, 100);
59.27 }
60.1 --- a/ko-fx/src/main/java/org/apidesign/html/kofx/Knockout.java Wed May 29 19:36:31 2013 +0200
60.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/Knockout.java Wed Jun 26 18:09:25 2013 +0200
60.3 @@ -26,7 +26,8 @@
60.4 import java.io.InputStreamReader;
60.5 import java.util.logging.Level;
60.6 import java.util.logging.Logger;
60.7 -import javafx.scene.web.WebEngine;
60.8 +import net.java.html.js.JavaScriptBody;
60.9 +import net.java.html.js.JavaScriptResource;
60.10 import net.java.html.json.Model;
60.11 import netscape.javascript.JSObject;
60.12 import org.apidesign.html.json.spi.FunctionBinding;
60.13 @@ -41,6 +42,7 @@
60.14 *
60.15 * @author Jaroslav Tulach <jtulach@netbeans.org>
60.16 */
60.17 +@JavaScriptResource("knockout-2.2.1.js")
60.18 public final class Knockout {
60.19 private static final Logger LOG = Logger.getLogger(Knockout.class.getName());
60.20 /** used by tests */
60.21 @@ -59,8 +61,9 @@
60.22 return InvokeJS.KObject.call("array", arr);
60.23 }
60.24
60.25 + private static int cnt;
60.26 public static <M> Knockout createBinding(Object model) {
60.27 - Object bindings = InvokeJS.KObject.call("create", model);
60.28 + Object bindings = InvokeJS.create(model, ++cnt);
60.29 return new Knockout(bindings);
60.30 }
60.31
60.32 @@ -82,14 +85,9 @@
60.33 static void bind(
60.34 Object bindings, Object model, PropertyBinding pb, boolean primitive, boolean array
60.35 ) {
60.36 - WebEngine e = web();
60.37 - if (e == null) {
60.38 - return;
60.39 - }
60.40 -
60.41 final String prop = pb.getPropertyName();
60.42 try {
60.43 - InvokeJS.KObject.call("bind", bindings, pb, prop, "getValue", pb.isReadOnly() ? null : "setValue", primitive, array);
60.44 + InvokeJS.bind(bindings, pb, prop, "getValue", pb.isReadOnly() ? null : "setValue", primitive, array);
60.45
60.46 ((JSObject)bindings).setMember("ko-fx.model", model);
60.47 LOG.log(Level.FINE, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
60.48 @@ -98,75 +96,56 @@
60.49 }
60.50 }
60.51 static void expose(Object bindings, FunctionBinding f) {
60.52 - WebEngine e = web();
60.53 - if (e == null) {
60.54 - return;
60.55 - }
60.56 final String prop = f.getFunctionName();
60.57 try {
60.58 - InvokeJS.KObject.call("expose", bindings, f, prop, "call");
60.59 + InvokeJS.expose(bindings, f, prop, "call");
60.60 } catch (Throwable ex) {
60.61 LOG.log(Level.SEVERE, "Cannot define binding for " + prop + " in model " + f, ex);
60.62 }
60.63 }
60.64
60.65 static void applyBindings(Object bindings) {
60.66 - if (web() != null) {
60.67 - JSObject ko = (JSObject) web().executeScript("ko");
60.68 - ko.call("applyBindings", bindings);
60.69 - }
60.70 + InvokeJS.applyBindings(bindings);
60.71 }
60.72
60.73 - static WebEngine web() {
60.74 - return (WebEngine) System.getProperties().get("webEngine");
60.75 - }
60.76 -
60.77 -
60.78 private static final class InvokeJS {
60.79 static final JSObject KObject;
60.80
60.81 static {
60.82 - final InputStream koScript = Knockout.class.getResourceAsStream("knockout-2.2.1.js");
60.83 - assert koScript != null : "Can't load knockout.js";
60.84 - BufferedReader r = new BufferedReader(new InputStreamReader(koScript));
60.85 - StringBuilder sb = new StringBuilder();
60.86 - for (;;) {
60.87 - try {
60.88 - String l = r.readLine();
60.89 - if (l == null) {
60.90 - break;
60.91 - }
60.92 - sb.append(l).append('\n');
60.93 - } catch (IOException ex) {
60.94 - throw new IllegalStateException(ex);
60.95 - }
60.96 - }
60.97 - web().executeScript(sb.toString());
60.98 - Object ko = web().executeScript("ko");
60.99 - assert ko != null : "Knockout library successfully defined 'ko'";
60.100 -
60.101 - Console.register(web());
60.102 - KObject = (JSObject) web().executeScript(
60.103 - "(function(scope) {"
60.104 - + " var kCnt = 0; "
60.105 - + " scope.KObject = {};"
60.106 - + " scope.KObject.create= function(value) {"
60.107 - + " var cnt = ++kCnt;"
60.108 - + " var ret = {};"
60.109 + Console.register();
60.110 + KObject = (JSObject) kObj();
60.111 + }
60.112 +
60.113 + @JavaScriptBody(args = { "s" }, body = "return eval(s);")
60.114 + private static native Object exec(String s);
60.115 +
60.116 + @JavaScriptBody(args = {}, body =
60.117 + " var k = {};"
60.118 + + " k.array= function() {"
60.119 + + " return Array.prototype.slice.call(arguments);"
60.120 + + " };"
60.121 + + " return k;"
60.122 + )
60.123 + private static native Object kObj();
60.124 +
60.125 + @JavaScriptBody(args = { "value", "cnt " }, body =
60.126 + " var ret = {};"
60.127 + " ret.toString = function() { return 'KObject' + cnt + ' value: ' + value + ' props: ' + Object.keys(this); };"
60.128 + " return ret;"
60.129 - + " };"
60.130 - + " scope.KObject.array= function() {"
60.131 - + " return Array.prototype.slice.call(arguments);"
60.132 - + " };"
60.133 - + " scope.KObject.expose = function(bindings, model, prop, sig) {"
60.134 - + " bindings[prop] = function(data, ev) {"
60.135 - // + " console.log(\" callback on prop: \" + prop);"
60.136 - + " model[sig](data, ev);"
60.137 - + " };"
60.138 - + " };"
60.139 - + " scope.KObject.bind = function(bindings, model, prop, getter, setter, primitive, array) {"
60.140 - + " var bnd = {"
60.141 + )
60.142 + static native Object create(Object value, int cnt);
60.143 +
60.144 + @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body =
60.145 + " bindings[prop] = function(data, ev) {"
60.146 + // + " console.log(\" callback on prop: \" + prop);"
60.147 + + " model[sig](data, ev);"
60.148 + + " };"
60.149 + )
60.150 + static native Object expose(Object bindings, Object model, String prop, String sig);
60.151 +
60.152 +
60.153 + @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
60.154 + " var bnd = {"
60.155 + " read: function() {"
60.156 + " try {"
60.157 + " var v = model[getter]();"
60.158 @@ -194,9 +173,10 @@
60.159 + " };"
60.160 + " };"
60.161 + " bindings[prop] = ko.computed(bnd);"
60.162 - + " };"
60.163 - + "})(window); window.KObject");
60.164 - }
60.165 -
60.166 + )
60.167 + static native void bind(Object binding, Object model, String prop, String getter, String setter, boolean primitive, boolean array);
60.168 +
60.169 + @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
60.170 + private static native void applyBindings(Object bindings);
60.171 }
60.172 }
61.1 --- a/ko-fx/src/main/java/org/apidesign/html/kofx/LoadJSON.java Wed May 29 19:36:31 2013 +0200
61.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/LoadJSON.java Wed Jun 26 18:09:25 2013 +0200
61.3 @@ -33,10 +33,11 @@
61.4 import java.util.Iterator;
61.5 import java.util.concurrent.Executor;
61.6 import java.util.concurrent.Executors;
61.7 +import java.util.concurrent.ThreadFactory;
61.8 import java.util.logging.Level;
61.9 import java.util.logging.Logger;
61.10 import javafx.application.Platform;
61.11 -import javafx.scene.web.WebEngine;
61.12 +import net.java.html.js.JavaScriptBody;
61.13 import netscape.javascript.JSObject;
61.14 import org.apidesign.html.json.spi.JSONCall;
61.15 import org.json.JSONArray;
61.16 @@ -52,7 +53,14 @@
61.17 */
61.18 final class LoadJSON implements Runnable {
61.19 private static final Logger LOG = FXContext.LOG;
61.20 - private static final Executor REQ = Executors.newCachedThreadPool();
61.21 + private static final Executor REQ = Executors.newCachedThreadPool(new ThreadFactory() {
61.22 + @Override
61.23 + public Thread newThread(Runnable runnable) {
61.24 + Thread thread = Executors.defaultThreadFactory().newThread(runnable);
61.25 + thread.setDaemon(true);
61.26 + return thread;
61.27 + }
61.28 + });
61.29
61.30 private final JSONCall call;
61.31 private final URL base;
61.32 @@ -130,10 +138,14 @@
61.33 }
61.34 } else {
61.35 int ch = is.read();
61.36 - array = ch == '[';
61.37 - is.unread(ch);
61.38 - if (!array && ch != '{') {
61.39 + if (ch == -1) {
61.40 string = true;
61.41 + } else {
61.42 + array = ch == '[';
61.43 + is.unread(ch);
61.44 + if (!array && ch != '{') {
61.45 + string = true;
61.46 + }
61.47 }
61.48 }
61.49 try {
61.50 @@ -216,18 +228,17 @@
61.51 throw new IOException(ex);
61.52 }
61.53 }
61.54 +
61.55 + @JavaScriptBody(args = { }, body =
61.56 + "var h;"
61.57 + + "if (!!window && !!window.location && !!window.location.href)\n"
61.58 + + " h = window.location.href;\n"
61.59 + + "else "
61.60 + + " h = null;"
61.61 + + "return h;\n"
61.62 + )
61.63 + private static native String findBaseURL();
61.64
61.65 - private static String findBaseURL() {
61.66 - WebEngine eng = (WebEngine) System.getProperties().get("webEngine");
61.67 - return (String) eng.executeScript(
61.68 - "var h;"
61.69 - + "if (!!window && !!window.location && !!window.location.href)\n"
61.70 - + " h = window.location.href;\n"
61.71 - + "else "
61.72 - + " h = null;"
61.73 - + "h\n");
61.74 - }
61.75 -
61.76 private static boolean isDefined(Object val) {
61.77 return !"undefined".equals(val);
61.78 }
62.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
62.2 +++ b/ko-fx/src/test/java/org/apidesign/html/kofx/DynamicHTTP.java Wed Jun 26 18:09:25 2013 +0200
62.3 @@ -0,0 +1,189 @@
62.4 +/**
62.5 + * HTML via Java(tm) Language Bindings
62.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
62.7 + *
62.8 + * This program is free software: you can redistribute it and/or modify
62.9 + * it under the terms of the GNU General Public License as published by
62.10 + * the Free Software Foundation, version 2 of the License.
62.11 + *
62.12 + * This program is distributed in the hope that it will be useful,
62.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
62.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
62.15 + * GNU General Public License for more details. apidesign.org
62.16 + * designates this particular file as subject to the
62.17 + * "Classpath" exception as provided by apidesign.org
62.18 + * in the License file that accompanied this code.
62.19 + *
62.20 + * You should have received a copy of the GNU General Public License
62.21 + * along with this program. Look for COPYING file in the top folder.
62.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
62.23 + */
62.24 +package org.apidesign.html.kofx;
62.25 +
62.26 +import java.io.ByteArrayInputStream;
62.27 +import java.io.IOException;
62.28 +import java.io.InputStream;
62.29 +import java.io.OutputStream;
62.30 +import java.io.Reader;
62.31 +import java.net.URI;
62.32 +import java.net.URISyntaxException;
62.33 +import java.util.ArrayList;
62.34 +import java.util.List;
62.35 +import org.glassfish.grizzly.PortRange;
62.36 +import org.glassfish.grizzly.http.server.HttpHandler;
62.37 +import org.glassfish.grizzly.http.server.HttpServer;
62.38 +import org.glassfish.grizzly.http.server.NetworkListener;
62.39 +import org.glassfish.grizzly.http.server.Request;
62.40 +import org.glassfish.grizzly.http.server.Response;
62.41 +import org.glassfish.grizzly.http.server.ServerConfiguration;
62.42 +
62.43 +/**
62.44 + *
62.45 + * @author Jaroslav Tulach <jtulach@netbeans.org>
62.46 + */
62.47 +final class DynamicHTTP extends HttpHandler {
62.48 + private static int resourcesCount;
62.49 + private static List<Resource> resources;
62.50 + private static ServerConfiguration conf;
62.51 + private static HttpServer server;
62.52 +
62.53 + private DynamicHTTP() {
62.54 + }
62.55 +
62.56 + static URI initServer() throws Exception {
62.57 + server = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
62.58 + resources = new ArrayList<Resource>();
62.59 +
62.60 + conf = server.getServerConfiguration();
62.61 + final DynamicHTTP dh = new DynamicHTTP();
62.62 +
62.63 + conf.addHttpHandler(dh, "/");
62.64 +
62.65 + server.start();
62.66 +
62.67 + return pageURL(server, "/test.html");
62.68 + }
62.69 +
62.70 + @Override
62.71 + public void service(Request request, Response response) throws Exception {
62.72 + if ("/test.html".equals(request.getRequestURI())) {
62.73 + response.setContentType("text/html");
62.74 + final InputStream is = DynamicHTTP.class.getResourceAsStream("test.html");
62.75 + copyStream(is, response.getOutputStream(), null);
62.76 + return;
62.77 + }
62.78 + if ("/dynamic".equals(request.getRequestURI())) {
62.79 + String mimeType = request.getParameter("mimeType");
62.80 + List<String> params = new ArrayList<String>();
62.81 + for (int i = 0;; i++) {
62.82 + String p = request.getParameter("param" + i);
62.83 + if (p == null) {
62.84 + break;
62.85 + }
62.86 + params.add(p);
62.87 + }
62.88 + final String cnt = request.getParameter("content");
62.89 + String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
62.90 + ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
62.91 + URI url = registerResource(new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()])));
62.92 + response.getWriter().write(url.toString());
62.93 + response.getWriter().write("\n");
62.94 + return;
62.95 + }
62.96 +
62.97 + for (Resource r : resources) {
62.98 + if (r.httpPath.equals(request.getRequestURI())) {
62.99 + response.setContentType(r.httpType);
62.100 + r.httpContent.reset();
62.101 + String[] params = null;
62.102 + if (r.parameters.length != 0) {
62.103 + params = new String[r.parameters.length];
62.104 + for (int i = 0; i < r.parameters.length; i++) {
62.105 + params[i] = request.getParameter(r.parameters[i]);
62.106 + if (params[i] == null) {
62.107 + if ("http.method".equals(r.parameters[i])) {
62.108 + params[i] = request.getMethod().toString();
62.109 + } else if ("http.requestBody".equals(r.parameters[i])) {
62.110 + Reader rdr = request.getReader();
62.111 + StringBuilder sb = new StringBuilder();
62.112 + for (;;) {
62.113 + int ch = rdr.read();
62.114 + if (ch == -1) {
62.115 + break;
62.116 + }
62.117 + sb.append((char) ch);
62.118 + }
62.119 + params[i] = sb.toString();
62.120 + }
62.121 + }
62.122 + if (params[i] == null) {
62.123 + params[i] = "null";
62.124 + }
62.125 + }
62.126 + }
62.127 +
62.128 + copyStream(r.httpContent, response.getOutputStream(), null, params);
62.129 + }
62.130 + }
62.131 + }
62.132 +
62.133 + private URI registerResource(Resource r) {
62.134 + if (!resources.contains(r)) {
62.135 + resources.add(r);
62.136 + conf.addHttpHandler(this, r.httpPath);
62.137 + }
62.138 + return pageURL(server, r.httpPath);
62.139 + }
62.140 +
62.141 + private static URI pageURL(HttpServer server, final String page) {
62.142 + NetworkListener listener = server.getListeners().iterator().next();
62.143 + int port = listener.getPort();
62.144 + try {
62.145 + return new URI("http://localhost:" + port + page);
62.146 + } catch (URISyntaxException ex) {
62.147 + throw new IllegalStateException(ex);
62.148 + }
62.149 + }
62.150 +
62.151 + static final class Resource {
62.152 +
62.153 + final InputStream httpContent;
62.154 + final String httpType;
62.155 + final String httpPath;
62.156 + final String[] parameters;
62.157 +
62.158 + Resource(InputStream httpContent, String httpType, String httpPath,
62.159 + String[] parameters) {
62.160 + httpContent.mark(Integer.MAX_VALUE);
62.161 + this.httpContent = httpContent;
62.162 + this.httpType = httpType;
62.163 + this.httpPath = httpPath;
62.164 + this.parameters = parameters;
62.165 + }
62.166 + }
62.167 +
62.168 + static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
62.169 + for (;;) {
62.170 + int ch = is.read();
62.171 + if (ch == -1) {
62.172 + break;
62.173 + }
62.174 + if (ch == '$' && params.length > 0) {
62.175 + int cnt = is.read() - '0';
62.176 + if (baseURL != null && cnt == 'U' - '0') {
62.177 + os.write(baseURL.getBytes("UTF-8"));
62.178 + } else {
62.179 + if (cnt >= 0 && cnt < params.length) {
62.180 + os.write(params[cnt].getBytes("UTF-8"));
62.181 + } else {
62.182 + os.write('$');
62.183 + os.write(cnt + '0');
62.184 + }
62.185 + }
62.186 + } else {
62.187 + os.write(ch);
62.188 + }
62.189 + }
62.190 + }
62.191 +
62.192 +}
63.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
63.2 +++ b/ko-fx/src/test/java/org/apidesign/html/kofx/KOFx.java Wed Jun 26 18:09:25 2013 +0200
63.3 @@ -0,0 +1,89 @@
63.4 +/**
63.5 + * HTML via Java(tm) Language Bindings
63.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
63.7 + *
63.8 + * This program is free software: you can redistribute it and/or modify
63.9 + * it under the terms of the GNU General Public License as published by
63.10 + * the Free Software Foundation, version 2 of the License.
63.11 + *
63.12 + * This program is distributed in the hope that it will be useful,
63.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
63.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
63.15 + * GNU General Public License for more details. apidesign.org
63.16 + * designates this particular file as subject to the
63.17 + * "Classpath" exception as provided by apidesign.org
63.18 + * in the License file that accompanied this code.
63.19 + *
63.20 + * You should have received a copy of the GNU General Public License
63.21 + * along with this program. Look for COPYING file in the top folder.
63.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
63.23 + */
63.24 +package org.apidesign.html.kofx;
63.25 +
63.26 +import java.lang.reflect.InvocationTargetException;
63.27 +import java.lang.reflect.Method;
63.28 +import javafx.application.Platform;
63.29 +import org.testng.ITest;
63.30 +import org.testng.annotations.Test;
63.31 +
63.32 +/**
63.33 + *
63.34 + * @author Jaroslav Tulach <jtulach@netbeans.org>
63.35 + */
63.36 +public final class KOFx implements ITest, Runnable {
63.37 + private final Method m;
63.38 + private Object result;
63.39 + private Object inst;
63.40 +
63.41 + KOFx(Method m) {
63.42 + this.m = m;
63.43 + }
63.44 +
63.45 + @Override
63.46 + public String getTestName() {
63.47 + return m.getName();
63.48 + }
63.49 +
63.50 + @Test
63.51 + public synchronized void executeTest() throws Exception {
63.52 + if (result == null) {
63.53 + Platform.runLater(this);
63.54 + wait();
63.55 + }
63.56 + if (result instanceof Exception) {
63.57 + throw (Exception)result;
63.58 + }
63.59 + if (result instanceof Error) {
63.60 + throw (Error)result;
63.61 + }
63.62 + }
63.63 +
63.64 + @Override
63.65 + public synchronized void run() {
63.66 + boolean notify = true;
63.67 + try {
63.68 + if (inst == null) {
63.69 + inst = m.getDeclaringClass().newInstance();
63.70 + }
63.71 + result = m.invoke(inst);
63.72 + if (result == null) {
63.73 + result = this;
63.74 + }
63.75 + } catch (InvocationTargetException ex) {
63.76 + Throwable r = ex.getTargetException();
63.77 + if (r instanceof InterruptedException) {
63.78 + notify = false;
63.79 + Platform.runLater(this);
63.80 + return;
63.81 + }
63.82 + result = r;
63.83 + } catch (Exception ex) {
63.84 + result = ex;
63.85 + } finally {
63.86 + if (notify) {
63.87 + notifyAll();
63.88 + }
63.89 + }
63.90 + }
63.91 +
63.92 +}
64.1 --- a/ko-fx/src/test/java/org/apidesign/html/kofx/KnockoutFXTest.java Wed May 29 19:36:31 2013 +0200
64.2 +++ b/ko-fx/src/test/java/org/apidesign/html/kofx/KnockoutFXTest.java Wed Jun 26 18:09:25 2013 +0200
64.3 @@ -20,18 +20,32 @@
64.4 */
64.5 package org.apidesign.html.kofx;
64.6
64.7 +import java.io.BufferedReader;
64.8 +import java.io.IOException;
64.9 +import java.io.InputStreamReader;
64.10 +import java.lang.annotation.Annotation;
64.11 +import java.lang.reflect.Method;
64.12 +import java.net.URI;
64.13 +import java.net.URISyntaxException;
64.14 +import java.net.URL;
64.15 +import java.net.URLConnection;
64.16 +import java.util.ArrayList;
64.17 +import java.util.List;
64.18 import java.util.Map;
64.19 +import java.util.concurrent.Executors;
64.20 import net.java.html.BrwsrCtx;
64.21 -import netscape.javascript.JSObject;
64.22 -import org.apidesign.bck2brwsr.vmtest.VMTest;
64.23 +import net.java.html.boot.BrowserBuilder;
64.24 +import net.java.html.js.JavaScriptBody;
64.25 import org.apidesign.html.context.spi.Contexts;
64.26 import org.apidesign.html.json.spi.Technology;
64.27 import org.apidesign.html.json.spi.Transfer;
64.28 +import org.apidesign.html.json.tck.KOTest;
64.29 import org.apidesign.html.json.tck.KnockoutTCK;
64.30 import org.json.JSONException;
64.31 import org.json.JSONObject;
64.32 import org.openide.util.lookup.ServiceProvider;
64.33 import org.testng.annotations.Factory;
64.34 +import static org.testng.Assert.*;
64.35
64.36 /**
64.37 *
64.38 @@ -39,13 +53,68 @@
64.39 */
64.40 @ServiceProvider(service = KnockoutTCK.class)
64.41 public final class KnockoutFXTest extends KnockoutTCK {
64.42 + private static Class<?> browserClass;
64.43 +
64.44 public KnockoutFXTest() {
64.45 }
64.46 -
64.47 - @Factory public static Object[] compatibilityTests() {
64.48 - return VMTest.newTests().withClasses(testClasses()).withLaunchers("fxbrwsr").build();
64.49 +
64.50 + @Factory public static Object[] compatibilityTests() throws Exception {
64.51 + Class[] arr = testClasses();
64.52 + for (int i = 0; i < arr.length; i++) {
64.53 + assertEquals(
64.54 + arr[i].getClassLoader(),
64.55 + KnockoutFXTest.class.getClassLoader(),
64.56 + "All classes loaded by the same classloader"
64.57 + );
64.58 + }
64.59 +
64.60 + URI uri = DynamicHTTP.initServer();
64.61 +
64.62 + final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(KnockoutFXTest.class).
64.63 + loadPage(uri.toString()).
64.64 + invoke("initialized");
64.65 +
64.66 + Executors.newSingleThreadExecutor().submit(new Runnable() {
64.67 + @Override
64.68 + public void run() {
64.69 + bb.showAndWait();
64.70 + }
64.71 + });
64.72 +
64.73 + ClassLoader l = getClassLoader();
64.74 + List<Object> res = new ArrayList<Object>();
64.75 + for (int i = 0; i < arr.length; i++) {
64.76 + Class<?> c = Class.forName(arr[i].getName(), true, l);
64.77 + Class<? extends Annotation> koTest =
64.78 + c.getClassLoader().loadClass(KOTest.class.getName()).
64.79 + asSubclass(Annotation.class);
64.80 + for (Method m : c.getMethods()) {
64.81 + if (m.getAnnotation(koTest) != null) {
64.82 + res.add(new KOFx(m));
64.83 + }
64.84 + }
64.85 + }
64.86 + return res.toArray();
64.87 }
64.88
64.89 + static synchronized ClassLoader getClassLoader() throws InterruptedException {
64.90 + while (browserClass == null) {
64.91 + KnockoutFXTest.class.wait();
64.92 + }
64.93 + return browserClass.getClassLoader();
64.94 + }
64.95 +
64.96 + public static synchronized void initialized(Class<?> browserCls) throws Exception {
64.97 + browserClass = browserCls;
64.98 + KnockoutFXTest.class.notifyAll();
64.99 + }
64.100 +
64.101 + public static void initialized() throws Exception {
64.102 + Class<?> classpathClass = ClassLoader.getSystemClassLoader().loadClass(KnockoutFXTest.class.getName());
64.103 + Method m = classpathClass.getMethod("initialized", Class.class);
64.104 + m.invoke(null, KnockoutFXTest.class);
64.105 + }
64.106 +
64.107 @Override
64.108 public BrwsrCtx createContext() {
64.109 FXContext fx = new FXContext();
64.110 @@ -68,16 +137,45 @@
64.111 return json;
64.112 }
64.113
64.114 - private static JSObject eval;
64.115 @Override
64.116 - public Object executeScript(String script, Object[] arguments) {
64.117 - if (eval == null) {
64.118 - eval = (JSObject) Knockout.web().executeScript("(function(scope) {"
64.119 - + " scope.jko = {};"
64.120 - + " scope.jko.compute = function(s, args) { var f = new Function(s); return f.apply(null, args); }"
64.121 - + "})(window); window.jko;");
64.122 + @JavaScriptBody(args = { "s", "args" }, body = ""
64.123 + + "var f = new Function(s); "
64.124 + + "return f.apply(null, args);"
64.125 + )
64.126 + public native Object executeScript(String script, Object[] arguments);
64.127 +
64.128 + @JavaScriptBody(args = { }, body =
64.129 + "var h;"
64.130 + + "if (!!window && !!window.location && !!window.location.href)\n"
64.131 + + " h = window.location.href;\n"
64.132 + + "else "
64.133 + + " h = null;"
64.134 + + "return h;\n"
64.135 + )
64.136 + private static native String findBaseURL();
64.137 +
64.138 + @Override
64.139 + public URI prepareURL(String content, String mimeType, String[] parameters) {
64.140 + try {
64.141 + final URL baseURL = new URL(findBaseURL());
64.142 + StringBuilder sb = new StringBuilder();
64.143 + sb.append("/dynamic?mimeType=").append(mimeType);
64.144 + for (int i = 0; i < parameters.length; i++) {
64.145 + sb.append("¶m" + i).append("=").append(parameters[i]);
64.146 + }
64.147 + String mangle = content.replace("\n", "%0a")
64.148 + .replace("\"", "\\\"").replace(" ", "%20");
64.149 + sb.append("&content=").append(mangle);
64.150 +
64.151 + URL query = new URL(baseURL, sb.toString());
64.152 + URLConnection c = query.openConnection();
64.153 + BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
64.154 + URI connectTo = new URI(br.readLine());
64.155 + return connectTo;
64.156 + } catch (IOException ex) {
64.157 + throw new IllegalStateException(ex);
64.158 + } catch (URISyntaxException ex) {
64.159 + throw new IllegalStateException(ex);
64.160 }
64.161 - return eval.call("compute", script, arguments);
64.162 }
64.163 -
64.164 }
65.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
65.2 +++ b/ko-fx/src/test/resources/org/apidesign/html/kofx/test.html Wed Jun 26 18:09:25 2013 +0200
65.3 @@ -0,0 +1,34 @@
65.4 +<!--
65.5 +
65.6 + HTML via Java(tm) Language Bindings
65.7 + Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
65.8 +
65.9 + This program is free software: you can redistribute it and/or modify
65.10 + it under the terms of the GNU General Public License as published by
65.11 + the Free Software Foundation, version 2 of the License.
65.12 +
65.13 + This program is distributed in the hope that it will be useful,
65.14 + but WITHOUT ANY WARRANTY; without even the implied warranty of
65.15 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
65.16 + GNU General Public License for more details. apidesign.org
65.17 + designates this particular file as subject to the
65.18 + "Classpath" exception as provided by apidesign.org
65.19 + in the License file that accompanied this code.
65.20 +
65.21 + You should have received a copy of the GNU General Public License
65.22 + along with this program. Look for COPYING file in the top folder.
65.23 + If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
65.24 +
65.25 +-->
65.26 +<!DOCTYPE html>
65.27 +<html>
65.28 + <head>
65.29 + <title>Knockout.fx Execution Harness</title>
65.30 + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
65.31 + <meta name="viewport" content="width=device-width">
65.32 + </head>
65.33 + <body>
65.34 + <h1>Knockout.fx Execution Harness</h1>
65.35 + </body>
65.36 + <script></script>
65.37 +</html>
66.1 --- a/pom.xml Wed May 29 19:36:31 2013 +0200
66.2 +++ b/pom.xml Wed Jun 26 18:09:25 2013 +0200
66.3 @@ -13,8 +13,6 @@
66.4 </parent>
66.5 <properties>
66.6 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
66.7 - <bck2brwsr.version>0.7.2</bck2brwsr.version>
66.8 - <bck2brwsr.launcher.version>0.7.2</bck2brwsr.launcher.version>
66.9 <netbeans.version>RELEASE73</netbeans.version>
66.10 <license>COPYING</license>
66.11 </properties>
66.12 @@ -23,9 +21,10 @@
66.13 <module>json-tck</module>
66.14 <module>ko-archetype</module>
66.15 <module>ko-archetype-test</module>
66.16 - <module>ko-bck2brwsr</module>
66.17 <module>ko-fx</module>
66.18 <module>context</module>
66.19 + <module>boot</module>
66.20 + <module>boot-fx</module>
66.21 </modules>
66.22 <licenses>
66.23 <license>