npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

json-pollock

v1.7.7

Published

Renders live DOM elements out of JSON according to the Structured Messaging Templates spec

Downloads

1,216

Readme

Json-Pollock

Build Status GitHub license Downloads Version

The Json-Pollock package renders live DOM elements out of JSON according to the Structured Messaging Templates specification

Installation

npm i json-pollock --save

In the dist folder you'll find a list of file that allows you to consume json-pollock in a different ways:

As a Bundle

json-pollock.bundle.min.js - this script bundle both package and styles, once you import it into your code it will inject the needed styles into your page header - no additional actions are needed from your side. it is also supports umd - meaning you can consume it using AMD, CommonJS and as simple script (see examples)

Separate files for code and style

json-pollock.min.js - use this script if you want to handle the import of the styles by youself, if you use it you should also take care to link json-pollock.min.css to your web page. also supports umd.

No UMD

json-pollock.global.min.js - this script is the same as json-pollock.min.js, however is does not support umd - it only puts JsonPollock on the current this (usually the window object). use this in case you inject the package into sites that are not managed by you and you dont know if it uses AMD or not.

No validation

json-pollock.global.no_validation.min.js - a version of json-pollock.global.min.js which the validation phase is excluded. this bundle is lighter as it does not bundles the validation package (Ajv), however it should be used with more care in regard to the json input.

examples

A script tag:

<!-- for bundle this import if enough -->
<script src="path-to-node-modules/dist/json-pollock.bundle.min.js"></script>

<!-- for others you should also link the styles -->
<script src="path-to-node-modules/dist/json-pollock.[global.]min.js"></script>
<link rel="stylesheet" href="path-to-node-modules/dist/json-pollock.min.css">

Following examples are relevant only for json-pollock.bundle.min.js and json-pollock.min.js:

Using RequireJS:

Map the JsonPollock path in the RequireJs config, and then:

require(["JsonPollock"],(jsonPollock) => {
    ...
})

Using CommonJS:

const JsonPollock = require("JsonPollock");

Usage

init

You can call the init function if you want to configure JsonPollock - it is not mandatory, if you won't call it JsonPollock will be initialized with defaults.

JsonPollock.init({
	maxAllowedElements: 100,
	onAfterElementRendered: onAfterElementRenderedHandler
});

Supported options:

|name | type | description | default | |---|---|---|---| | maxAllowedElements | Number | max DOM elements that will be renderes, other elements will be ignored. | 50 | | onAfterElementRendered | Function | A callback function that will be invoked after each render on an element, it allows to customize the result DOM element. see the following for exact signature and usage example of the callback function. | |

Example callback function for onAfterElementRendered:

/**
* @param {HTMLElement} element html element that was rendered by json-pollock
* @param {Object} template SC template of this element  
* @returns {HTMLElement} manipulated html element
*/
const onAfterElementRendered = (element, template) => {
	// maniplate elements:
	switch (template.type) {
		case JsonPollock.TEMPLATE_TYPES.TEXT:
			// add custom css class
			element.classList.add('my-ns-text');
			break;
		case JsonPollock.TEMPLATE_TYPES.LINK:
			// edit inline style
			element.style.color = 'red';
			break;
		case JsonPollock.TEMPLATE_TYPES.MAP:
			// prevent 'map' element to be rendered
			return null;
      ...
    }
    return element;
}

render

The render function renders json into a DOM element.

const content = {
	"type": "vertical",
	"elements": [{
		"type": "image",
		"url": "http://assets/phone.jpg",
		"tooltip": "Great Phone!",
		"click": {
			"actions": [{
				"type": "navigate",
				"name": "Navigate to store via image",
				"lo": 23423423,
				"la": 2423423423
			}]
		}
	}]
}
const rooEl = JsonPollock.render(content);
document.getElementById('container').appendChild(rooEl);

registerAction

The registerAction function allow to register a callback to a certain action type, as defined in the spec.

/**
 * @param {Object} data	callback payload
 * @param {Object} data.actionData action configuration as defined in the json
 * @param {Object=} data.metadata metadata configuration as defined in the json, optional
 * @param {Event=} data.uiEvent UI DOM Event object of the clicked element, optional
 * @param {String=} data.groupID reference to section id - curently relevant to checkbox element, optional. 
 * @param {DOMElement=} data.formEl reference to the associated form element, optional
 **/
const linkCallback = (data) => {	
  window.open(data.actionData.uri,"_blank");
};
JsonPollock.registerAction('link', linkCallback);

unregisterAction

The unregisterAction function allow to unregister a callback to a certain action type, as defined in the spec.

JsonPollock.unregisterAction('link');

unregisterAllActions

The unregisterAllActions function allow to unregister all callbacks to all action types.

JsonPollock.unregisterAllActions();

validate

The validate function allow check if a given JSON is a valid for rendering, if validation fails it will thorw an Error (see Error Handling)

Note that this function is not availble on the No validation build

/**
 * @parame {Object} json JSON object
 * */
JsonPollock.validate(json);

Error Handling

JsonPollock.render() will throw an Error if it fails from any reason, the error object will have a message property that will give the error description.

Perior to the rendering the JSON object is validated against the JSON schema, if it fails to validate the error object will also include an errors property that will hold the validation errors.

...
try {
  const rooEl = JsonPollock.render(json);
  ...
} catch(e) {
	console.log(e.message);    // error message
	console.log(e.errors);     // validation errors
}

Playground

Here