# Likes

> Let visitors like or rate items on any public page, with counts kept on Hyperclay and no backend of your own.

Source: https://hyperclay.com/docs/likes/

Visitors can react to individual items on a public page, such as liking a post or rating a project, without you running a backend. You declare the items in the page's own rules tag, the page reads the counts from Hyperclay, and a click writes one reaction back. Hyperclay stores the counts, so they survive renaming or moving the page.

The simplest way to like an item is the ClayJS like plugin: one attribute on a button, and the plugin reads the counts, paints them and sends the click.

```html
<button like="post-1">♥</button>
```

Load `?plugins=like` on the ClayJS script tag and it does the rest. Its page has the markup, the events and the API: [ClayJS like plugin](https://clayjs.com/docs/plugins/like/).

## What likes do

A like is one row on Hyperclay, keyed to the page, the item, the action and a visitor id. A page reads the totals for every item it declares with one request, and toggles a single item with another. Nothing about the count lives in the saved HTML, so two people opening the page see the same numbers, and moving the page to another folder keeps them.

The page decides what a visitor can send, and Hyperclay refuses anything the page has not declared. A page that declares nothing has no likes at all.

## Declare the items on the page

Likes are set up in the page's `api` rules tag, under the key `projects`. This example declares every `.entry` inside `#stream` as an item:

```html
<script type="application/json" data-rules-name="api" data-rules-version="1">
{"projects": ["#stream > .entry", {"id": "@data-id", "actions": "@data-actions", "name": ".entry-name"}]}
</script>
```

`projects` is a data extraction list rule, the same syntax as [page data](https://hyperclay.com/docs/page-data/): a selector, then a map from field names to selectors. Each matched element becomes one item, and the map reads fields from it.

- `id` is required. It names the item in every request, must be unique on the page, and can be at most 48 characters; an item with a longer id is left out. `@data-id` reads the element's `data-id` attribute, so the markup keeps the id.
- `name` is optional. It is a label for the item, read from text or an attribute.
- `actions` is optional and defaults to `like`. It holds the actions the item accepts, separated by spaces, so `like share` accepts two. Each action can be at most 48 characters.

An action can accept a set of values. Write it as `rating:1|2|3|4|5`, and a reaction to that action has to carry one of `1`, `2`, `3`, `4` or `5`. The markup for such a page looks like this:

```html
<div id="stream">
  <article class="entry" data-id="post-1" data-actions="like">
    <h2 class="entry-name">First post</h2>
  </article>
  <article class="entry" data-id="post-2" data-actions="like rating:1|2|3|4|5">
    <h2 class="entry-name">Second post</h2>
  </article>
</div>
```

Hyperclay reads the rules tag at most once a minute, and again after five seconds when a request names an item the page has not declared yet. An item you add to the markup starts accepting likes within a few seconds of its first request.

Any element carrying a `like` attribute in the saved page is also an item, with the action `like` and the attribute's value (or the element's `id`) as its id, so the ClayJS like plugin needs no rule at all and the two can sit on the same page.

## Read the counts

`GET /_/reactions` on the page's own host returns the totals for every declared item, plus a form token:

```
curl -H "Document-URL: https://alice.hyperclay.com/posts.html" https://alice.hyperclay.com/_/reactions
```

```json
{ "counts": { "post-1": { "like": 3 }, "post-2": { "like": 1, "rating": { "5": 4, "4": 1 } } },
  "formToken": "..." }
```

Every declared item and action appears, at zero when nobody has reacted, so `counts.post-1.like` is always a number. An action with values appears as an object keyed by value, and a value nobody has chosen is absent. That is why `rating` above lists `5` and `4` and nothing else.

Send the `Document-URL` header with the page's own address, so Hyperclay knows which page is asking when your document sits on a username host.

## Record a reaction

`PUT /_/reactions` turns a reaction on or off for one item and one visitor:

```
curl -X PUT -H "Document-URL: https://alice.hyperclay.com/posts.html" \
  -H "Content-Type: application/json" \
  -d '{"item":"post-1","action":"like","visitor":"9f2c1d4a7b6e8c0d","on":true,"formToken":"..."}' \
  https://alice.hyperclay.com/_/reactions
```

The body has these fields:

- `item` is the item's `id`, and `action` is one of its actions.
- `visitor` is a random id the page makes once and keeps, 16 to 64 characters of `A` to `Z`, `a` to `z`, `0` to `9` and `-`. It is how Hyperclay knows that the same person clicked twice, and it is hashed before it is stored.
- `on` is `true` to add the reaction and `false` to take it away.
- `value` carries the chosen value for an action declared with values, and is required when `on` is `true` and the action has them. Leave it out for a plain `like`.
- `formToken` is the one-time token from the previous response. Only turning a reaction on needs it, and each token works once.

The response carries the new total for that action and a fresh token:

```json
{ "ok": true, "item": "post-1", "action": "like", "on": true, "count": 4, "formToken": "..." }
```

Keep the returned `formToken` for the next request, and read the counts again after a page reload. Toggling is idempotent per visitor: a visitor who likes an item twice still counts once.

## A complete client script

This page declares its items, adds a button to each, keeps one visitor id in `localStorage`, and toggles a like. It is plain `fetch` with no library.

```html
<script type="application/json" data-rules-name="api" data-rules-version="1">
{"projects": ["#posts > li", {"id": "@data-id"}]}
</script>
<ul id="posts">
  <li data-id="post-1">First post</li>
  <li data-id="post-2">Second post</li>
</ul>
<script>
  const visitor = (() => {
    try {
      const saved = localStorage.getItem('likes-visitor');
      if (saved) return saved;
    } catch (error) {}
    const id = Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
    try { localStorage.setItem('likes-visitor', id); } catch (error) {}
    return id;
  })();
  let counts = {};
  let formToken = null;

  async function request(url, options = {}) {
    const response = await fetch(url, {
      ...options,
      cache: 'no-store',
      headers: { 'Content-Type': 'application/json', 'Document-URL': location.href },
    });
    const result = await response.json().catch(() => ({}));
    if (typeof result.formToken === 'string') formToken = result.formToken;
    if (!response.ok) throw new Error(result.error || 'That did not work.');
    return result;
  }

  function paint(element, button) {
    const total = counts[element.dataset.id].like;
    button.textContent = `${button.dataset.liked === 'true' ? 'Liked' : 'Like'} (${total})`;
  }

  document.querySelectorAll('[data-id]').forEach(element => {
    const button = document.createElement('button');
    button.dataset.liked = 'false';
    button.addEventListener('click', async () => {
      const on = button.dataset.liked !== 'true';
      const result = await request('/_/reactions', {
        method: 'PUT',
        body: JSON.stringify({ item: element.dataset.id, action: 'like', visitor, on, formToken }),
      }).catch(error => alert(error.message));
      if (!result) return;
      button.dataset.liked = String(on);
      counts[element.dataset.id].like = result.count;
      paint(element, button);
    });
    element.append(' ', button);
  });

  request('/_/reactions').then(result => {
    counts = result.counts;
    document.querySelectorAll('[data-id]').forEach(element => paint(element, element.querySelector('button')));
  }).catch(() => {});
</script>
```

The script sends `Document-URL` on both requests, the same header the ClayJS message plugin sends, so a page served from a username host resolves to the right document.

## Errors and limits

Failures come back as JSON with `ok: false`, a `code`, an `error` message, and a fresh `formToken`.

- **`unknown-site`**: the page has no `projects` rule in its `api` rules tag, or none of its items is valid. Answers 404. A private page answers with the same plain 404 as a page that does not exist.
- **`unknown-item`**: the item is not declared by this page, or was removed from the markup. Answers 404.
- **`unknown-action`**: the item does not accept that action. Answers 404.
- **`invalid`**: `item` or `action` is missing, the visitor id is the wrong length or holds the wrong characters, `on` is not a boolean, or `value` is missing, too long or not one of the declared values. Answers 400.
- **`form-token`**: turning a reaction on arrived without a usable one-time token. Answers 400, and the response carries a fresh token to retry with.
- **Rate limits**: one connection can send 300 reactions an hour before it is locked out for the rest of the hour with `That's too many requests at once. Give it a little while and try again.` A connection can also turn on a given item and action for at most 5 different visitors a day, and reactions from further new visitors are dropped while the request still answers `ok`, so a shared connection cannot inflate a count.
- **`unavailable`**: Hyperclay could not read the page or reach its database. Answers 503, and the same request works again later.

Reading the counts is free of the write limit, so a page can poll `GET /_/reactions` to stay current.

## Likes are hosted only

Counts live on Hyperclay, keyed to the page. A page opened as a local file in HTML Clay, or downloaded with [Import and export](https://hyperclay.com/docs/import-export/), has no `/_/reactions` to talk to and shows no likes. Publish the page on Hyperclay to use them, on any plan.

A private page has no likes either. It answers with the same plain 404 as a page that does not exist, so a request never reveals whether it declares items.
