Code Monkey home page Code Monkey logo

adlib's Introduction

adlib

npm version build status apache licensed

A JavaScript library for interpolating property values in JSON Objects.

The ArcGIS Hub team uses adlib to build Web Maps, Hub Sites, Hub Pages and other newly created ArcGIS Online content using customer Open Data on the fly.

To get a feel for how adlib works, check out this Live Demo!

Usage

ES Module

import { adlib, listDependencies }  from 'adlib'

adlib(template, settings) // renders an adlib template
listDependencies(template) // list all dependecies of an adlib template

Browser (from CDN)

This package is distributed as a UMD module and can also be used in AMD based systems or as a global under the adlib namespace.

<script src="https://unpkg.com/adlib"></script>
adlib.adlib(template, settings)
adlib.listDependencies(template)

TypeScript

TypeScript definitions are available from DefinitelyTyped: npm install --save-dev @types/adlib

General Pattern

const template: {
  value: '{{ instance.color }}'
};

const settings: {
  instance: {
    color: 'red'
  }
};

const result = adlib(template, settings);
// > { value: 'red' }

Note Adlib does not mutate the template, it returns a new object that contains copies of the template properties with interpolations applied. This allows the template to be used multiple times in succession with different settings hashes.

List dependencies

Gets a list of all variables your template depends upon

const template = 'Injuries: {{CRASHID}}<br />On Scene: {{ISREPORTONSCENE}}'
const deps = adlib.listDependencies(template); // CRASHID, ISREPORTONSCENE

Supported Interpolations

Strings

Within the template, the value of any property can be described using {{obj.prop}}.

If the obj.prop "path" in the settings object is a string, that string value is assigned to the value.

Multiple Strings

A property of a template can have a value like 'The {{thing.animal}} was {{thing.color}}'. When combined with a settings object that has the appropriate values, this will result in The fox was brown.

let template = {
  value: 'The {{thing.animal}} was {{thing.color}}'
};
let settings = {
  thing: {
    color: 'red',
    animal: 'fox'
  }
};
let result = adlib(template, settings);
//> {value: 'The fox was red'}

Objects

If the interpolated value is an object, it is returned. This allow us to graft trees of json together.

let template = {
  value: '{{s.obj}}'
};
let settings = {
  s: {
    obj: {
      val: 'red'
    }
  }
};
let result = adlib(template, settings);
//> { value: {val: 'red'}}

Arrays

If the interpolated value is an array, it is returned. Interpolation is also done within arrays.

let template = {
  values: ['{{s.animal}}', 'fuzzy', '{{s.color}}'],
  names: '{{s.names}}'
};
let settings = {
  s: {
    animal: 'bear',
    color: 'brown',
    names: ['larry', 'sergey']
  }
};
let result = adlib(template, settings);
//> result.values === ['bear', 'fuzzy', 'brown']
//> result.names === ['larry', 'sergey']

Transforms

Adlib can apply transforms during the interpolation. The transform fn should have the following signature: fn(key, value, settings).

// Pattern
// {{key:transformFnName}}

let  tmpl = `{{s.animal.type:upcase}}`;
let settings = {
  s: {
    animal: {
      type: 'bear'
    }
  }
}
// will parse into
// key: s.animal.type
// value: 'bear'
// transformFnName: 'upcase'

Notes About Transforms

  • Transforms are ideally pure functions, and they must be sync functions! Promises are not supported.
  • Transform functions should be VERY resilient - we recommend unit testing them extensively
  • If your settings hash does not have an entry for the key, the value will be null.

Transforms

let template = {
  value:'{{s.animal.type:upcase}}'
};
let settings = {
  s: {
    animal: {
      type: 'bear'
    },
    color: 'brown'
  }
};
let transforms = {
  upcase (key, val, settings) {
    return val.toUpperCase();
  }
};
let result = adlib(template, settings, transforms);
//> result.value = 'BEAR'

Transforms using the Key

A typical use-case for this is for translation.

let template = {
  value:'{{s.animal.type:translate}}'
};
let settings = {};
let transforms = {
  translate (key, val, settings) {
    // the translator is passed in from the consuming application
    // note that the settings hash is empty
    return translator.translate(key);
  }
};
let result = adlib(template, settings, transforms);
//> result.value = 'string returned from translation system'

Built-in Transforms

adlib comes with some built-in transforms:

  • optional - declare a value to be optional

Optional Transform

{{key.path:optional:<levelToRemove>}}

By default, if the key is not found, adlib simply leaves the {{key.path}} in the output json. However, that can/will lead to problems when the json is consumed.

The optional transform helps out in these scenarios. By default when adlib encounters something like:

{
  someProp: 'red'
  val: '{{key.path:optional}}'
}

and key.path is null or undefined, the val property will simply be removed.

{
  someProp: 'red'
}

The same thing works in arrays

{
  someProp: 'red'
  vals: [
    'red',
    '{{key.path:optional}}'
  ]
}

// returns
{
  someProp: 'red'
  vals: [
    'red',
  ]
}

However, there are times when simply removing the property/entry is not enough. Sometimes you need to "reach up" the object graph and remove a parent. This is where the levelToRemove comes in...

let template = {
  someProp: 'red',
  operationalLayers: [
    {
      url: `{{layers.pipes.url}}`,
      fields: [
        {
          key: 'direction',
          fieldName: `{{layers.pipes.directionField:optional:3}}`
        }
      ]
    }
  ]
};
let settings = {
  layers: {
    pipes: {
      url: 'http://someserver.com/23'
    }
  }
};
// will returns
{
  someProp: 'red'
  operationalLayers: []
}

levelToRemove

value removes what
0 (default) the property or array entry
1 the parent object/array
2 the grand-parent object/array
... ... up the hierarchy

Path Hierarchies

Sometimes you may want to adlib a value using one of several possible data sources. You can specify each data source in a hierarchy of preference in the template

let template = {
  dataset: {
    title: {{layer.name||item.title}},
    modified: {{metadata.some.super.nested.value.bc.im.a.weird.xml.doc:toISO||item.modified:toISO}},
    tags: {{metadata.categories||item.tags}}
  }
}

