README.md 58.8 KB
Newer Older
1
# About g1
S Anand's avatar
S Anand committed
2

3
`g1` is library of interaction patterns in [Gramex](https://learn.gramener.com/guide/).
S Anand's avatar
S Anand committed
4

5
Install using:
S Anand's avatar
S Anand committed
6

7
8
9
    yarn install g1
    # ... OR ...
    npm install --save g1
S Anand's avatar
S Anand committed
10

11
To use all features, add this to your HTML:
S Anand's avatar
S Anand committed
12

13
    <script src="node_modules/g1/dist/g1.min.js"></script>
S Anand's avatar
S Anand committed
14

S Anand's avatar
S Anand committed
15
16
Or import one of the individual libraries below. [g1.min.js](dist/g1.min.js) has all of these
functions. [g.js](dist/g.js) is an un-minified version for debugging.
S Anand's avatar
S Anand committed
17

18
19
Interactions:

S Anand's avatar
S Anand committed
20
- [urlfilter.min.js](dist/urlfilter.min.js): URL filtering library
21
22
23
24
    - [$.urlfilter](#urlfilter) changes URL query parameters when clicked. Used to filter data.
    - [g1.url.parse](#urlparse) parses a URL into a structured object
    - [g1.url.join](#urljoin) joins two URLs
    - [g1.url.update](#urlupdate) updates a URL's query parameters
S Anand's avatar
S Anand committed
25
26
- [urlchange.min.js](dist/urlchange.min.js): URL state change events
    - [$.urlchange](#urlchange) listens to hash changes and routes events
27
28
29
30
31
- [highlight.min.js](dist/highlight.min.js): highlighting library
    - [$.highlight](#highlight) toggles classes on elements when clicked or hover

Data components:

S Anand's avatar
S Anand committed
32
33
- [formhandler.min.js](dist/formhandler.min.js): Table renderer using [FormHandler](https://learn.gramener.com/guide/formhandler/)
    - [$.formhandler](#formhandler) renders a HTML table from a [FormHandler URL](https://learn.gramener.com/guide/formhandler/)
34
35
36
37
38
- [leaflet.min.js](dist/leaflet.min.js): Leaflet utilities
    - [L.TopoJSON](#ltopojson) loads TopoJSON files just like GeoJSON. Requires [topojson](https://github.com/topojson/topojson)

Utilities:

S Anand's avatar
S Anand committed
39
- [template.min.js](dist/template.min.js): template library
40
    - [$.template](#template) renders lodash templates. Requires [lodash](https://lodash.com/)
S Anand's avatar
S Anand committed
41
- [event.min.js](dist/event.min.js): event library
42
    - [$.dispatch](#dispatch) is like [trigger](https://api.jquery.com/trigger/) but sends a native event (triggers non-jQuery events too)
S Anand's avatar
S Anand committed
43
44
- [datafilter.min.js](dist/datafilter.min.js): filtering data library
    - [g1.datafilter](#datafilter) filters the data based on the options
S Anand's avatar
S Anand committed
45
46
- [types.min.js](dist/types.min.js): type detection library
    - [g1.types](#types) returns the data types of columns in a DataFrames
S Anand's avatar
S Anand committed
47

48
## $.urlfilter
S Anand's avatar
S Anand committed
49
50
51
52
53
54
55
56
57
58

Example:

```html
<a class="urlfilter" href="?name=John">Link</a>
<script>
  $('body').urlfilter()
</script>
```

59
60
61
Let's say the page is `?city=NY`. Clicking on any `.urlfilter` (trigger) in
`body` (container) opens `?city=NY&name=John`. The `href=` in the `.urlfilter`
link *updates* the current page URL instead of replacing it.
S Anand's avatar
S Anand committed
62
63
64
65
66
67
68
69
70
71

`data-mode` controls the way the URL is updated by the `href`:

| URL    | href      | default    | `data-mode="add"` | `data-mode="toggle"` | `data-mode="del"` |
|--------|-----------|------------|-------------------|----------------------|-------------------|
| `?`    | `?x=1`    | `?x=1`     | `?x=1`            | `?x=1`               | `?`               |
| `?x=1` | `?x=1`    | `?x=1`     | `?x=1&x=1`        | `?`                  | `?`               |
| `?x=1` | `?y=1`    | `?x=1&y=1` | `?x=1&y=1`        | `?x=1&y=1`           | `?x=1`            |
| `?x=1` | `?x=2`    | `?x=2`     | `?x=1&x=2`        | `?x=1&x=2`           | `?x=1`            |

72
73
74
For example:

```html
S Anand's avatar
S Anand committed
75
76
77
78
79
80
81
82
<a class="urlfilter" href="?city=NY">                        Change ?city= to NY</a>
<a class="urlfilter" href="?city=NY" data-mode="add">        Add ?city= to NY</a>
<a class="urlfilter" href="?city=NY" data-mode="del">        Remove NY from ?city=</a>
<a class="urlfilter" href="?city=NY" data-mode="toggle">     Toggle NY in ?city=</a>

<a class="urlfilter" href="?city=NY" data-target="pushState">Change ?city= to NY using pushState</a>
<a class="urlfilter" href="?city=NY" data-target="#">        Change location.hash, i.e. #?city= to NY</a>
<a class="urlfilter" href="?city=NY" data-target="iframe">   Change iframe URL ?city= NY</a>
83
    <iframe src="?country=US"></iframe>
S Anand's avatar
S Anand committed
84
<a class="urlfilter" href="?city=NY" data-target=".block">   Use AJAX to load ?city=NY into .block</a>
85
86
87
88
89
90
    <div class="block" src="?country=US"></div>
<script>
  $('body').urlfilter()     // Activate all the .urlfilter elements above
</script>
```

91
### $.urlfilter attributes
S Anand's avatar
S Anand committed
92

93
URLFilter triggers use these attributes:
S Anand's avatar
S Anand committed
94

95
96
97
- `class="urlfilter"` indicates that this is a trigger
- `href=` updates the page URL with this link
- `data-target` defines the target where the URL is updated:
S Anand's avatar
S Anand committed
98
99
100
101
    - default: updates `window.location`
    - `pushState`: updates the current page using pushState
    - `#`: updates the `window.location.hash`
    - `.class`: loads URL into `.class` by updating its `src=` attribute as the base URL
102
103
104
105
106
- `data-mode` can be
    - empty - updates existing query key with value
    - `add` - adds a new query key and value
    - `del` - deletes query key. If value exists, only deletes the (key, value) combination
    - `toggle` - toggles the query key and value combination
S Anand's avatar
S Anand committed
107
- `data-remove`: removes any URL query parameters without values. e.g. `?x&y=1` becomes `?`
108
- `data-src` changes which attribute holds the current URL when `data-target=` is a selector. Default: `src`
S Anand's avatar
S Anand committed
109

110
URLFilter containers uses these attributes:
S Anand's avatar
S Anand committed
111

112
113
114
115
- `data-selector` changes which nodes urlfilter applies to. Default: `.urlfilter`
- `data-attr` changes which attribute updates the URL. Default: `href`
- You can also specify `data-mode`, `data-remove` and `data-src`. This is the same as specifying on
  every `.urlfilter` trigger.
S Anand's avatar
S Anand committed
116

S Anand's avatar
S Anand committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

## url.parse

`g1.url` provides URL manipulation utilities.

```js
var url = g1.url.parse("https://username:password@example.com:80/~folder/subfolder/filename.html?a=1&a=2&b=3%2E&d#hash")
```

### url object attributes

This parses the URL and returns an object with the following attributes matching `window.location`:

| Attribute  | Value                              |
|------------|------------------------------------|
| `href`     | the original URL                   |
| `protocol` | `https`                            |
| `origin`   | `username:password@example.com:80` |
| `username` | `username`                         |
| `password` | `password`                         |
| `hostname` | `example.com`                      |
| `port`     | `80`                               |
| `pathname` | `folder/subfolder/filename.html`   |
| `search`   | `a=1&a=2&b=3%2E&d`                 |
| `hash`     | `hash`                             |

... and additional attributes:

| Attribute    | Value                                                  |
|--------------|--------------------------------------------------------|
| `userinfo`   | `username:password`                                    |
| `relative`   | `folder/subfolder/filename.html?a=1&a=2&b=3%2E&d#hash` |
| `directory`  | `folder/subfolder/`                                    |
| `file`       | `filename.html`                                        |
| `searchKey`  | `{'a:'2', b:'3.', d:''}`                               |
| `searchList` | `{'a:['1', '2'], b:['3.'], d:['']}`                    |

It can also parse URL query strings.

```js
var url = g1.url.parse('?a=1&a=2&b=3%2E&d#hash')
```

| Attribute    | Value                            |
|--------------|----------------------------------|
| `search`     | `a=1&a=2&b=3%2E&d`               |
| `hash`       | `hash`                           |
| `searchKey`  | `{a:'2', b:'3.', d:''}`          |
| `searchList` | `a:['1', '2'], b:['3.'], d:['']` |

These attributes are **not mutable**. To change the URL, use
[url.join](#urljoin) or [url.update](#urlupdate).

### url object methods

The url object has a `.toString()` method that converts the object back into a
string.


## url.join

```js
var url = url.join(another_url)
```

updates the `url` with the attributes from `another_url`. For example:

| url                    | joined with          | gives                      |
|------------------------|----------------------|----------------------------|
| `/path/p`              | `a/b/c`              | `/path/a/b/c`              |
| `/path/p/q/`           | `../a/..`            | `/path/p/`                 |
| `http://host1/p`       | `http://host2/q`     | `http://host2/q`           |
| `https://a:b@host1/p`  | `//c:d@host2/q?x=1`  | `https://c:d@host2/q?x=1`  |
| `/path/p?b=1`          | `./?a=1#top`         | `/path/?a=1#top`           |

`.join()` updates the query parameters and hash fragment as well. To prevent this, use:

```js
url.join(another_url, {query: false, hash: false})
```

For example:

```js
g1.url.parse('/').join('/?x=1#y=1', {hash: false}).toString() == '/?x=1'
g1.url.parse('/').join('/?x=1#y=1', {query: false}).toString() == '/#y=1'
```


## url.update

```js
var url = url.update(object)
```

updates the `url` query parameters with the attributes from `object`. For example:

| url          | updated with         | gives                 |
|--------------|----------------------|-----------------------|
| `/`          | `{a:1}`              | `/?a=1`               |
| `/?a=1&b=2`  | `{b:3, a:4, c:''}`   | `/?a=4&b=3&c=`        |
| `/?a=1&b=2`  | `{a:null}`           | `/?b=2`               |
| `/?a=1&b=2`  | `{a:[3,4], b:[4,5]}` | `/?a=3&a=4&b=4&b=5`   |

By default, it *updates* the query parameters. But:

- `url.update(object, 'add')` *adds* the query parameters instead of updating
- `url.update(object, 'del')` *deletes* the query parameters instead of updating
- `url.update(object, 'toggle')` *toggles* the query parameters (i.e. adds if missing, deletes if present)

For example:

| url                 | updated with         | in mode             | gives                 |
|---------------------|----------------------|---------------------|-----------------------|
| `/?a=1&a=2`         | `{a:3, b:1}`         | `add`               | `/?a=1&a=2&a=3&b=1`   |
| `/?a=1&a=2'`        | `{a:[3,4]}`          | `add`               | `/?a=1&a=2&a=3&a=4`   |
| `/?a=1&a=2&b=1`     | `{a:2, b:2}`         | `del`               | `/?a=1&b=1`           |
| `/?a=1&a=2&b=1`     | `{a:[1,4]}`          | `del`               | `/?a=2&b=1`           |
| `/?a=1&a=2`         | `{a:1, b:1}`         | `toggle`            | `/?a=2&b=1`           |
| `/?a=1&a=2&b=1&b=2` | `{a:[2,3], b:[1,3]}` | `toggle`            | `/?a=1&a=3&b=2&b=3`   |

You can specify different modes for different query parameters.


```js
g1.url.parse('/?a=1&b=2&c=3&d=4')       // Update this URL
  .update({a:1, b:[2,3], c:6, d:7},     // With this object
          'a=del&b=toggle&c=add')       // Delete ?a, Toggle ?b, add ?c, update ?d (default)
// Returns /?b=3&c=3&c=6&d=7
```

## Interaction conventions

All interaction components use this naming convention:

- Interactions are enabled on a *container*, typically `body`. For example,
  `$('body').urlfilter()`. Containers have these common attributes:
    - `data-selector`: selector to identify triggers. e.g. `.urlfilter`, `.highlight`
    - `data-target`: selector that all triggers act on by default
    - `data-mode`: mode of interaction for all triggers
    - `data-attr`: attribute that contains the interaction data, e.g. `href` for `.urlfilter`
258
    - `data-event`: event that triggers urlfilter. Defaults to `'click'`
S Anand's avatar
S Anand committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
- Interactions are triggered on a *trigger*. For example, `.urlfilter` for `$().urlfilter()`.
  Clicking / hovering on / typing in a trigger triggers the interaction.
    - `data-target`: selector that this trigger acts on
    - `data-mode`: mode of interaction for this trigger
- Interactions change a *target*. For example, `urlfilter` changes `location.href` by default. The
  `data-target` on containers and triggers define this.
- Interactions data is contained in an attribute. This is applied to the target. For example,
  `.urlfilter` applied `href` to the target. The attribute name is stored in `data-attr`.
- Interactions have *modes*. This can be controlled using `data-mode=`.

All container `data-` attributes can also be passed as an option to the
function. For example, `<body data-selector=".link">` is the same as
`$('body').urlfilter({selector: '.link'})`.


274
### $.urlfilter events
S Anand's avatar
S Anand committed
275

276
- `urlfilter` is fired on the trigger when the URL is changed.
S Anand's avatar
S Anand committed
277
278
  Note: if the page is reloaded (e.g. if there is no `data-target=`),
  the page is reloaded and the event is lost. Attributes:
S Anand's avatar
S Anand committed
279
280
281
282
    - `url`: the new URL
- `load` is fired on the target when the URL is loaded -- only if the `data-target=` is a selector. Attributes:
    - `url`: the new URL

283

S Anand's avatar
S Anand committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
## $.urlchange

$.urlchange triggers custom events when the URL changes. This makes it easy to
build URL-driven applications.

Suppose we have buttons that sort based on "City" or "Sales". These are usually
bound directly to DOM events like this:

```html
<!-- DO NOT DO THIS -- this example shows what should NOT be done -->
<button class="sort">City</button>
<button class="sort">Sales</button>
<script>
  $('.sort').on('click', function(e) { action($(this).text()) })
</script>
```

**Problem**: In the example above, the sort is lost when the page is reloaded.

**Solution**: DOM events should not trigger actions directly. DOM events should
change the URL like this:

```html
<button href="?_sort=City" class="urlfilter" target="#">City</button>
<button href="?_sort=Sales" class="urlfilter" target="#">Sales</button>
<script>
  $('body').urlfilter()
</script>
```

Now, changes in the URL should trigger actions:

```js
$(window)
  .urlchange()    // URL changes trigger '#?city' events
  .on('#?city', function(e, city) { action(city) })
```

Examples:

- `#?x=1` triggers 2 events on `window`:
  - `.on('#?', function(e) { e.hash.searchKey.x == '1' }`
  - `.on('#?x', function(e, val) { val == '1' && e.vals == ['1'] })`
- When the URL changes from `#?x=1` to `#?x=1&y=2`, it triggers 2 events on `window`:
  - `.on('#?', function(e) { e.hash.searchKey == {x: '1', y: '2'} }`
  - `.on('#?y', function(e, val) { val == '2' && e.vals == ['2'] })`
  - No `#?x` event is fired, since x has not changed
- When the URL changes from `#?x=1` to `#?x=1&x=2`, it triggers 2 events on `window`:
  - `.on('#?', function(e) { e.hash.searchKey == {x: '1', y: '2'} }`
  - `.on('#?x', function(e, val) { val == '1' && e.vals == ['1', '2'] })`
  - The `#?x` event is fired since x has a new value

### $.urlchange events

- `#?` is fired when the URL hash changes. Event attributes are:
  - `hash`: a [g1.url.parse](#urlparse) object that holds the parsed URL hash
- `#?<key>` is fired for *each* key that is changed. Event attributes are:
  - `hash`: a [g1.url.parse](#urlparse) object that holds the parsed URL hash
  - `vals`: a list of values in matching `#?<key>`.
    For example, `#?x=1&x=2` triggers `#?x` with `vals=['1', '2']`
  - `val`: the first value of `vals`.


347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
## $.dropdown

Dropdown component that integrates well with g1.urlfilter

$.dropdown requires `bootstrap-select` library and its dependencies.

Examples:

```html
<div class="container1"></div>
<script>
  $('.container1').dropdown({data: ['Red', 'Green', 'Blue'] })
</script>
```
The above code snippet renders a dropdown using [bootstrap-select](https://silviomoreto.github.io/bootstrap-select/examples/) library. The rendered dropdown has 3 options namely Red, Green, Blue.

```html
<div class="container2"></div>
<script>
  $('.container2').dropdown({ key: 'colors', data: ['Red', 'Green', 'Blue'] })
</script>
```

`key` enables urlfilter for dropdown. If Red option is selected from dropdown, URL is appended with `?colors=Red`

By default, the selected dropdown values are appended to URL query string. To append to the hash instead, use `target: '#'`.

```html
<div class="container3"></div>
<script>
  $('.container3').dropdown(
    { key: 'colors',
      data: ['Red', 'Green', 'Blue'],
      target: '#'
    })
</script>
```

To change URL without reloading the page, use `target: 'pushState'`.

```html
<div class="container4"></div>
<script>
  $('.container4').dropdown(
    { key: 'colors',
      data: ['Red', 'Green', 'Blue'],
      target: 'pushState'
    })
</script>
```

To use bootstrap-select options, use `options:`

```html
<div class="container5"></div>
<script>
  $('.container5').dropdown({
    data: ['Red', 'Green', 'Blue'], key: 'colors',
    options: {
      style: 'btn-primary',
      liveSearch: true
    }
  })
</script>
```


### $.dropdown events
- `load` is triggered after dropdown is rendered
- `change` is triggered whenever dropdown value is changed

```html
<div class="container5"></div>
<script>
  $('.container5')
  .on('load', function() {
    // Your code here
  })
  .on('change', function() {
    // Your code here
  })
  .dropdown({
    key: 'colors',
    data: ['Red', 'Green', 'Blue']
  })
</script>

```

### $.dropdown options
- `data`: Array of values.
- `url`: End point that returns the `data`. If `data:` is also given, `data` takes priority.
- `target`: defines how URL is updated. Can be `''` (Default), `#` or `pushState`
- `key`: key with which URL is updated.
- `multiple`: To render a dropdown that supports multi-select. Can be `true` or `false` (Default).
- `options`: Supports same options as [bootstrap-select options](https://silviomoreto.github.io/bootstrap-select/options/)


445
## $.highlight
S Anand's avatar
S Anand committed
446

447
Highlight elements when hovering on or clicking another element.
S Anand's avatar
S Anand committed
448

449
Example:
S Anand's avatar
S Anand committed
450

451
452
453
454
455
456
457
458
459
```html
<div data-toggle="highlight" data-target="a.red" data-classes="active">Link</a>
<div data-toggle="highlight" data-target="a.red" data-classes="active" data-mode="click">Link</a>
<script>
  $('body').highlight({
    classes: 'shadow',
    mode: 'click'
  })
</script>
460
```
S Anand's avatar
S Anand committed
461

462
### $.highlight attributes
S Anand's avatar
S Anand committed
463

464
Highlight triggers use these attributes:
S Anand's avatar
S Anand committed
465

466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
- `data-toggle="highlight"` indicates that the element acts as a highlighter
- `data-target=` selectors to highlight (required)
- `data-mode="click"` highlights on click. Use `data-mode="hover"` to higlight on hover (default)
- `data-classes=` space-separated class names to toggle on target elements

Highlight containers use these attributes:

- `data-selector=` changes which nodes highlight applies to. Default: `[data-toggle="highlight"]`
- `data-mode` is the same as specifying data-mode on every highlighter. Default: `hover`
- `data-attr` is the attribute that defines classes to toggle. Default: `data-classes`
- `data-classes=` is the same as specifiying the data-classes on every highlighter. Default: `active`

### $.highlight events

- `highlight` is fired on the trigger when activated. Attributes:
    - `target`: elements that match the `data-target=` selector


S Anand's avatar
S Anand committed
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
## types

`g1.types(data)` returns the column data types. For example:

```js
var data = [
  {a: 1, b: 1.1, c: 'c', d: '2014-04-04', e: true},
  {a: 2, b: 2},
]
g1.types(data)      // Returns {"a": "number", "b": "number", "c": "string", "d": "date", "e": "boolean"}
```

### types options

`types()` accepts 2 parameters:

- `data`: a list of objects
- `options`: a dictionary that may contain these keys:
  - `convert`: converts values to the right type. For example, "1" is converted to 1. default: `false`
  - `limit`: number of rows to evaluate. default: 1000
  - `ignore`: list of values that should be ignored. default: `[null, undefined]`

Rules:

- Evaluate up to `limit` rows
- Ignore values that are keys in the `ignore` option. Only consider the rest
- If `convert` is `false`, then for each column:
  - If all values are Date objects -> `date`
  - Else if all values are numbers -> `number`
  - Else if all values are strings -> `string`
  - Else if all values are bools -> `boolean`
  - Else if there are no values or is undefined or null -> `null`
  - Else -> `mixed`
- Else if `convert` is `true`, then for each column:
  - If all values can be converted to Date -> `date`
  - Else if all values can be converted to numbers -> `number`
  - Else if all values are bools -> `boolean`
  - Else if there are no values or is undefined or null  -> `null`
  - Else -> `string`


525
## g1.datafilter
526

S Anand's avatar
S Anand committed
527
528
529
`g1.datafilter(data, filters)` returns the filtered data based on the filters. While urlfilter on [$.formhandler](#formhandler) applies filtering on data server side, `datafilter` applies urlfilter on frontend loaded data.

For example:
530
531

```js
532
var data = [
533
534
535
536
537
538
539
540
  {"ID": "1", "product": "Fan", "sales": "100", "city": "NY"},
  {"ID": "2", "product": "Fan", "sales": "80", "city": "London"},
  {"ID": "3", "product": "Fan", "sales": "120", "city": "NJ"},
  {"ID": "4", "product": "Fan", "sales": "130", "city": "London"},
  {"ID": "5", "product": "Light", "sales": "500", "city": "NY"},
  {"ID": "5", "product": "Light", "sales": "100", "city": "London"}
]

S Anand's avatar
S Anand committed
541
542
543
544
545
g1.datafilter(data, {
  'sales>': ['100'],
  'city': ['London', 'NJ'],
  'product': ['Fan']
})
546
547
// Returns [{"ID": "3", "product": "Fan", "sales": "120", "city": "NJ"}, {"ID": "4", "product": "Fan", "sales": "130", "city": "London"}]
```
548

S Anand's avatar
S Anand committed
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
g1.datafilter with multiple datasets:
```js
var data1 = [
  {"ID": "1", "product": "Fan", "sales": "100", "city": "NY"},
  {"ID": "2", "product": "Fan", "sales": "80", "city": "London"},
  {"ID": "3", "product": "Fan", "sales": "120", "city": "NJ"},
  {"ID": "4", "product": "Fan", "sales": "130", "city": "London"},
  {"ID": "5", "product": "Light", "sales": "500", "city": "NY"},
  {"ID": "5", "product": "Light", "sales": "100", "city": "London"}
]

var data2 = [
  {"ID": "1", "city": "NY"},
  {"ID": "2", "city": "London"},
  {"ID": "3", "city": "NJ"},
  {"ID": "4", "city": "London"},
  {"ID": "5", "city": "NY"},
  {"ID": "5", "city": "London"}
]

569
g1.datafilter(data1, {
S Anand's avatar
S Anand committed
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
  'datsetname2:city': ['London', 'NJ'],
  'sales>~': [100],
  'datsetname1:product': ['Fan']
}, 'datsetname1'))
// ignores datsetname2:city: ['London', 'NJ']

// Returns [{"ID": "3", "product": "Fan", "sales": "120", "city": "NJ"}, {"ID": "4", "product": "Fan", "sales": "130", "city": "London"}, {"ID": "1", "product": "Fan", "sales": "100", "city": "NY"}]


g1.datafilter(data2, {
  'datsetname2:city': ['London', 'NJ'],
  'sales>~': [100],
  'datsetname1:product': ['Fan']
}, 'datsetname2'))

// ignores datsetname1:product: ['Fan']

// Return [
//   {"ID": "2", "city": "London"},
//   {"ID": "3", "city": "NJ"},
//   {"ID": "4", "city": "London"},
//   {"ID": "5", "city": "London"}
// ]
```

- `data`: a list of objects
- `filters`: [formhandler filters][formhandler-filters] extracted using
  `g1.url.parse(url).searchList`. This converts `?city=London&sales>=1000` to
  this filters object: `{'city': ['London'], 'sales>': ['1000']}`
- `namespace`: (optional) If `namespace` is not given, all filters are applied
  on the dataset. If `namespace` is given, only filters that begin with
  `<namespace>:` or that have no `:` are applied
602

S Anand's avatar
S Anand committed
603
[formhandler-filters]: https://learn.gramener.com/guide/formhandler/#formhandler-filters
S Anand's avatar
S Anand committed
604

S Anand's avatar
S Anand committed
605
606
## $.formhandler

607
608
An interactive table component for [FormHandler][formhandler] data.

S Anand's avatar
S Anand committed
609
```html
610
<div class="formhandler" data-src="formhandler-url" data-page-size="10"></div>
S Anand's avatar
S Anand committed
611
<script>
612
613
614
$('.formhandler').formhandler({
  pageSize: 20
})
S Anand's avatar
S Anand committed
615
616
617
</script>
```

618
619
Options can passed via an options dict, and over-ridden using `data-` attributes.
In the above example, `data-page-size="10"` over-rides `pageSize: 20`.
S Anand's avatar
S Anand committed
620

621
[formhandler]: https://learn.gramener.com/guide/formhandler/
S Anand's avatar
S Anand committed
622
623
624

### $.formhandler options

625
The full list of options is below. Simple options can be specified as `data-` attributes as well.
S Anand's avatar
S Anand committed
626

627
- `src`: [FormHandler][formhandler] URL endpoint
628
- `data`: Array of objects. Dataset for formhandler table. If both `src` and `data` are provided, `data` takes priority.
629
630
631
- `namespace`: (Optional) If the URL has `?name:key=value`, the filter
  `key=value` only applies to formhandlers with namespace as `name`.
  Filters without a namespace like `?key=value` will apply to all formhandlers.
S Anand's avatar
S Anand committed
632
- `columns`: comma-separated column names to display, or a list of objects with these keys:
633
    - `name`: column name. `"*"` is a special column placeholder for "all columns" (options given for `"*"` are applied for all columns)
634
635
    - `title`: for header display. Defaults to the same value as `name`
    - `type`: `text` (default) / `number` / `date`. Data type. Determines filters to be used
636
    - `format`: string / function that returns formatted cell display value.
637
638
639
640
      - function accepts an object with these keys:
        - `name`: column name
        - `value`: cell data value
        - `row`: row data
641
        - `index`: row index
642
        - `data`: the dataset from `src`
643
644
      - strings specify a numeral.js format if the value is a number (you must include numeral.js)
      - strings specify a moment.js format if the value is a date (you must include moment.js)
645
    - `editable`: `true` (default) / `false`. When `true`, edit and save buttons appears at end of each row.
S Anand's avatar
S Anand committed
646
647
648
649
650
      - To bind UI input element such as dropdown, datepicker, radio etc., `editable` accepts an object with these keys.
        - `input`: **Mandatory**. The type of input element to use. The valid values are checkbox, radio, range, select, and any other legal [HTML form input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
        - `options`: An array of options to select from. **Mandatory** if `input` is either of `select` or `radio`
        - `attrs`: To place common attributes such as max, min, placeholder, name etc., on the `input` element.

S Anand's avatar
S Anand committed
651
          Example:
S Anand's avatar
S Anand committed
652
          `input: 'number', attrs: {step: 10, placeholder: '0 - 1000', name: 'some_name'}` would render as
S Anand's avatar
S Anand committed
653

S Anand's avatar
S Anand committed
654
655
          `<input step=10 placeholder="0 - 1000" name="some_name" />`

S Anand's avatar
S Anand committed
656
657
    - `template`: string template / function that renders the cell.
      - function accepts an object with these keys:
658
        - `name`: column name
S Anand's avatar
S Anand committed
659
        - `value`: cell data value
660
        - `format`: formatted cell display value
S Anand's avatar
S Anand committed
661
        - `link`: cell link value (if applicable)
662
663
        - `index`: row index
        - `row`: row data
S Anand's avatar
S Anand committed
664
665
        - `data`: the dataset from `src`
      - string template can use the above variables
666
667
668
669
    - `sort`: `true` / `false` / operators dict with:
      - `{'': 'Sort ascending', '-': 'Sort descending'}` (default)
    - `filters`: `true` (default) / `false` / operators dict with:
      - `{'', 'Equals...', '!', 'Does not equal...', ...}`.
S Anand's avatar
S Anand committed
670
        The default list of operators is based on the auto-detected type of the column.
671
672
    - `link`: string / function that generates a link for this each cell.
      - If no `link:` is specified, clicking on the cell filters by that cell.
673
674
675
676
677
678
679
680
681
682
683
      - If `link:` is a function, opens a new window with the URL as `fn(args)`.
        - function accepts an object with these keys:
          - `name`: column name
          - `value`: cell data value
          - `format`: formatted cell display value
          - `index`: row index
          - `row`: row data
          - `data`: the dataset from `src`
        Example: `function(args) { return 'https://example.org/city/' + args.value }`
      - If `link:` is a string, opens a new window with the string URL interpolated as a lodash template with an object (mentioned above) as data.
        Example: `"https://example.org/city/<%- value >"`
684
685
    - `hideable`: `true` (default) / `false`. Show or hide `Hide` option in header dropdown
    - `hide`: `true` / `false` (default). Hides the column
686
    - `unique`: TODO: {dict of query parameter and display value} or [list of values] or function?
687
- `edit`: Shows the Edit control. Can be `true` / `false` (default). Can also pass an object.
688
  - `done`: function that gets called after saving the edited row.
689
690
691
- `add`: Show the Add control. Can be `true` / `false` (default). Can also pass an object.
  - `done`: function that gets called after saving the new row.
- `actions`: A list of objects. you need not add it to actions
692
  - `{{action}}`: a function() that gets triggered on clicking the element with `data-action='{{action}}` attribute. The value of `data-action` attribute must match with key `{{action}}` in `actions`.
693
694
695
      - function accepts an object with these keys:
        - `row`: row data
        - `index`: index of the row in the dataset from `src`
696
697
698
        - `notify(message)`: a function that shows a notification
      - If the return value can be a jQuery deferred (e.g. `$.ajax`), it shows a loading indicator and a success / failure message when the deferred is resolved. Example:
        - `highlight_row`: `function(obj) { $(obj.row).addClass('.yellow_color')}`. Either a new column can be defined in `columns:` (example: {`name`: `Additional Col`}) with cell_template having an element with data attribute as `data-action='highlight_row'` or can use an existing column but with custom template that has an element with data attribute as `data-action='highlight_row'`.
699
  - Note: DELETE operation is executed on a row if an element has data attribute `data-action='delete'`. If `delete` action is given in `actions`, the function given for `delete` is executed on click of an element with `data-action='delete'` instead od executing DELETE operation.
S Anand's avatar
S Anand committed
700
701
702
703
- `table`: Shows the table control. Can be:
  - `true`: displays a table (default)
  - `'grid'`: renders a grid instead of a table
  - `false`: disables the table (and shows nothing for the main content)
704
- `count`: Shows the number of rows. Can be `true` (default) / `false`
S Anand's avatar
S Anand committed
705
706
707
708
709
710
711
- `page`: Shows the page control. Can be `true` (default) / `false`.
- `pageSize`: page size. Defaults to 100
- `size`: Shows the page size control. Can be `true` (default) / `false`
- `sizeValues`: Allowed page size values. Defaults to `[10, 20, 50, 100, 500, 1000]`
- `export`: Shows the export control. Can be `true` (default) / `false`
- `exportFormats`: {xlsx: 'Excel'}
- `filters`: Shows the applied filters control. Can be `true` (default) / `false`
712
713
714
715
716
717
- `transform`: an optional function() that modifies data. It accepts a dict that has keys:
    - `data`: the FormHandler data
    - `meta`: the FormHandler metadata from the `FH-*` HTTP headers
    - `args`: the URL query parameters passed to the FormHandler
    - `options`: the options applicable to the FormHandler
    - returns a dict with modified values of `data` and `meta`
718
719
720
721
722
723
724
725
726
- `icon`: if `table: 'grid'` is used, display an icon. string / function that renders the cell.
    - function accepts an object with these keys:
      - `row`: row data
      - `data`: the dataset from `src`
      - `index`: index of the row in the dataset from `src`
  Example:
    - `icon: 'fa fa-home fa-3x'` renders a FontAwesome home icon
    - `icon: './path/to/image.png'` renders the image specified
    - `icon: function(args) { return args.row['image_link'] }` renders an image with `src` attribute as the value from column name `image_link`
S Anand's avatar
S Anand committed
727
728
729
730

**Advanced**. Each component can have a target which specifies a selector. For
e.g., to render the export button somewhere else, use
`data-export-target=".navbar-export"`. This replaces the `.navbar-export`
731
732
733
contents with the export button. (It searches within the table container for
`.navbar-export` first, and if not found, searches everywhere.) Available
targets are:
S Anand's avatar
S Anand committed
734
- `tableTarget`
735
- `countTarget`
S Anand's avatar
S Anand committed
736
737
738
739
740
741
742
743
744
745
- `pageTarget`
- `sizeTarget`
- `exportTarget`
- `filtersTarget`
- `searchTarget`

**Advanced**: Each component's template string can be over-ridden. For example,
`data-search-template="<input type='search'>"` will replace the search template
with a simple input. Available template strings are:
- `tableTemplate`
746
- `countTemplate`
S Anand's avatar
S Anand committed
747
748
749
750
751
- `pageTemplate`
- `sizeTemplate`
- `exportTemplate`
- `filtersTemplate`
- `searchTemplate`
S Anand's avatar
S Anand committed
752
753
754
- `rowTemplate`, which can be a string template or function
  - function accepts an object with these keys:
    - `row`: row data
755
    - `index`: row index
S Anand's avatar
S Anand committed
756
757
    - `data`: the dataset from `src`
  - string template can use the above variables
S Anand's avatar
S Anand committed
758

759
760
761
762
763
764
765
766
767
768
769
770
771
772
Features to be implemented:

- Loading indicator
- Full text search
- URL targets other than '#', e.g. pushState

### $.formhandler events

- `load` is fired on the source when the template is rendered. Attributes:
    - `formdata`: the FormHandler data
    - `meta`: the FormHandler metadata
    - `args`: the URL query parameters passed to the request
    - `options`: applied options to the FormHandler

773
774
  Note: Make sure `load` event listener is attached before calling `$.formhandler()`

S Anand's avatar
S Anand committed
775
776
- `editmode` is fired on the source when the Edit button is clicked and table changes to edit mode.

777
### $.formhandler examples
S Anand's avatar
S Anand committed
778

S Anand's avatar
S Anand committed
779
Render a table using the FormHandler at `./data`:
S Anand's avatar
S Anand committed
780
781

```html
S Anand's avatar
S Anand committed
782
<div class="formhandler" data-src="./data"></div>
S Anand's avatar
S Anand committed
783
784
785
786
787
<script>
  $('.formhandler').formhandler()
</script>
```

S Anand's avatar
S Anand committed
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
Customize cell rendering to display a chart in a cell:

```html
<div class="formhandler" data-src="./data"></div>
<script>
  $('.formhandler').formhandler({
    columns: [
      {name: '*'},
      {
        name: 'c1',
        format: function (o) {
          return '<svg height="10" width="10"><circle cx="5" cy="5" r="' + o.c1 / 10 + '" fill="red"></circle></svg>'
        }
      }
    }
  })
</script>
```

S Anand's avatar
S Anand committed
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
In edit mode, show HTML input bindings like Dropdown, Datepicker, Number fields.. :

```html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.js"></script>

<div class="edit-fh" data-src="./data"></div>
<script>
      $('.edit-fh').formhandler({
        columns: [
          {
            name: 'ID',
            editable: false     // Disable edit for column "ID" because it is a primary key and cannot be edited.
          },
          {
            name: 'Continent'  // Defaults to editable: false
          },
          {
            name: 'c1',
            editable: {
              input: 'number',
              attrs: {        // keys and values in `attrs` will be added as <input type="number" min=10 max=100 placeholder="0 - 100"/>
                min: 10,
                max: 100,
S Anand's avatar
S Anand committed
834
                placeholder: '0 - 100'
S Anand's avatar
S Anand committed
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
              }
            }
          },
          {
            name: 'Stripes',
            editable: {
              input: 'select',  // renders a default select dropdown as <select class="form-control form-control-sm">...</select>
              options: [        // `options` is mandatory because `input` is "select"
                'Vertical',
                'Horizontal',
                'Diagonal'
              ]
            }
          },
          {
            name: 'Shapes',
            editable: {
              input: 'select',
              options: [
                'Circle',
                'Crescent',
                'Triangle',
                'Stars'
              ],
              attrs: {
                class: 'select-example-basic',  // To render the dropdown as select2 library dropdown, add class attribute as identifier
                name: 'shapes'
              }
            }
          },
          {
            name: 'date_col',
            editable: {
              input: 'text',
              attrs: { // To edit column "date_col" using a date picker widget using "bootstrap-datepicker" library, add class attribute as identifier
                class: 'datepicker-example form-control form-control-sm'
              }
            }
          }
        ]
      }).on('editmode', function () {
        // turns <select class="select-example-basic">...</select> to select2 dropdown widget
        $('.select-example-basic').select2()
        // turns <input type="text" class="datepicker-example"/> to bootstrap-datepicker calendar widget
        $('.datepicker-example').datepicker({
          format: 'dd-mm-yyyy',
          todayHighlight: true,
          autoclose: true
        })
      })
</script>
```

S Anand's avatar
S Anand committed
888

S Anand's avatar
S Anand committed
889

890
891
892
893
894
## $.template

```html
<script type="text/html">Your platform is <%= navigator.userAgent %></script>
<script>
895
  $('body').template()
896
897
898
</script>
```

899
900
renders all `script[type="text/html"]` as [lodash templates](https://lodash.com/docs/#template).
This displays `Your platform is ...` and shows the userAgent just below the script tag.
901
902
903
904

- Anything inside `<% ... %>` is executed as Javascript.
- Anything inside `<%= ... %>` is evaluated in-place.

905
906
The template can use all global variables. You can pass additional variables
using as `.template({var1: value, var2: value, ...})`. For example:
907
908
909
910
911
912
913
914

```html
<script type="text/html">
  <% list.forEach(function(item) { %>
    <div><%= item %></div>
  <% }) %>
</script>
<script>
915
  $('body').template({list: ['a', 'b', 'c']})
916
917
918
</script>
```

919
920
To re-render the template, run `.template(data)` again with different data.

921
### $.template options
922

923
To re-use the template or render the same template on a different DOM node,
924
925
run `.template(data, {target: selector})`. This allows you to declare templates
once and apply them across the body. For example:
926
927
928

```js
$('script.chart')
929
930
931
    .template({heading: 'Dashboard 1'}, {target: '.dashboard1'})
    .template({heading: 'Dashboard 2'}, {target: '.dashboard2'})
    .template({}, {target: '.no-heading'})
932
```
933

934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
The target can also be specified via a `data-target=".dashboard1"` on the script
template. This is the same as specifying `{target: '.dashboard'}`. For example:

```html
<script class="chart" data-target=".dashboard1">...</script>
<script class="chart" data-target=".dashboard2">...</script>
```

To append instead of replacing, run `.template(data, {append: true})`. Every
time `.template` is called, it appends rather than replaces. For example:

```js
$('script.list')
    .template({heading: 'Item 1'}, {append: true}),   // Appends the heading
    .template({heading: 'Item 2'}, {append: true}),   // instead of replacing it
```

You can also specify this as `<script data-append="true">`. This helps append to
an existing target. For example:

```html
<script class="list" data-append="true" data-target=".existing-list">...</script>
<ul class="existing list">
  <li>Existing item</li>
  <!-- Every time .template() is called, the result is added as a list item here -->
</ul>
```


963
### $.template attributes
964
965
966
967
968
969

Template containers can have an `src=` attribute that loads the template from a file:

```html
<script type="text/html" src="template.html"></script>
<script>
970
  $('body').template()
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
</script>
```

If the `src=` URL returns a HTTP error, the HTML *inside* the script is rendered as
a template. The template can use:

- all data passed by the `$().template()` function, and
- an [xhr](http://api.jquery.com/Types/#jqXHR) object - which has error details

For example:

```html
<script type="text/html" src="missing.html">
  Template returned error code: <%= xhr.status %>.
  Data is <%= data %>
</script>
<script>
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
  $('body').template({data: data})
</script>
```

`$().template()` renders all `script[type="text/html"]` nodes.
Use `data-selector=` attribute to change the selector. For example:

```html
<section data-selector="script.lodash-template">
  <script class="lodash-template">...</script>
</section>
<script>
  $('section').template()
</script>
```

Or you can directly render templates using

```html
<script>
  $('script.lodash-template').template()
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
</script>
```

### $.template events

- `template` is fired on the source when the template is rendered. Attributes:
    - `templatedata`: the passed data
    - `target`: the target nodes rendered, as a jQuery object

For example:
1019
1020
1021

```js
$('script[type="text/html"]')
1022
1023
1024
1025
1026
1027
  .on('template', function(e) {       // Returns nodes rendered by the template
    e.target                          // Get the target nodes
      .filter('div')                  // Filter all <div> elements inside
      .attr('class', 'item')          // Change their class
  })
  .template()                         // Trigger the template AFTER binding the event handler
1028
1029
1030
1031
```

## $.dispatch

S Anand's avatar
S Anand committed
1032
1033
Triggers a native JavaScript event. For example:

1034
1035
1036
1037
```js
$('a.action').dispatch('click')
```

S Anand's avatar
S Anand committed
1038
1039
1040
1041
sends a click to `a.action`. Like [$.trigger](https://api.jquery.com/trigger/),
but this will fire non-jQuery event handlers as well.

### $.dispatch options
1042
1043
1044
1045
1046
1047
1048
1049
1050

You can add an optional dict as the second parameter. It can have any
[event properties](https://developer.mozilla.org/en-US/docs/Web/API/Event#Properties)
as attributes. For example:

```js
$('a.action').dispatch('click', {bubbles: true, cancelable: false})
```

S Anand's avatar
S Anand committed
1051
1052
1053
1054
1055
1056
- bubbles: whether the event bubbles or not. default: true
- cancelable: whether the event is cancelable or not. default: true
- All other `new Event()` options will also work

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077

## L.TopoJSON

```js
var layer = new L.TopoJSON(topojson_data).addTo(map)
```

adds a TopoJSON layer to a leaflet map. The usage is identical to [L.GeoJSON()](http://leafletjs.com/reference-1.2.0.html#geojson).

Typical usage is below:

```js
$.get('topojson-file.json')
  .done(function(topojson_data) {
    var map = L.map('map-id')
    var layer = new L.TopoJSON(topojson_data).addTo(map)
    map.fitBounds(layer.getBounds())
  })
```


S Anand's avatar
S Anand committed
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
## sanddance

Transitions elements with flexible timing controls.

### sanddance options

It accepts 2 parameters

1. `attrs`: changes any HTML / SVG attributes of the selection (e.g. `fill`, etc)
  - `fill`, `stroke` for color
  - `x`, `y`, `cx`, `cy`, `transform`, etc for position (but these are better controlled via the options)
  - etc.
2. `options`: defines layout options (e.g. `x`, `y`, `duration`, `speed`, etc)
  - `x`: transition the elements to the x position
  - `y`: transition the elements to the y position
  - `speed`: transition at constant speed in pixels per second
  - `duration`: transition time in milliseconds (overrides `speed`)
  - `delay`: transition delay in milliseconds (default is 0)
  - `easing`: transition easing in d3-ease method (default is d3.easeLinear)
  - `filter`: filter the selection based on a column value (ex: age > 30)

Examples:

```js
// smoothly changes the fill color to blue in 100 ms
var turn_to_blue = g1.sanddance({ fill: 'blue' }, { duration: 100 })
selection.call(turn_to_blue)

// g1.sanddance moves elements to the x, y specified in 100ms
var move = g1.sanddance({}, { x: 200, y: 200, duration: 100 })
selection.call(move)

// transitions at 1000 pixels/sec.
var move_at_constant_speed = g1.sanddance({}, {x: 300, y: 300, speed: 1000})
selection.call(move_at_constant_speed)

// transitions in 100ms duration.
var move_in_duration = g1.sanddance({}, {x: 400, y: 400, duration: 100})
selection.call(move_in_duration)

// transitions after 100ms delay.
var move_after_delay = g1.sanddance({}, {x: 300, y: 300, delay: 100})
selection.call(move_after_delay)

// transitions at ease of d3.easeBounce
var move_easing = g1.sanddance({}, {x: 300, y: 300, duration: 100, easing: d3.easeBounce})
selection.call(move_easing)

// filters the selection
var selection_filtered = g1.sanddance({fill: 'red'}, {duration: 100, filter: function(d) { return d.age > 30}})
selection.call(selection_filtered)
```

### sanddance.chain

To apply a sequence of sanddances one after another, use `g1.sanddance.chain`. For example:

```js
// chain sanddances. First, fill everything red, then move x to 200 and y to 100
selection.call(
  g1.sanddance.chain(
    g1.sanddance({fill: 'red'}, {duration: 100}),
    g1.sanddance({}, {x: 200, y: 100, duration: 100})
  )
)
```

### sanddance layouts

#### 1. grid

Returns a sanddance that moves elements into a grid. Usage:

```js
// Lay out the elements in a grid
selection.call(
  g1.sanddance({}, {        // Create a layout based on the data array
    layout: 'grid',         // lay out as a grid
    width: 400,             // with width 400
    height: 300,            // and height 300
    data: data,             // using the specified data
    sort: 'age',            // sorted by the 'age' column
    ascending: false,       // in descending order
    duration: 100           // in 100ms
  })
)
```

Options:
- `data`: an array that has the data that is used to lay out the elements
- `width`: width of the grid in SVG units
- `height`: height of the grid in SVG units
- `sort`: column name or `function(d, i)` to sort by
- `ascending`: `false` reverses the sort order (default: `true`)

Values can be specified as a scale. Example: `fill:` can be specified as below.

```js
fill: {
  metric: 'age',
  scheme: 'RdYlGn'
}
// or
fill: {
  metric: 'age',      // same as function(d) { return d.age }
  scale: 'linear',
  domain: [0, 50, 100],
  range: ['red', 'yellow', 'green'],
}
```

Scales are dictionaries with the following keys:

- `metric:` can be a string column name or a `function(d, i)` that returns a value for each item in the data
- `scheme:` d3 chromatic color scheme to interpolate to (e.g. `'RdYlGn'`)
- `scale:` d3 scale to use. Defaults to `'linear'`
- `range`: a list that contains the scale's range
- `domain`: a list that contains the scale's domain (defaults to the extent of the metric)

```js
// fill as scale config with linear scale
selection.call(
  g1.sanddance({
    fill: {
      metric: function(d) { return d.age },
      scale: 'linear',
      domain: [0, 100],
      range: ['red', 'blue'],
    }
  }, {
    layout: 'grid',
    data: data,
    width: 400,
    height: 300,
    duration: 100
  })
)

// fill as scale config with scheme
selection.call(
  g1.sanddance({
    fill: {
      metric: function(d) { return d.age },
      scheme: 'RdYlGn'
    }
  }, {
    layout: 'grid',
    data: data,
    width: 400,
    height: 300,
    duration: 100
 })
)
```

#### 2. hexpack

Returns a sanddance that moves elements into a hexpack. Usage:

```js
// Lay out the elements in a hexpack
selection.call(
  g1.sanddance({}, {        // Create a layout based on the data array
    layout: 'hexpack',      // lay out as hexpack
    width: 400,             // with width 400
    height: 300,            // and height 300
    data: data,             // using the specified data
    sort: 'age',            // sorted by the 'age' column
    ascending: false,       // in descending order
    duration: 100           // in 100ms
  })
)
```
The values can also be specified as a scale config and the options definitions are same as grid.

### sanddance methods

`sanddance.update(new_attrs, new_options)` returns a new sanddance that updates
the old `attrs` with `new_attrs` and the old `options` with `new_options`.

```js
// The two lines below are the same:
g1.sanddance({ stroke: 'blue' }).update({ fill: 'red' })
g1.sanddance({ stroke: 'blue', fill: 'red' })

// Update the options
g1.sanddance({}, { delay: 100 }).update({}, { duration: 100 }),
g1.sanddance({}, { duration: 100, delay: 100 })
```

### sanddance events

These events are triggered by the sanddance object.

- `init` when the sanddance is initialized
- `start` when the first transition begins (after delay)
- `end` when all transitions are complete

All events set the d3 selection as `this`. For example:

```js
// sanddance events
selection.call(
  g1.sanddance({ fill: 'red' })
    .on('init.log', function() { console.log('init', this) })
    .on('start.log', function() { console.log('start', this) })
    .on('end.log', function() { console.log('end', this) })
)
```

1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
## g1.mapviewer

Mapviewer is an abstraction over [Leaflet](http://leafletjs.com/) that can
create common GIS applications using configurations.

Mapviewer requires `npm install leaflet d3 d3-scale-chromatic g1`.

```html
<link rel="stylesheet" href="node_modules/leaflet/dist/leaflet.css">
<script src="node_modules/leaflet/dist/leaflet.js"></script>
<script src="node_modules/d3/build/d3.js"></script>
<script src="node_modules/d3-scale-chromatic/dist/d3-scale-chromatic.min.js"></script>
<script src="node_modules/g1/dist/mapviewer.min.js"></script>
```

This creates a simple base map:

```html
<div id="base-map" style="height:300px"></div>
<script>
  var map = g1.mapviewer({
    id: 'base-map',
    layers: {
      worldMap: { type: 'tile', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' }
    }
  })
</script>
```

This creates a set of markers for each row in [cities.json](test/cities.json).

```html
<div id="marker-map" style="height:300px">
<script>
  var map = g1.mapviewer({
    id: 'marker-map',
    layers: {
      worldMap: { type: 'tile', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
      cityMarkers: {
        type: 'marker',
        url: 'cities.json',
        latitude: 'lat',
        longitude: 'long',
        options: {
          // title: 'column-name'      // TODO
        }
        // TODO: allow specifying styles (e.g. color, icon file, etc) from data
      }
    }
  })
</script>
```

This creates a set of circle markers for each row in [cities.json](test/cities.json).
You can apply styles based on any attribute or function.

```html
<div id="circle-marker-map" style="height:300px">
<script>
  var map = g1.mapviewer({
    id: 'circle-marker-map',
    layers: {
      worldMap: { type: 'tile', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
      cityMarkers: {
        type: 'circleMarker',
        url: 'cities.json',
        latitude: 'lat',
        longitude: 'long',
        attrs: {
          fillColor: {
            metric: 'pollution',
S Anand's avatar
S Anand committed
1359
            scheme: 'RdYlGn'
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
          }
        }
      }
    }
  })
</script>
```

This loads a [GeoJSON file](test/india-states.geojson), links data from
[state_score.json](test/state_score.json), and sets the fill color from a merged
attribute.

```html
<div id="geojson-map" style="height:300px">
<script>
  var map = g1.mapviewer({
    id: 'geojson-map',
    layers: {
      worldMap: { type: 'tile', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
      indiaGeojson: {
        type: 'geojson',
        url: 'india-states.geojson',
        link: {
          url: 'state_score.json',    // Load data from this file
          dataKey: 'name',            // Join this column from the URL (data)
          mapKey: 'ST_NM'             // with this property in the GeoJSON
        },
S Anand's avatar
S Anand committed
1387
1388
1389
1390
1391
1392
        options: {
          style: {
            fillColor: '#a00',
            fillOpacity: 1
          }
        },
1393
1394
        attrs: {
          fillColor: {                // Fill the regions
S Anand's avatar
S Anand committed
1395
1396
            metric: 'score',          // with the "score" column from state_score.json
            scheme: 'RdYlGn'           // using a RdYlGn gradient
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
          },
          tooltip: function(prop) {   // On hover, show this HTML tooltip
            return prop.ST_NM + ': ' + prop.TOT_P
          }
        }
      }
    }
  })
</script>
```
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
This adds legend to the map

```html
<div id="choropleth" class="map"></div>
<script>
  var choro_map = g1.mapviewer({
    id: 'choropleth',
    legend: {
      position: 'topright',
      format: 'd',
      shape: d3.symbolCircle,
      size: 100,
      scale: d3.scaleLinear().domain([10, 20, 30]).range(['red', 'yellow', 'green']),
      orient: 'horizontal',
      width: 300,
      height: 100
    },
    layers: {
      worldMap2: { type: 'tile', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
      indiaGeojson: {
        type: 'geojson',
        url: 'india-states.geojson',
        link: {
          url: 'state_score.json',
          dataKey: 'name',
          mapKey: 'ST_NM'
        },
        options: {
          style: {
            fillColor: '#ccc',
            fillOpacity: 1
          }
        },
        attrs: {
          fillColor: {
            metric: 'score',
            scale: 'linear',
            domain: [10, 20, 30],
            range: ['red', 'yellow', 'green'],
          }
        }
      }
    }
  })
</script>
```
1453

1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
Drilldown feature example:

```html
<div id="geojson-map" style="height:300px">
<script>
  var map = g1.mapviewer({
    id: 'geojson-map',
    layers: {
      worldMap: { type: 'tile', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
      indiaGeojson: {
        type: 'geojson',
        url: 'india-states.geojson',
        link: {
          url: 'state_score.json',    // Load data from this file
          dataKey: 'name',            // Join this column from the URL (data)
          mapKey: 'ST_NM'             // with this property in the GeoJSON
        },
        attrs: {
          fillColor: {                // Fill the regions
            metric: 'score',          // with the "score" column state_score.json
            range: 'RdYlGn'           // using a RdYlGn gradient
          },
          tooltip: function(prop) {   // On hover, show this HTML tooltip
            return prop.ST_NM + ': ' + prop.TOT_P
          }
        }
      }
    },
    drilldown: {
      rootLayer: 'indiaGeojson',
      levels: [
        {
          layerName: function(properties) {return properties['STATE'] + '-layer'},
          layerOptions: {
            url: function(properties) {return properties['STATE'] + '-census.json'},
            type: 'geojson',
            attrs: {
              fillColor: {
                metric: 'DT_CEN_CD',
                range: 'RdYlGn'
              },
              tooltip: function (properties) {
                return 'DISTRICT: ' + properties['DISTRICT']
              }
            }
          }
        }
      ]
    }
  })
</script>
```

1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
**Note**: You can use `type: 'topojson'` when loading TopoJSON maps.

### g1.mapviewer options

- `id`: ID of the map DOM element (example: `mapid`), or the DOM element
- `map`:
    - `options`: supports same options as [Map options](http://leafletjs.com/reference-1.3.0.html#map)
- `layers`: builds layers one on top of another in the specified order.
  - `{layername: {...} }` dict with layer name as keys
  - Each layer MUST have a type. Currently supported types are
    - tile
    - geojson
    - topojson
1520
    - marker (`link`: option is not yet supported )
1521
1522
1523
1524
1525
1526
1527
1528
    - circleMarker
  - `tile` layer MUST have a url: that has the URL template for the leaflet tile layer.
    - `url`: A string of the form - `http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png`
    - `options`: supports same options as [Tile options](http://leafletjs.com/reference-1.3.0.html#tilelayer-minzoom)
  - `geojson` layer MUST have a data as an array of objects or else MUST have a url (string).
    - `url`: String
    - `data`: An array of objects. data: takes preference over url.
    - `options`: supports same options as [GeoJSON options](http://leafletjs.com/reference-1.3.0.html#geojson-style)
1529
    - `link`: adds attributes from input dataset to geojson/topojson
1530
      - `url` is url (String) to fetch data
1531
1532
      - `mapKey` is attribute name in geojson/topojson to match
      - `dataKey` is column name in input dataset that matches with geojson/topojson `mapKey`
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
    - `popup`: string / function that returns formatted value
    - `popupOptions`: An object with properties and values from [leaflet popup options](https://leafletjs.com/reference-1.3.4.html#popup-l-popup)
    - `tooltip`: string / function that returns formatted value.
      - function(properties) must return a string. feature properties are passed as argument.
    - `tooltipOptions`: An object with properties and values from [leaflet tooltip options](https://leafletjs.com/reference-1.3.0.html#tooltip-option)
      - `direction` property can be a string or function. function is passed the following arguments.
        - `centerPoint` is center coordinates of map view
        - `tooltipPoint` is center coordinates of tooltip
        - `properties` are feature properties

    NOTE: `tooltip` and `tooltipOptions` are previously (till v0.9.l) are inside `attrs`. This spec breaking change is mage to maintain consistency with `popup` and `popupOptions`
S Anand's avatar
S Anand committed
1544
    - `attrs` Data driven styles. same as `options`. (`attrs` take priority over `options`)
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
      - For `color`, `weight`, `opacity`, `fillColor`, `fillOpacity` properties, the options are:.
        - `metric` string / function
          - If `metric`: is a string, can be any numeric property of geojson
          - To have a metric that is formala based on multiple properties, use function. Example: `function(row) { return row['congress_votes'] - row['bjp_votes']}`
        - `domain` An array of two numbers. Defaults to calculated values of given `metric`.
        - `range`
          - For `fillColor` and `color`, must be a [interpolate color scheme](https://github.com/d3/d3-scale-chromatic#diverging)
          - For `weight`, `opacity`,`fillOpacity` must be an array with min and max values
      - `tooltip`: string / function that returns formatted value.
        - function(properties) must return a string. feature properties are passed as argument.
        - TODO: the properties currently include only geoJSON properties. link properties must be added
1556
      - `tooltipOptions`: An object with properties and values from [leaflet tooltip options](https://leafletjs.com/reference-1.3.0.html#tooltip-option)
1557
  - `topojson` - same as `geojson`
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
  - `marker` layer MUST have a data as an array of objects or else MUST have a url (string).
    - `url`: String
    - `data`: An array of objects. data: takes preference over url.
    - `latitude`: String (mandatory). Must be column name that contains latitude of marker
    - `longitude`: String (mandatory). Must be column name that contains longitude of marker
    - `options`: supports same options as [marker options](http://leafletjs.com/reference-1.3.0.html#marker-icon)
  - `circleMarker` layer MUST have a data as an array of objects or else MUST have a url (string).
    - `url`: String
    - `data`: An array of objects. data: takes preference over url.
    - `latitude`: String (mandatory). Must be column name that contains latitude of marker
    - `longitude`: String (mandatory). Must be column name that contains longitude of marker
    - `options`: supports same options as [circleMarker options](http://leafletjs.com/reference-1.3.0.html#circlemarker-radius)
    - `attrs` same as `attrs` for `geojson` type layer
1571
1572
1573
- `drilldown`:
    - `rootLayer`: `geojson/topojson` layer that acts as root layer to drilldown further.
    - `levels`: Array of objects that provides layer info
1574
      - `layerName`: Can be a string or function. Function takes argument as `properties` of parentLayer feature
1575
      - `layerOptions`: Same as layer options in `layers` option. If `url` is function, `url` takes argument as `properties` of parentLayer feature
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
- `legend`: configuration of legend to be added to layer. It requires [d3-legend](https://cdnjs.com/libraries/d3-legend). This creates a `<div class="map-legend">`.
    - `position`: can be `topright`, `topleft`, `bottomleft` or `bottomright`(Defaults to `bottomright`)
    - `format`: accepts d3 formats and applies to legend labels. (Defaults to `d`)
    - `shape`: can be a d3 symbol or an svg path. Default `d3.symbolSquare`
    - `size`: size of legend cell
    - `cells`: number of cells in legend. Default `5`
    - `width`: width of legend
    - `height`: height of legend
    - `scale`: accepts d3 scale format (mandatory). For examples, refer [d3-legend](https://d3-legend.susielu.com/#color-examples)
    - `orient`: orientation of legend. Can be `vertical` (Default) or `horizontal`
    - `shapeWidth`: width of legend cell. Default `20`
    - `shapePadding`: padding of legend cell. Default `20`
    - `labelOffset`: value to determine distance of label from each legend cell. Default `20`
1589
1590

### g1.mapviewer methods
1591
`fitToLayer(layerName, options)`
1592
1593
Zooms map view to fit the layer. Supports same options as [fitBounds options](http://leafletjs.com/reference-1.3.0.html#fitbounds-options)

1594
1595
1596
`zoomHandler(layerName, minZoomLevel, maxZoomLevel(optional) )`
Shows the layer with `layerName` only between `minZoomLevel` and `maxZoomLevel`.

1597
1598
### g1.mapviewer events

1599
1600
1601
- `layersloaded` is fired when all layers are saved in mapviewer.gLayers (used interally).
  - tooltip is rendered on each layer only after `layersload` is fired
- `layerName + 'loaded'` is fired for each layer with name as `layerName`
S Anand's avatar
S Anand committed
1602

S Anand's avatar
S Anand committed
1603
1604
1605
1606
1607
1608
1609
## Contributing

Contributions are welcome.

- Please report bug fixes on the [issues page](https://code.gramener.com/s.anand/g1/issues)
- Developers may read [CONTRIBUTING.md](CONTRIBUTING.md) to understand the file
  structure and how to set this repository up