Support and Documentation

Creating mock JSON data

Styleguide uses JSON as the format for data files. This section describes the components of the JSON data files as well as their locations inside a Brightspot project.

Keys

Styleguide data files must have a _template key that points to the template file. The remaining keys provide mock data or processing instructions to generate a view's interface methods.

 {
   "_template": "path/to/Article.hbs",
   "headline": "Deadly Gamma Ray Burst Headed for Manny's Pizzeria",
   "reporter": "Alfalfa Mail",
   "body": "Sensitive radio telescopes in the isolated Canary Islands have detected a deadly gamma ray burst originating in an outer spiral of the Milky Way Galaxy. Instrumentation aboard European satellites confirm that the burst is headed for Manny's Pizzeria in mid-town Manhattan, home to the city's most cherished tomato sauce recipe.",
   "bodyImage": "https://svs.gsfc.nasa.gov/vis/a010000/a010300/a010369/twoComponentJetStream_1280x720.00577_print.jpg"
}

In the previous snippet, all of the values are static. Styleguide has value helper functions that generate random names, dates, text strings, and images. For details, see Value helpers. In addition, special keys are available for including other data files, selecting image sizes, and other technical functions. For details, see Special keys.

File paths

Styleguide supports both absolute and relative paths in data files. An absolute path is indicated by /, starting from the styleguide directory. A relative path is indicated by ./ or ../, starting from the directory in which the data file resides.

Note

Do not include the styleguide/ directory in an absolute path.

In the following illustration, the data files reference other data files.

styleguide-paths.svg

The table below shows how absolute and relative paths can be specified. In the data files in the previous illustration, paths are set on the _include key to reference other data files.

File

Includes

Location of Referenced File

ArticleBreakingNews.json

"_include":"ArticlePage.json"

/styleguide/article/ArticlePage.json

ArticlePage.json

"_include":"/page/CreativeWorkPage.json" OR "_include":"../page/CreativeWorkPage.json"

/styleguide/page/CreativeWorkPage.json

Styleguide pathing behavior applies to both the root styleguide directory that contains the default theme (brightspot/express/styleguide), as well as the child styleguide directories nested within the various themes' directories, such as brightspot/express/themes/brightspot-theme-falcon. For more information, see Overview of Brightspot's themes.

Simulating AJAX calls

In Styleguide you can simulate AJAX calls so that you can test your client-side JavaScript that processes the server's responses. The underlying concept in Styleguide's implementation of AJAX is that you use a template to submit data in an AJAX session, and you populate another template with the server's response.

The following example shows how to create a form for visitor comments, send the comment to the server, and then display the comment in the original web page.

Step 1: Create directory structure

All the files for your AJAX simulation are under the directory styleguide/, preferably in their own subdirectory. Create the subdirectory in which you'll create the Styleguide files, such as reader-comments/.

AJAX directory structure
Figure 135. AJAX directory structure


Referring to the previous illustration, the five files in the directory reader-comments/ are the minimum you need to simulate an AJAX session in Styleguide. You'll create those files in the following steps.

Step 2: Create a template with a form

Simple AJAX deployments start with an HTML form. In the subdirectory you created for AJAX files (see illustration AJAX directory structure), create the template for the form used to submit a reader comment and display the AJAX response.