let settings = {
  metadata: {
    categories: [
      'citations',
      'civil offense',
      'misdemeanor'
    ],
    some: {
      super: {
        nested: {
          value: {
            bc: {
              im: {
                a: {
                  weird: {
                    xml: {
                      doc: '1505836376836'
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  item: {
    title: '2014 Parking Violations',
    tags: [
      'Parking',
      'Washington',
      'Citations',
      'Crimes',
      'Law Enforcement',
      'Nuisance',
      'Cars'
    ]
  },
  layer: {}
}

let transforms = {
  toISO: function (key, val, settings) {
    if (isStringAndNotADateValue(val)) {
      return new Date(val).toISOString()
    }
  }
}

adlib(template, settings, transforms)
// => returns
{
  dataset: {
    title: '2014 Parking Violations',
    modified: '2017-09-19T15:52:56.836Z',
    tags: [
      'citations',
      'civil offense',
      'misdemeanor'
    ]
  }
}

Path Hierarchies with Defaults

If none of the paths are available, the last entry can be a static value and that will be returned. We support returning strings ('RED', 'the red fox'), ints (23, 15), and floats (12.3, 0.234)

Note Transforms can not be applied to the default value! Please see TODO.md for notes about changes required for this.

let template = {
  msg: 'Site is at {{obj.mainUrl||obj.otherUrl||https://foo.bar?o=p&e=n}}'
}

var settings = {}

let result = adlib(template, settings);
// => returns
// 'Site is at https://foo.bar?o=p&e=n'

Local Development

npm install && npm test

Contributing

Esri welcomes contributions from anyone and everyone. Please see our guidelines for contributing.

Release

First, get the latest code and update dependencies.

git pull master --tags
yarn

Then, make sure the version in package.json is the same as what's released (you can check against npm view if unsure).

Next, update the CHANGELOG w/ release content and then run these commands:

git add .
yarn test && yarn run build:release
npm version -f [ major | minor | patch ]
git push origin master --tags
npm publish

License

Copyright © 2017-2019 Esri

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

A copy of the license is available in the repository's LICENSE file.

adlib's People

Contributors

ajturner avatar akharris avatar benstoltz avatar dbouwman avatar dependabot[bot] avatar jgravois avatar jmhauck avatar jordantsanz avatar miketschudi avatar r00b avatar rgwozdz avatar tomwayson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adlib's Issues

generated a ES5 ESM build

currently module points to the source code, which is not ES5. Convention has been to publish an ESM build that is compiled down to ES5 (other than the imports).

The quickest way to do this would be to add a format: 'es' rollup profile like

// profiles/esm.js
import config from './base';

config.output.file = 'dist/adlib.esm.js';
config.output.format = 'es';
config.output.sourceMap = 'dist/adlib.esm.js.map';

export default config;

I've tested that. It works, but it's not ideal b/c the output is a bundle (single file), meaning consumers can't tree-shake.

Hierarchies with unmatched settings terminate early

When hierarchies are present and a match fails, processing terminates. E.g., in

  let template = {
    msg: '{{organization.name||My Community}}<br />{{organization.nonexistantproperty.sharedTheme.logo.small||https://www.arcgis.com/sharing/rest/content/items/28989a5ecc2d4b2fbf62ac0f5075b7ff/data}}<br />{{organization.name||My Community}}',
  }

  var settings = {
    organization: {
      name: "myOrg"
    }
  };

  let result = adlib(template, settings)

  t.plan(1);
  t.equal(result.msg, 'myOrg<br />https://www.arcgis.com/sharing/rest/content/items/28989a5ecc2d4b2fbf62ac0f5075b7ff/data<br />myOrg');
  t.end();

adlib produces

myOrg<br />https://www.arcgis.com/sharing/rest/content/items/28989a5ecc2d4b2fbf62ac0f5075b7ff/data<br />organization.name

--only the first organization.name is replaced.

If the defaults are removed,

myOrg<br />{{organization.nonexistantproperty.sharedTheme.logo.small}}<br />myOrg

is produced as expected.

continuous testing

the current tests:

  • execute in node on the bundled output
  • have to be manually re-run after changes to the code

I'd like to set up the tests to run whenever the code changes and to run on non-bundled output (i.e. something that would actually be used in a node app). I'm thinking something along the lines of what is discussed here: rollup/rollup#657 (comment)

Doesn't handle empty strings

If I try to adlib a variable equal to an empty string '', the entire node will be left untouched, and not adlibbed with an empty string:

for a='', "{{a}}" will yield "{{a}}" and not "".

Adlib truth table for defaults

Template syntax Template data requires Indicator exists Output
"field": "{{indicator.name||A_STRING}}" String no "A_STRING"
"field": "{{indicator.name||A_STRING}}" String yes indicator.name.value
"field": "{{indicator.name||5}}" Number no 5
"field": "{{indicator.name||5}}" Number yes indicator.name.value
"field": "{{indicator.name||1469803210000}}" Date no 1469803210000
"field": "{{indicator.name||1469803210000}}" Date yes indicator.name.value
"field": "{{indicator.name||some.other.object}}" Object (extent) no some.other.object.value
"field": "{{indicator.name||some.other.object}}" Object (extent) yes indicator.name.value

Get rid of babel deps

Unless we plan to use 'em. Currently transpilation is being taken care of by buble.

`:optional` kills the entire node

If I am trying to adlib something like this:

"url": "{{foo:optional}}/more/stuff/here"

and foo is falsey, then the resulting adlibbed variable url will be undefined, whereas I'd expect it to be "/more/stuff/here".

whitespace inside templates causes logical failure

Consider a template like:

{
  "title": "{{crashLayer.title || test}}"
}

And settings like:

{
  "crashLayer": {
    "title": "2008 Collisions"
  }
}

We get the result from adlib:

{
  "title": " test"
}

when what we really want is "title": "2008 Collisions". This occurs because leading/trailing whitespace in handlebars content is not being fully handled/trimmed during parsing.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.