# Mapping

A service answers in its own shape, and a card has fields of its own: a stat's `value`, a list's `items`. A sourced card's `map` joins the two. Each key is a field of the card, and each value is a rule that says where it comes from in the answer.

The simplest rule is a path, such as `summary.queries.total`. Others fill in a template, build a list from an array, count or total it, choose between two rules on a condition, or do arithmetic. `derive` works a value out once on the source, and every card that uses the source can read it.

Paths, rules and the options a list takes are all below. Four subjects have a page each:

- [Names and tables](https://legatobar.com/docs/mapping-tables.md): Answers that use names as keys or parallel arrays, and tables that need flattening or grouping.
- [Expiry and slices of time](https://legatobar.com/docs/mapping-expiry.md): Days left on a certificate or a renewal, and a long series cut into a set number of slices.
- [Conditions](https://legatobar.com/docs/mapping-conditions.md): The tests a rule, a card or a button can make on the answer.
- [Sparkline readings](https://legatobar.com/docs/mapping-sparklines.md): A sparkline of a value the service only reports as it is now.

## Derived values

`derive` works out values from the answer and adds them to it, in order, so a later one can use an earlier one, and so can `map`. Each entry is a name and a [rule](https://legatobar.com/docs/mapping.md#mapping). This source fragment assumes its named requests produce a `monitors` array:

```json
"derive": [
  { "name": "total", "value": { "count": "monitors" } },
  { "name": "problems", "value": { "count": "monitors", "where": { "path": "monitor_status", "not": 1 } } },
  { "name": "headline", "value": {
      "if": { "path": "total", "equals": 0 },
      "then": { "template": "No monitor data" },
      "else": { "if": { "path": "problems", "equals": 0 },
                "then": { "template": "All {total} up" },
                "else": { "template": "{problems} of {total} need attention" } }
  } }
]
```

Names are lowercase letters, digits and `_`. An answer that isn't an object is kept under `data`.

## Mapping

`map` is an object whose keys are fields of the card and whose values are rules saying where each one comes from in the answer. A key can reach into the card's own lists: `items[0].value` fills the first fact's value. Card fields have plain names, so a map key never takes quotes, and each field is named once.

A rule can also name the page: [`title_from`](https://legatobar.com/docs/detail-pages.md#titled-by-its-item) reads one against a source's answer for the panel's title row.

Paths are relative to the current JSON value. They support named object fields, dots and zero-based array indexes. They are not full JSONPath expressions or JavaScript: there are no wildcards, recursive searches or executable expressions.

| Response shape | Path or rule |
| --- | --- |
| Nested object | `owner.login` |
| Nested array item | `projects[0].tasks[1].title` |
| First item of a top-level array | `[0].name` |
| Key with spaces or punctuation | `list[0]["Resting HR"]` |
| Entire response, including plain text | `$` |
| List from an array | `{ "each": "projects[0].tasks", "template": "{title}" }` |
| List from a top-level array | `{ "each": "$", "template": "{name}" }` |

Inside `each`, paths are relative to that item and `{$}` means the item itself. Use `owner.login` for a nested field; a leading `$.` is not supported. Field names can contain letters, numbers, underscores and hyphens. Put any other key in quotes and brackets: `list[0]["Resting HR"]` or `["Sleep (h)"]`, for services such as NocoDB and Airtable that name fields the way you title columns. A quoted key can hold spaces, dots and brackets, but not `"`, `\`, `{`, `}` or `|`.

| Rule | Example | Gives |
| --- | --- | --- |
| A path | `"summary.queries.total"` | The value at that path. Paths use dots and `[n]` for array items: `top_blocked.domains[0].domain`. |
| Template | `{ "template": "{summary.clients.active} active clients" }` | Text with `{path}` filled in. A missing value becomes "—". |
| List | `{ "each": "top_blocked.domains", "fields": { "label": "domain", "value": "count" }, "limit": 5 }` | One item per array element, built from `fields` (or one string per element, with `"template"` instead of `fields`, or one list per element, with `"cells"`, for a [table's rows](https://legatobar.com/docs/card-lists.md#table)). Paths inside are relative to the element; `{$}` is the element itself. |
| List of numbers | `{ "each": "data", "where": { "path": "cpu", "gte": 0 }, "value": { "path": "cpu", "scale": 100, "round": 1 }, "buckets": 144 }` | One value per element, from the rule in `value`: a sparkline's `points`. An element the rule gives nothing for is left out, so give the sparkline's `labels` rule the same `where` and `buckets`, and the two stay the same length. `buckets` (2 to 240) keeps at most that many by gathering neighbours into runs of near-equal length: a `value` list averages each run, and a `template` or `fields` list reads its last element. A day of one-minute readings in 144 buckets is one point per 10 minutes. With `"running": true` each number is the total so far, for a month-to-date line; see [Calendar days](https://legatobar.com/docs/mapping-expiry.md#calendar-days). |
| Aggregate | `{ "count": "lights_on" }`, `{ "avg": "monitor_response_time", "of": "monitors" }` | `count` an array, or `sum`, `avg`, `min`, `max`, `first`, `join` or `worst` one field over the array in `of`. `join` takes a `separator` (", " by default). `worst` is the worst state among them: see [Slices of time](https://legatobar.com/docs/mapping-expiry.md#slices-of-time). |
| Condition | `{ "if": { "path": "problems", "equals": 1 }, "then": …, "else": … }` | One rule or the other. Without `else`, nothing when the condition fails. |
| Arithmetic | `{ "add": ["bank_cash", "manual_cash"] }`, `{ "subtract": ["assets", "debts"] }` | `add`, `subtract`, `multiply` or `divide` 2 to 8 sides, each a rule or a number. `subtract` and `divide` go left to right. A side that's missing or not a number, or a division by zero, leaves the result missing, so `default` applies. |
| Month elapsed | `{ "month_elapsed": true }` | How far through this calendar month now is, from 0 to 1: the 24th of a 30-day month is about 0.78. For a pacing card's `elapsed` on a page without a [period](https://legatobar.com/docs/periods.md). |
| Since | `{ "since": "StartedAt" }` | Gives seconds from a moment to now. The input can also be a rule. Reads ISO 8601, Unix seconds or milliseconds. Future moments give negative numbers. Missing or unreadable dates and years before 1970 give no value, so `default` applies. Supports `scale`, `round` and the other adjusters. |
| Expiry | `{ "expires": { "days": "cert_days" }, "warning": 14, "as": "state" }` | A state, words or days for something that expires: see [Expiry](https://legatobar.com/docs/mapping-expiry.md#expiry). |

A list's `each` can also be 2 to 4 paths, joined in order before `where`, `sort` and `limit` apply, for a service that splits one kind of thing across requests. A path among them that holds one object, such as a car's state now, counts as one row, so a story of drives and charges can begin with how the car is now. Lunch Money keeps linked and manual accounts apart; this lists every credit card from both, largest balance first:

```json
{ "each": ["banks.plaid_accounts", "manual.manual_accounts"], "where": { "path": "type", "equals": "credit" },
  "sort": { "by": "to_base", "order": "desc" }, "limit": 20, "fields": { "label": "display_name", "value": "to_base" } }
```

A path with no array in the answer is skipped; with none at all, the card keeps its last value.

Lists and aggregates take the same options for choosing elements:

- `entries`: `true` turns each element that's an object into one row per field, `{ "key", "value" }`, before anything else. See [Names as keys](https://legatobar.com/docs/mapping-tables.md#names-as-keys).
- `lookup`: each element's match in another array, attached as a field before the other options apply. See below.
- `where`: a [condition](https://legatobar.com/docs/mapping-conditions.md#conditions) each element must meet, with paths relative to the element.
- `flatten` and `group`: after `where`, each element's own list in its place, then rows gathered by a value they share. See [Turning a table round](https://legatobar.com/docs/mapping-tables.md#turning-a-table-round).
- `sort`: a path to sort by, or `{ "by": path, "order": "desc" }`. `by` can also be 2 to 4 paths, each breaking the ties of those before it: Todoist's tasks sort by `["section.order_key", "order_key"]`, their section's place and then their own. Rows that tie on every path keep their order.
- `collapse`: after `sort`, a path to a value. A row whose value there is the same as the row kept before it is left out, and so is a row with no value there. Text matches with spaces trimmed and case ignored. Only neighbours count, so scans in Reno, Boise and Reno again keep all three. A map card's [route](https://legatobar.com/docs/card-lists.md#routes) uses it for one stop per place.
- `limit`: how many to keep, from the first.
- `last`: how many to keep, from the end, after `sort` and `collapse`. Use it for the newest rows when they're sorted oldest first. A rule takes `limit` or `last`, not both.

Some services send ids in one answer and the names for them in another. Lunch Money's budget summary lists each category's spending by `category_id`, and its categories request has the names. A `lookup` finds, for each element, the first element of the array in `from` whose `by` field equals the element's `on` field, and attaches it as the field named in `as`:

```json
{ "each": "summary.categories",
  "lookup": { "from": "cats.categories", "by": "id", "on": "category_id", "as": "category" },
  "where": { "path": "category.is_group", "not": true },
  "fields": { "label": { "path": "category.name", "default": "Other" }, "value": "totals.other_activity" } }
```

A renamed category then shows its new name the next time the source answers, with nothing in the page to update. `from` is read from the same place as the array itself: the whole answer for a card's `map` or a derived value. The two ids match as values, so `12` and `"12"` are the same. An element with no match goes without the field, so a `default` applies, and `as` replaces any field the element already had with that name. When `from` is one object rather than an array, it's the only candidate: Mealie's meal plan rows carry a `groupId`, and `"lookup": { "from": "group", "by": "id", "on": "groupId", "as": "group" }` attaches `/api/groups/self` to each, so a row's link can read `group.slug`.

