{# This page is opened whenever the surfer opens a new tab, thus indicating they want to go somewhere.

As such I provide some links to places they might likely be trying to go (depicted as recognizable screenshots),
and I take advantage of this page to promote project links. #}

<!DOCTYPE html>

{# Ensure the appropriate recommendations are downloaded. #}
{% query %}BEGIN TRANSACTION;{% endquery %}
{% query %}SELECT * FROM recommendations;
{% empty %}
  {% fetch %}
    {% if distro.ID %}
      http://recommendations.adrian.geek.nz/links/{{ distro.ID }}.tsv
    {% endif %}
    {% for distro in distro.ID_LIKE|split:" " %}
      http://recommendations.adrian.geek.nz/links/{{ distro }}.tsv
    {% endfor %}
    {% for lang in LOCALE %}
      http://recommendations.adrian.geek.nz/links/{{ lang }}.tsv
    {% endfor %}
  {% each as links %}
    {% for section in links %}{% for link in section %}
      {% query %}
        INSERT OR IGNORE INTO recommendations(uri, weight) VALUES ({{ link }}, 1.0/{{ section|length }});
      {% endquery %}
    {% endfor %}{% endfor %}
  {% endfetch %}
{% endquery %}

{# Update the visit_counts index. This can take a little bit but not so much it is noticable.
    Formulating it this way regularly gives control back to the GLib MainLoop,
    such that the application remains responsive.
    i.e. SQLite can freeze Odysseus, but Prosody cannot. #}
{# visit_counts is a special index, akin to a materialized view, that optimizes
    selecting/ordering pages based on number of visits. #}
{% query %}SELECT uri, COUNT(*) AS count FROM page_visit GROUP BY uri;
{% except %}SELECT * FROM visit_counts WHERE url = {{ uri }} AND count = {{ count }};
{% each-row %}
  <!-- Indexing {{ uri }} -->
  {% query %}INSERT OR REPLACE INTO visit_counts(url, count)
        VALUES ({{ uri }}, {{ count }});{% endquery %}
{% endquery %}
{% query %}END TRANSACTION;{% endquery %}

<html>
<head>
  <title>[user-home] {% trans %}New Tab{% endtrans %}</title>
  <style>
    @import url(odysseus:butterick.css);
    main {text-align: center;}
    main hr {border: none; border-bottom: thin solid; }
    footer {position: fixed; bottom: 0; background: #fffa;}

    main {width: auto; max-width: 800px;/* Fits 5 128px thumbnails + spacing */}
    main nav {width: auto;}
    main nav img {box-shadow: 2px 2px 2px; margin: 5px;}
    main nav img:hover {box-shadow: 4px 4px 4px;}

    /* Styling for the different link sources */
    .suggestion > a {color: #666; text-decoration: none; font-size: 132px; text-align: center;}
    .pinned img {color: #64baff;}
    .pinned form:first-of-type * {display: none;}
    .history img {color: #666;}
    .recommendation img {color: #9bdb4d;}

    /* Fixes for HTML5Sortable to work in the context of the topsites list. */
    .sortable-placeholder {display: inline-block; width: 132px;}
  </style>
</head>
<body>
  <main><nav>
    {% macro q-tailrank %}(SELECT COUNT(*) FROM topsites_whitelist
        WHERE uri NOT IN (SELECT uri FROM topsites_blacklist))
      AS order_
    {% endmacro %}
    {% query 20 %}
      SELECT uri, 0 as order_, "suggestion" AS cat,
          {{"Several sites recommended this link."|trans}} AS help,
          {{"<a href='odysseus:suggestions'>Suggested For You</a>"}} AS caption
        FROM unvisited_links
        WHERE uri NOT IN (SELECT uri FROM page_visit)
        ORDER BY endorsements*random() DESC LIMIT 1;
      SELECT uri, order_, "pinned" AS cat,
          {{"You 'pinned' this here"|trans}} AS help, {{"Pinned"|trans}} AS caption
        FROM topsites_whitelist ORDER BY order_ ASC;
      SELECT url as uri, {% q-tailrank %}, "history" AS cat,
          {{"Frequently visited"|trans}} AS help,
          {{"<a href='odysseus:history'>History</a>"|trans}} AS caption
        FROM visit_counts
        WHERE count >= 10 AND uri NOT IN (SELECT uri FROM topsites_whitelist)
        ORDER BY count DESC;
      SELECT uri, {% q-tailrank %}, "recommendation" AS cat,
          {{"Recommended by Adrian Cochrane"|trans}} AS help, {{"Recommended"|trans}} AS caption
        FROM recommendations
        WHERE uri NOT IN (SELECT uri FROM page_visit) -- Only recommend new links.
        ORDER BY random() * weight;
    {% except %}
      SELECT 1 WHERE {{ uri }} NOT IN (SELECT uri FROM topsites_blacklist);
    {% each-row %}
      <figure class="{{ cat }}" tooltip="{{ cat }}">
        <a href="{{ uri }}" title="{{ help }}
{{ uri }}">
          {% if cat in "suggestion" %}?{% else %}
          <img style="width: 132px; height: 132px;"
                {% query %}SELECT image FROM screenshot_v2 WHERE uri = {{ uri }};
                {% each-row %}
                  src="data:image/png;base64,{{ image }}"
                {% empty %}{# Custom URI scheme that caches the HTTP responses in this table. #}
                  src="odysseusproxy:///{{ uri }}"
                {% endquery %}
                height="128" width="128" />{% endif %}
        </a>
        <legend>
          <form method="POST"><input aria-hidden name="$" value="topsites_whitelist" />
            <input aria-hidden name="uri" value="{{ uri }}" />
            <input type="number" name="order_" value="{{ order_ }}" />
            <button type="submit" title="Keep this link on this page.">&check;</button>
          </form>
          {{ caption|safe }}
          <form method="POST"><input aria-hidden name="$" value="topsites_blacklist" />
            <input aria-hidden name="uri" value="{{ uri }}" />
            <button type="submit" title="Remove this link from this page.">x</button>
          </form>
        </legend>
      </figure>
    {% endquery %}
  </nav></main>

  <script src="odysseus:ext/html5sortable.js"></script>
  <script>
    sortable('nav')[0].addEventListener('sortupdate', (e) => {
      /* This code submits the appropriate form to save the new order. */
      var data = e.detail.destination,
        $ = (el) => el.querySelector('[name=order_]'),
        _ = (offset) =>
          $(data.items[Math.min(data.index + offset, data.items.length)])

      if (data.index == 0) _(0).value = $(data.items[0]).value - 1;
      else _(0).value = +_(1).value + (+_(1).value - +_(-1).value)/2

      _(0).form.submit();
    })

    // As poor progressive enhancement, remove extraneous controls only once they're extraneous.
    for (var el of document.querySelectorAll('[name=order_]'))
      el.setAttribute('aria-hidden', true)
  </script>

  <footer>{% random %}{% alt %}
      {% trans %}Browse faster with
        <a href="https://alcinnz.github.io/Odysseus-support/guides/keyboard-shortcuts.html">
          keyboard shortcuts</a>!{% endtrans %}
    {% alt %}
      {% trans %}{# Translators: Use this entry to sell your translation project! #}
        Do you know another language? Then do your friends a favour and
        <a href="https://www.transifex.com/none-483/odysseus/dashboard/">teach Odysseus it</a>!{% endtrans %}
    {% alt %}
      {% trans %}Don't know where to go? Here's some
        <a href="https://alcinnz.github.io/Odysseus-recommendations/">recommendations</a>.{% endtrans %}
    {% alt %}
      {% trans %}Want to help
        <a href="https://github.com/alcinnz/Odysseus-support/wiki/Get-Involved!">make Odysseus more awesome</a>?{% endtrans %}
    {% alt %}
      {% trans %}Got questions? Have them <a href="https://alcinnz.github.io/Odysseus-support/">answered</a>.{% endtrans %}
    {% alt %}
      <p>{% trans %}Designed and coded with <a href="odysseus:credits">help</a>
        & ♥ by <a href="https://adrian.geek.nz/">Adrian Lyall Cochrane</a> in NZ.{% endtrans %}<p>
    {% alt %}
      {% trans %}History search not powerful enough for you?
        I <a href="https://alcinnz.github.io/Odysseus-support/guides/how-to-view-history.html">doubt it</a>!{% endtrans %}
    {% alt %}
      {% trans %}While Odysseus does store information about your browsing,
        that <a href="odysseus:privacy">doesn't mean</a> we share it with anyone but you.{% endtrans %}
    {% alt %}
      {% trans %}FYI: None of the links on this page were sponsered, no one paid for any of them.{% endtrans %}
  {% alt %}{% endrandom %}</footer>
</body>
</html>