{{!-- Filename: ReaderSubmit.hbs --}}
<div class="ReaderSubmit">
    <div class="CommentForm">
        <form action="{{formActionUrl}}" method="{{method}}">
            {{#element "body"}}
                <div class="{{elementName}}">
                    <textarea name="{{this}}"></textarea>
                </div>
            {{/element}}
            {{#element "submit"}}
                <button class="{{elementName}}" type="submit">{{this}}</button>
            {{/element}}
        </form>
    </div>
    {{#with "comments"}}
         <div class="CommentForm-comments">
             {{~this~}}
         </div>
    {{/element}}
</div>

In the previous snippet—

  • Line 1 declares the template name; this name appears in the corresponding data file.

  • Lines 4–13 evaluate to a traditional HTML form with a textarea and a submit button.

  • Lines 16–18 evaluate to <div class="ReaderSubmit-comments"> in which the AJAX response appears. The JavaScript function to display the response will query on the class name.

At run time, the reader submission form looks as follows.

Template at load time
Figure 136. Template at load time


Step 3: Create a data file for the form template

{
  "_template": "ReaderSubmit.hbs",
  "method": "post",
  "formActionUrl": "ReaderResponse.html",
  "body": "body",
  "submit": "Submit",
  "comments": "Comment appears here."
}

In the previous snippet—

  • Line 2 associates this data file with the template you created in Step 1.

  • Line 4 specifies the template Styleguide populates with the server's response. You'll create this template in Step 4.

  • The remaining lines populate various placeholders in the template.

Step 4: Create template for response

You need to create a template that contains the server's response to the AJAX input.

<div class="ReaderResponse">
    {{#with "body"}}
        <div class="ReaderResponse-body">
            {{this}}
        </div>
    {{/with}} 
</div> 

In the previous snippet—

  • Line 1 declares the template name; this name appears in the corresponding data file.

  • Lines 3–5 evaluate to <div class="ReaderResponse-body">. The JavaScript function places the AJAX response inside this div.

Step 5: Create data file for response template

Create a data file for the template you created in Step 4.

{
  "_template": "ReaderResponse.hbs",
  "_hidden": true,
  "_wrapper": false,
  "body": "Roses are read, violets are blue, most poems rhyme, but this one doesn't."
}

In the previous snippet—

  • Line 2 associates this data file with the template you created in Step 4.

  • Line 3 prevents the response template from appearing in the Styleguide UI—a typical practice for nested templates.

  • Line 4 indicates the returned template is not wrapped in any higher level templates—a typical practice for nested templates. For details about this key, see _wrapper.

  • Line 5 populates the response with static text.

Step 6: Create a JavaScript plugin file

Create a JavaScript file as a class that processes the event callbacks you want to capture as well as the response received from the server.

Example 59. JavaScript plugin file
const COMMENTING_SELECTOR = '.ReaderSubmit'
const COMMENTING_COMMENTS_SELECTOR = COMMENTING_SELECTOR + '-comments'
const FormData = window.FormData

export default class ReaderSubmit {

  constructor (element) {
    this.element = element
    this.bindEvents()
  }

  bindEvents () {
    this.element.addEventListener('submit', (event) => this.onFormSubmit(event))
  }

  onFormSubmit (event) {
    event.preventDefault()
    const form = event.target
    const formData = new FormData(form)

    window.fetch(form.getAttribute('action'), {
      method: 'POST',
      body: formData
    }).then((response) => {
      if (response.status !== 200) {
        throw new Error(response.statusText)
      }
      return response.text()
    }).then((returnedComment) => {
      document.querySelector(COMMENTING_COMMENTS_SELECTOR).innerHTML = returnedComment
    }
    ).catch((error) => {
      console.log(error)
    })
  }
}


In the previous snippet—

  • Lines 1–2 declare constant strings used in functions that access the DOM through class names, such as document.querySelector. Using constants in this manner is a best practice, as their values tie directly to the block names and element names in templates, and production-grade JavaScript files often reuse these names individually or in concatenation.

  • Line 5 declares a class using the statement export. This statement is mandatory as it allows you to register the class as a plugin in Step 7.

  • Lines 7–10 form the class's constructor. The constructor calls the function to bind events to the template's controls.

  • Lines 12–14 bind the event submit to the callback onFormSubmit().

  • Lines 16–35 describe the callback onFormSubmit() using the standard AJAX construct window.fetch:

    • Lines 21–28 send the form data to the server and receive the subsequent response. In this example, the response is a static text "Roses are read, violets are blue, most poems rhyme, but this one doesn't."

    • Lines 29–31 take the received response (which is a string) and assign it to the div whose class name is .ReaderSubmit-comments. See the illustration Result of AJAX session for an example of the response's appearance inside the originating web page.

Step 7: Register plugin

  1. In the theme's styleguide/ directory, create or open a file All.js. (See the illustration AJAX directory structure for the location of this file.)

  2. Add the following lines:

import plugins from '<path>/core/PluginRegistry.js'
import ReaderSubmit from './reader-comments/ReaderSubmit.js'
plugins.register(ReaderSubmit, '.ReaderSubmit')

In the previous snippet—

  • Line 1 imports the Node.js plugin-registry package. This package comes with Styleguide, so you do not need to install it yourself.

  • Line 3 associates the class ReaderSubmit with the CSS class .ReaderSubmit. Any time the browser adds to the DOM an HTML element with the class .ReaderSubmit, it instantiates an object of class ReaderSubmit—the same class you created in the listing JavaScript plugin file. For an illustration of the web page's state after running the constructor, see Template at load time.

Step 8: Run Styleguide

  1. Build and run your Styleguide project. From the express/ or theme directory, gulp styleguide.

  2. In the browser, click Submit to observe the AJAX interaction.

Result of AJAX session
Figure 137. Result of AJAX session


Referring to the previous illustration, clicking Submit retrieves the text in the data file ReaderResponse.json that you created in Step 5, and displays it in the div <div class="ReaderSubmit-comments">.

. See also:
Static images

You can use URLs to display static images in the Styleguide UI.

{
  "_template": "ImageReal.hbs",
  "src": "https://images.unsplash.com/photo-1517509160146-84ffefa28364",
  "caption": "Red fire extinguisher near red wall",
  "credit": "John Tyson"
}

In the previous snippet, line 3 points to a static image on the public Internet.

static-image-url.png
. See also: