Last active
August 29, 2015 14:10
-
-
Save pleasetrythisathome/30c2cec625c9fcd81163 to your computer and use it in GitHub Desktop.
nashorn cljs rendering
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns starlab.services.nashorn | |
(:require [clojure.tools.logging :as log] | |
[clojure.java.io :as io]) | |
(:import [javax.script | |
Invocable | |
ScriptEngineManager]) | |
(:use [plumbing.core :exclude [update]])) | |
(defn nashorn-env [] | |
(doto (.getEngineByName (ScriptEngineManager.) "nashorn") | |
;; React requires either "window" or "global" to be defined. | |
(.eval "var global = this;") | |
;; https://github.com/paulmillr/console-polyfill | |
(.eval (-> "nashorn/polyfills/console.js" | |
io/resource | |
io/reader)))) | |
(defn bootstrap-goog [nashorn-env goog-path] | |
(doto nashorn-env | |
;; parse dependencies | |
(.eval (-> (str goog-path "/base.js") | |
io/resource | |
io/reader)) | |
(.eval (-> (str goog-path "/deps.js") | |
io/resource | |
io/reader)))) | |
(defn bootstrap-build [nashorn-env build] | |
(doto nashorn-env | |
;; parse the compiled js file | |
(.eval (-> build | |
io/resource | |
io/reader)))) | |
(defn bootstrap-dev [nashorn-env goog-path] | |
(doto nashorn-env | |
;; set goog to import javascript using nashorn-env load(path) | |
(.eval (str "goog.global.CLOSURE_IMPORT_SCRIPT = function(path) { | |
load(\"resources/" goog-path "/\" + path); | |
return true; | |
};")) | |
;; loop through dependencies and require to trigger injections | |
(.eval "for(var namespace in goog.dependencies_.nameToPath) | |
goog.require(namespace);"))) | |
(defn nashorn-invokable [nashorn-env namespace method] | |
(fn [edn] | |
(.invokeMethod | |
^Invocable nashorn-env | |
namespace | |
method | |
(-> edn | |
pr-str | |
list | |
object-array)))) | |
(defn nashorn-renderer [environment compile-target render-ns] | |
(let [goog-path (str compile-target "/goog") | |
env (cond-> (nashorn-env) | |
(= environment :development) | |
(= environment :production) ) | |
;; eval the render namespace | |
namespace (.eval env render-ns) | |
;; pull the invocable render-to-string method out of view | |
render-to-string (nashorn-invokable env namespace "render-to-string")] | |
(fn render [state-edn] | |
(render-to-string state-edn)))) | |
;; this assumes a cljs setup with render-ns/render-to-string | |
;; ex. | |
(defn ^:export render-to-string | |
"Takes an app state as EDN and returns the HTML for that state." | |
[state-edn] | |
(->> state-edn | |
edn/read-string | |
(om/build app-view) | |
dom/render-to-str)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment