Skip to content
Brenton Ashworth edited this page Jun 18, 2013 · 19 revisions

Rendering

In this section we work on rendering our application. Rendering is the process of drawing something on the screen which represents our application and with which users can interact. In the previous section we created two HTML templates which we will make use of below.

It is important to note that rendering is more general that binding data to HTML. As we will see in a later section, we sometimes want to render with something other than HTML.

As we work through this section, the following concepts will be introduced.

  • Recording interactions
  • Playing recordings
  • Writing rendering code

Recording user interactions

Pedestal provides a way to record a sequence of deltas for later playback. We can use this feature to generate deltas which represent a typical use of our application.

Currently, the only way we have to interact with our application is the Data UI. Fortunately this is all we need to make a first recording. To make a recording, go to the DataUI

http://localhost:3000/tutorial-client-data-ui.html

and then type the key combination

Alt-Shift-R

You will see an indicator that you are currently recording in the lower right-hand corner of the screen.

As you interact with the application, each rendering delta is being recorded. Press the :inc button a few times. After you have recorded a sufficient amount of activity, type the key combination

Alt-Shift-R

to stop recording.

This will open a dialog which will ask you to name the recording. The dialog asks for both a keyword and a text description. For the keyword enter :tutorial and for the description enter Tutorial Recording.

Clicking Continue will save the recording while clicking Cancel will delete it.

The recording is saved in a Clojure file as Clojure data. This recording can be found in the file

tools/recording/tutorial-client/tutorial.clj

You could write a file like this from scratch or edit this file to create alternate interactions. Being able to generate and work with this kind of data allows us to capture hard-to-simulate interactions and work on rendering them without having to drive the application. We could even create an interaction that the application cannot yet produce. This would allow us to work on rendering and the application logic simultaneously.

Playing recordings

To see a list of recordings, click on the Render link in the Tools menu or open the page below.

http://localhost:3000/_tools/render

This page contains a list of each recording that you have created. Each recording will have three links. The link that is the recording's name will play through all the deltas at once. This is useful when you want to see how a specific point in time will be rendered.

The second link is named Break it will play through the deltas in chunks. For recorded data, each chunk is the output of a single transaction. This allows for the deltas to be played in the same way that the browser would receive them. A sequence of recorded deltas will contain the :break keyword to divide blocks of deltas by transaction. Breaks may be added by hand to control how this method of playback behaves.

The last link is named Step. It allows playback to proceed one delta at a time. This is the most helpful mode when working on a new renderer.

Click on the Step link and then open the JavaScript console in order to see the log messages which will be printed.

With focus on the main window, use the right and left arrow keys to navigate forward and backward through the deltas. As each delta is rendered it will be printed to the console. These deltas are also being fed through the application's renderer. Nothing is being displayed in the browser because this renderer does not understand these deltas.

Resolving this problem is our next task.

Rendering

Basic rendering is very simple. A rendering function can be provided to the application which will be called after every transaction and passed the sequence of deltas produced and the input queue. This function will have some side-effect which draws something on the screen or creates an event listener.

Pedestal provides a function in the io.pedestal.app.render.push namespace named renderer which will create a rendering function for us. This renderer is helpful to use when working with the DOM and is called the "push renderer" because it responds to data being pushed to it from the application.

The renderer to use is set up in the tutorial-client.start namespace. In the create-app function the renderer is created passing a render-config. That renderer configuration is implemented in the namespace tutorial-client.rendering which is where we will do all of our work.

Rendering in the DOM

Before we start, add one additional required namespace

[io.pedestal.app.render.push.handlers :as h]

At the beginning of the recording, the first deltas to be encountered are

[:node-create [] :map]
[:node-create [:tutorial] :map]

The first delta will only be seen once. It represents the creation of the root node of the application model tree.

The second delta represents the creation of the root node of this tutorial application. This delta will be rendered by adding the main template to the DOM, all subsequent rendering will fill in the values of this template. Unfortunately this means that the first the rendering function to write will also be the most complex.

A render configuration is a vector of tuples which map rendering deltas to functions. Each vector has the op then the path and then the function to call. In the example below, the render-template function will be called when the :tutorial node is created and the library function h/default-destroy will be called to remove the template when the :tutorial node is removed.

(defn render-config []
  [[:node-create [:tutorial] render-template]
   [:node-destroy [:tutorial] h/default-destroy]])

When using the push renderer, every rendering function receives three arguments: the renderer, the delta and the input queue. The renderer helps to map paths to the DOM. The delta contains all of the information which is required to make the change and the input queue is used to send messages back to the application.

(defn render-template [renderer [_ path] _]
  (let [parent (render/get-parent-id renderer path)
        id (render/new-id! renderer path)
        html (templates/add-template renderer path (:tutorial-client-page templates))]
    (dom/append! (dom/by-id parent) (html {:id id}))))

In the example above, the delta is destructured to get required information. This is a common pattern. The most common part of the delta to grab is the path.

The body of this function is as complicated as a rendering function can get. Here is what this function does:

  1. get the parent id for the current path from the renderer
  2. generate a new id for this path
  3. add the dynamic template to the renderer at this path
  4. add the template to the DOM under the parent id, providing the default values

For complex render functions, this is also a common pattern: get the parent id, create a new id, add some child content under the parent.

The functions render/get-parent-id and render/new-id! are simple to understand. See io.pedestal.app.render.push for more information.

The function templates/add-template takes all the hard work out of dealing with dynamic templates. This function associates the template with the given path and returns a function which generates the initial HTML. Calling the returned function with a map of data will return HTML which can be added to the DOM.

The dynamic template is retrieved from the templates map which is created at the top of this namespace.

(def templates (html-templates/tutorial-client-templates))

After adding this code, refresh the browser and then step through the deltas again to see the template get added to the DOM when the delta below is received.

[:node-create [:tutorial] :map]

Press the left arrow to go backward and see the template be removed from the DOM.

Rendering transforms

A :transform-enable delta provides a sequence of messages to send when some event occurs. We will arrange for these messages to be sent when a button is clicked. Because these messages don't have any parameters, and we are wiring up a simple click event, we can use library functions from the io.pedestal.app.render.push.handlers namespace to wire up these events.

(defn render-config []
  [...

   [:transform-enable [:tutorial :my-counter] (h/add-send-on-click "inc-button")]
   [:transform-disable [:tutorial :my-counter] (h/remove-send-on-click "inc-button")]])

The add-send-on-click handler will arrange for the messages included in this :transform-enable to be sent when the element with id inc-button is clicked. The remove-send-on-click handler will remove this event listener when a :transform-enable is received.

This is one example of how small, focused handlers can lead to reusable code.

Changing value in a template

By design, we have arranged for most of the values that will be plugged into our template to have a path which ends with the template field name. This means that we can write one function to handle all of these cases.

(defn render-value [renderer [_ path _ new-value] input-queue]
  (let [key (last path)]
    (templates/update-t renderer [:tutorial] {key (str new-value)})))

This function uses the templates/update-t function to update a value in a template. update-t has three arguments: the renderer, the path that the template is associated with and the map of value to update in the template. In this case the key is the last part of the path.

All value changes for the paths [:tutorial :*] and [:pedestal :debug :*] are sent to this function to update the values in the template.

(defn render-config []
  [...

   [:value [:tutorial :*] render-value]
   [:value [:pedestal :debug :*] render-value]])

Rendering lists

Remember that we have two templates, one for the whole page and one for element in the list of other counters. If we were to write a function to add the :other-counter template, we would realize that it is almost identical to the render-template function above. Instead of doing this, let's make a more general function which can be used in both cases.

Here is the new version of render-template.

(defn render-template [template-name initial-value-fn]
  (fn [renderer [_ path :as delta] input-queue]
    (let [parent (render/get-parent-id renderer path)
          id (render/new-id! renderer path)
          html (templates/add-template renderer path (template-name templates))]
      (dom/append! (dom/by-id parent) (html (assoc (initial-value-fn delta) :id id))))))

This is a function which returns a function. It takes the template name and a function which, when passed the delta, will return a map of initial values for the template. It returns a rendering function.

When we receive the deltas for the other counters, they will look like this:

[:node-create [:tutorial :other-counters] :map]
[:node-create [:tutorial :other-counters "abc"] :map]
[:value [:tutorial :other-counters "abc"] nil 42]

When we receive the delta

[:node-create [:tutorial :other-counters] :map]

We will want to create the container for the other counters. When we receive the delta

[:node-create [:tutorial :other-counters "abc"] :map]

we will add the template for this counter. When we receive the delta

[:value [:tutorial :other-counters "abc"] nil 42]

We will set the value the template.

Because we have re-written the render-template function, we can handle creating new templates with this configuration:

[:node-create [:tutorial :other-counters :*]
  (render-template :other-counter
                   (fn [[_ path]] {:counter-id (last path)}))]

That function assumes that there is a parent id under which these templates can be added as children. The template that we created has a div with id other-counters where we would like these elements to go.

The changes below will associate this id with the parent path of all counter nodes

(defn render-other-counters-element [renderer [_ path] _]
  (render/new-id! renderer path "other-counters"))

(defn render-config []
  [...

   [:node-create [:tutorial :other-counters] render-other-counters-element]
   ...
   ])

Finally we add the function to update the other counter values.

(defn render-other-counter-value [renderer [_ path _ new-value] input-queue]
  (let [key (last path)]
    (templates/update-t renderer path {:count (str new-value)})))

(defn render-config []
  [...

   [:value [:tutorial :other-counters :*] render-other-counter-value]])

The final version of the render configuration is shown below.

(defn render-config []
  [[:node-create [:tutorial] (render-template :tutorial-client-page
                                              (constantly {:my-counter "0"}))]
   [:node-destroy [:tutorial] h/default-destroy]
   [:transform-enable [:tutorial :my-counter] (h/add-send-on-click "inc-button")]
   [:transform-disable [:tutorial :my-counter] (h/remove-send-on-click "inc-button")]
   [:value [:tutorial :*] render-value]
   [:value [:pedestal :debug :*] render-value]

   [:node-create [:tutorial :other-counters] render-other-counters-element]
   [:node-create [:tutorial :other-counters :*]
    (render-template :other-counter
                     (fn [[_ path]] {:counter-id (last path)}))]
   [:value [:tutorial :other-counters :*] render-other-counter-value]])

With these changes in place, we should now be able to step forward and backward in the rendering aspect and see each of these functions performing its specific task.

Development and production aspects

With a working custom renderer, we can now go click on Development or Production in the tools menu and see a working version of the application.

Clean up

You may notice that the counter starts a 1 before we have clicked the button. This is because early in the process we added some code which sends a messages when the application starts. This is no longer required.

In the namespace tutorial-client.start, remove the following line from the create-app function.

(p/put-message (:input app) {msg/type :inc msg/topic [:my-counter]})

Next steps

In this step we have got the point where we can use the Data UI to see our app work with a simulated back-end and we can run with the real renderer in the Development and Production aspects. It would be nice if we could see our simulated app work with the our custom renderer so that we tell that is was really working without having to fire up and service.

In the next section we will see how we can customize the development tools to create new aspects that allow us to see part of our application in a new and interesting way.

The tag for this step is step7.

Home | Aspects

Clone this wiki locally