Observações
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
<!--
Sightings: the field log's own screen (docs/device-ui/README.md), a nature journal for birds,
butterflies and whatever else crosses the path. One file, served by the device at /.cz/ui.html. It
talks to its device with nothing but fetch("/…"): in the Connectivitizer app those requests go
through the app's end-to-end encrypted session; opened straight from the device's web server
(http://127.0.0.1:<port>/.cz/ui.html) they are ordinary requests.
One composer uses every phone feature a device page may ask for, each from its own button and with a
sentence that says what it is for: the camera (a live viewfinder), a photo from the phone's own camera
or gallery, the microphone (a voice note), the location, and links that open outside the app. Each
refusal is answered with the place in the app where it can be turned on.
Text from the device (species, notes) is only ever shown with textContent, never as HTML.
-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<title>Sightings</title>
<style>
:root {
--bg: #f3efe3; --card: #fffcf4; --ink: #23261d; --muted: #5f6450; --line: #ddd5c0; --wash: #e4ead3;
--moss: #3d6b3a; --on-moss: #ffffff; --moss-soft: #e5eddc; --sun: #9a5416; --sun-soft: #f6e6cf;
--bad: #a3321f; --hint-bg: #f8edd4; --hint-line: #e6d0a0; --rec: #c2361f; --finder: #20251c;
--shadow: 0 1px 2px rgb(50 45 20 / 0.06), 0 6px 20px rgb(50 45 20 / 0.06);
--serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #141813; --card: #1d221b; --ink: #ebe7d8; --muted: #a9a894; --line: #333a30; --wash: #1b2419;
--moss: #8fc48a; --on-moss: #10190f; --moss-soft: #243022; --sun: #e3a35f; --sun-soft: #342a1c;
--bad: #f19a86; --hint-bg: #2c2819; --hint-line: #4f4528; --rec: #ff7a62; --finder: #0c0f0b; --shadow: none;
}
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body { margin: 0; background: var(--bg) linear-gradient(180deg, var(--wash), transparent 320px) no-repeat; color: var(--ink); font: 16px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
main { max-width: 600px; margin: 0 auto; padding: 18px 16px calc(28px + env(safe-area-inset-bottom)); display: grid; gap: 18px; }
h1, h2, h3, h4 { margin: 0; font-family: var(--serif); font-weight: 600; letter-spacing: -0.01em; }
h1 { font-size: 34px; line-height: 1.05; }
h2 { font-size: 21px; }
p { margin: 0; }
.muted { color: var(--muted); }
.small { font-size: 13px; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); margin-bottom: 6px; }
.intro { margin-top: 6px; color: var(--muted); font-size: 15px; }
.tally { display: grid; grid-template-columns: repeat(3, 1fr); margin: 14px 0 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.tally div { padding: 8px 4px; text-align: center; }
.tally div + div { border-left: 1px solid var(--line); }
.tally dt { font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }
.tally dd { margin: 0; font: 600 24px/1.1 var(--serif); font-variant-numeric: tabular-nums; }
svg.i { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 20px; box-shadow: var(--shadow); }
.composer { padding: 14px; display: grid; gap: 12px; }
.composer-head { display: flex; justify-content: space-between; align-items: baseline; padding: 2px 2px 0; }
/* The viewfinder: an empty frame, the live camera or the photo. */
.finder { position: relative; aspect-ratio: 4 / 3; border-radius: 14px; overflow: hidden; background: var(--moss-soft); border: 1px dashed color-mix(in srgb, var(--moss) 40%, transparent); }
.finder[data-state="live"], .finder[data-state="photo"] { background: var(--finder); border-style: solid; border-color: transparent; }
.finder video, .finder > img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; display: none; }
.finder[data-state="live"] video, .finder[data-state="photo"] > img { display: block; }
.finder-empty { position: absolute; inset: 0 0 56px; display: grid; place-content: center; justify-items: center; gap: 8px; padding: 12px 20px; text-align: center; color: var(--muted); font-size: 14px; }
.finder-empty svg { width: 108px; height: 64px; color: var(--moss); opacity: 0.85; }
.finder:not([data-state="empty"]) .finder-empty { display: none; }
.corners { position: absolute; inset: 14px; pointer-events: none; display: none; background:
linear-gradient(#fff, #fff) left top / 22px 2px, linear-gradient(#fff, #fff) left top / 2px 22px,
linear-gradient(#fff, #fff) right top / 22px 2px, linear-gradient(#fff, #fff) right top / 2px 22px,
linear-gradient(#fff, #fff) left bottom / 22px 2px, linear-gradient(#fff, #fff) left bottom / 2px 22px,
linear-gradient(#fff, #fff) right bottom / 22px 2px, linear-gradient(#fff, #fff) right bottom / 2px 22px; background-repeat: no-repeat; opacity: 0.8; }
.finder[data-state="live"] .corners { display: block; }
.tools { position: absolute; left: 0; right: 0; bottom: 0; display: flex; gap: 8px; align-items: center; padding: 10px; }
.finder:not([data-state="empty"]) .tools { background: linear-gradient(transparent, rgb(0 0 0 / 0.55)); }
.finder[data-state="live"] .tools.still, .finder:not([data-state="live"]) .tools.live { display: none; }
.tools.live { justify-content: center; padding-bottom: 14px; }
.ftool { font: inherit; font-size: 14px; font-weight: 600; min-height: 44px; padding: 0 14px; border-radius: 999px; border: 0; display: inline-flex; align-items: center; gap: 7px; cursor: pointer; background: var(--card); color: var(--moss); box-shadow: 0 1px 3px rgb(0 0 0 / 0.15); position: relative; }
.finder:not([data-state="empty"]) .ftool { background: rgb(20 24 18 / 0.72); color: #fff; box-shadow: none; }
.ftool input { position: absolute; inset: 0; opacity: 0; width: 100%; cursor: pointer; }
.ftool { white-space: nowrap; }
.finder[data-state="photo"] .ftool { width: 44px; padding: 0; justify-content: center; }
.finder[data-state="photo"] .lbl { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.ftool.icon-only { padding: 0; width: 44px; justify-content: center; margin-left: auto; }
.tools.live .ftool { position: absolute; left: 12px; bottom: 20px; }
.shutter { width: 68px; height: 68px; border-radius: 50%; border: 4px solid #fff; background: rgb(255 255 255 / 0.28); cursor: pointer; padding: 0; box-shadow: inset 0 0 0 4px rgb(0 0 0 / 0.25); }
.shutter:active { background: #fff; }
.finder-size { position: absolute; top: 10px; left: 10px; font-size: 12px; color: #fff; background: rgb(0 0 0 / 0.45); padding: 3px 8px; border-radius: 999px; }
.finder-size:empty, .finder:not([data-state="photo"]) .finder-size { display: none; }
.fields { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: end; }
.field { display: grid; gap: 5px; font-size: 13px; font-weight: 600; color: var(--muted); min-width: 0; }
input[type="text"], input[type="number"], textarea { font: inherit; font-size: 16px; color: var(--ink); background: var(--bg); border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; width: 100%; min-height: 46px; }
#species, .edit .sp { font-family: var(--serif); font-size: 18px; font-weight: 600; }
textarea { min-height: 72px; resize: vertical; }
.stepper { display: flex; align-items: stretch; border: 1px solid var(--line); border-radius: 12px; background: var(--bg); overflow: hidden; }
.stepper button { width: 40px; min-height: 46px; border: 0; background: transparent; color: var(--moss); font: 600 22px/1 system-ui, sans-serif; cursor: pointer; }
.stepper input { width: 52px; border: 0; border-radius: 0; text-align: center; padding: 0; font-weight: 650; font-variant-numeric: tabular-nums; -moz-appearance: textfield; appearance: textfield; background: transparent; }
.stepper input::-webkit-inner-spin-button, .stepper input::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
.counter { justify-self: end; font-weight: 400; font-size: 12px; }
:focus-visible { outline: 3px solid color-mix(in srgb, var(--moss) 50%, transparent); outline-offset: 2px; }
.ftool:focus-within { outline: 3px solid color-mix(in srgb, var(--moss) 60%, #fff); }
.stepper input:focus-visible, .stepper button:focus-visible { outline-offset: -3px; }
/* What else goes with the sighting: chips that show their state. */
.attach { display: flex; flex-wrap: wrap; gap: 8px; }
.chip, .pill { font: inherit; font-size: 14px; font-weight: 600; min-height: 44px; border-radius: 999px; display: inline-flex; align-items: center; gap: 8px; padding: 0 14px; border: 1px solid var(--line); background: var(--bg); color: var(--ink); cursor: pointer; text-decoration: none; max-width: 100%; }
.chip .i { color: var(--moss); }
.chip.on { background: var(--moss-soft); border-color: transparent; cursor: default; padding-right: 4px; }
.chip.rec { border-color: var(--rec); color: var(--rec); }
.chip.rec .i { color: var(--rec); }
.dot { width: 10px; height: 10px; border-radius: 50%; background: var(--rec); animation: pulse 1s ease-in-out infinite; }
@keyframes pulse { 50% { opacity: 0.3; } }
.meter { display: inline-flex; gap: 2px; align-items: center; height: 18px; }
.meter span { width: 3px; border-radius: 2px; background: currentColor; opacity: 0.8; }
.x { width: 36px; height: 36px; border-radius: 50%; border: 0; background: transparent; color: var(--muted); font-size: 20px; line-height: 1; cursor: pointer; flex: none; }
.uses { font-size: 13px; color: var(--muted); }
.save-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
button.primary { font: inherit; font-weight: 650; font-size: 16px; min-height: 48px; padding: 0 22px; border-radius: 999px; border: 0; background: var(--moss); color: var(--on-moss); cursor: pointer; display: inline-flex; align-items: center; gap: 8px; }
button:disabled { opacity: 0.55; cursor: default; }
/* A voice note: play, a waveform that fills as it plays, the time. */
.voice { display: inline-flex; align-items: center; gap: 8px; min-height: 40px; padding: 0 12px 0 4px; border-radius: 999px; background: var(--sun-soft); color: var(--sun); min-width: 0; }
.voice .play { width: 34px; height: 34px; border-radius: 50%; border: 0; background: var(--sun); color: var(--card); display: grid; place-items: center; cursor: pointer; flex: none; }
.voice .play .i { width: 16px; height: 16px; fill: currentColor; stroke: none; }
.wave { display: inline-flex; align-items: center; gap: 2px; height: 22px; }
.wave span { width: 3px; border-radius: 2px; background: currentColor; opacity: 0.35; }
.wave span.on { opacity: 1; }
.voice .t { font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; }
.hint { background: var(--hint-bg); border: 1px solid var(--hint-line); border-radius: 12px; padding: 10px 12px; font-size: 14px; }
.hint .settings-link { margin-top: 8px; font: inherit; font-weight: 650; font-size: 14px; min-height: 40px; padding: 0 14px; border-radius: 999px; border: 1px solid var(--moss); background: transparent; color: var(--moss); cursor: pointer; }
.toast { position: fixed; left: 16px; right: 16px; bottom: calc(16px + env(safe-area-inset-bottom)); max-width: 568px; margin: 0 auto; box-shadow: 0 8px 28px rgb(0 0 0 / 0.18); z-index: 5; }
.problem { color: var(--bad); font-size: 14px; }
.saved { color: var(--moss); font-size: 14px; font-weight: 600; }
/* The journal: days, and a trail of sightings along each. */
.journal { display: grid; gap: 10px; }
.journal-head { display: flex; justify-content: space-between; align-items: baseline; padding: 0 2px; }
.day { display: grid; gap: 10px; }
.day h3 { font-size: 17px; font-style: italic; display: flex; align-items: baseline; gap: 10px; padding: 6px 2px 0; }
.day h3 span { font: 13px system-ui, sans-serif; color: var(--muted); font-style: normal; }
.trail { list-style: none; margin: 0; padding: 0 0 0 20px; display: grid; gap: 14px; position: relative; }
.trail::before { content: ""; position: absolute; left: 6px; top: 8px; bottom: 8px; border-left: 2px dotted color-mix(in srgb, var(--moss) 45%, transparent); }
.entry { position: relative; }
.entry::before { content: ""; position: absolute; left: -20px; top: 18px; width: 10px; height: 10px; border-radius: 50%; background: var(--card); border: 2px solid var(--moss); }
.sighting { overflow: visible; }
.sighting .photo { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; border-radius: 19px 19px 0 0; background: var(--finder); }
.s-body { padding: 12px 12px 14px 14px; display: grid; gap: 10px; }
.s-head { display: flex; gap: 10px; align-items: flex-start; }
.badge { width: 42px; height: 42px; border-radius: 12px; display: grid; place-items: center; background: var(--moss-soft); color: var(--moss); flex: none; }
.badge.butterfly { background: var(--sun-soft); color: var(--sun); }
.badge .i { width: 24px; height: 24px; }
.s-title { flex: 1; min-width: 0; }
.s-title h4 { font-size: 19px; line-height: 1.2; overflow-wrap: anywhere; }
.s-title h4.unnamed { font-style: italic; color: var(--muted); font-weight: 500; }
.s-title .n { color: var(--sun); font-family: system-ui, sans-serif; font-size: 15px; font-weight: 700; margin-left: 4px; }
.s-title time { font-size: 13px; color: var(--muted); font-variant-numeric: tabular-nums; }
.tag { font-size: 11px; font-weight: 700; color: var(--sun); text-transform: uppercase; letter-spacing: 0.06em; margin-left: 8px; }
.note { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 15px; }
.s-meta { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
a { color: var(--moss); font-weight: 600; text-underline-offset: 3px; }
a.chip { color: var(--moss); min-height: 40px; font-size: 13px; }
a.chip .acc { color: var(--muted); font-weight: 500; }
.menu { position: relative; flex: none; }
.menu summary { list-style: none; width: 40px; height: 40px; border-radius: 50%; display: grid; place-items: center; cursor: pointer; color: var(--muted); margin: -4px -4px 0 0; }
.menu summary::-webkit-details-marker { display: none; }
.menu[open] summary { background: var(--moss-soft); color: var(--moss); }
.menu-list { position: absolute; right: 0; top: 40px; z-index: 3; min-width: 196px; padding: 6px; display: grid; background: var(--card); border: 1px solid var(--line); border-radius: 14px; box-shadow: 0 10px 30px rgb(0 0 0 / 0.16); }
.menu-list > * { font: inherit; font-size: 15px; font-weight: 500; text-align: left; min-height: 44px; padding: 0 12px; border: 0; border-radius: 10px; background: transparent; color: var(--ink); display: flex; align-items: center; gap: 10px; cursor: pointer; text-decoration: none; }
.menu-list > :hover { background: var(--bg); }
.menu-list .danger { color: var(--bad); }
.edit { display: grid; gap: 10px; }
.edit textarea { min-height: 104px; }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
button.quiet { font: inherit; font-weight: 600; min-height: 44px; padding: 0 16px; border-radius: 999px; border: 1px solid var(--line); background: transparent; color: var(--ink); cursor: pointer; }
.empty { text-align: center; padding: 26px 12px; color: var(--muted); border: 1px dashed var(--line); border-radius: 16px; }
footer { display: grid; gap: 10px; padding: 14px 4px 0; border-top: 1px solid var(--line); font-size: 13px; }
footer nav { display: flex; flex-wrap: wrap; gap: 4px 18px; }
footer nav a { display: inline-flex; align-items: center; min-height: 44px; font-size: 14px; }
[hidden] { display: none !important; }
@media (prefers-reduced-motion: reduce) { .dot { animation: none; } * { scroll-behavior: auto !important; transition: none !important; } }
@media (min-width: 420px) { h1 { font-size: 38px; } }
</style>
</head>
<body>
<main>
<header>
<p class="eyebrow" id="where">Connecting…</p>
<h1>Sightings</h1>
<p class="intro">A field journal for birds, butterflies and whatever else crosses your path. Each sighting is kept on this device.</p>
<dl class="tally" aria-label="Kept on the device">
<div><dt>Sightings</dt><dd id="tally-entries">–</dd></div>
<div><dt>Species</dt><dd id="tally-species">–</dd></div>
<div><dt>Individuals</dt><dd id="tally-count">–</dd></div>
</dl>
</header>
<section class="card composer" aria-labelledby="new-title">
<div class="composer-head"><h2 id="new-title">New sighting</h2><span class="muted small" id="now"></span></div>
<!-- The camera (a live viewfinder, getUserMedia) and a photo from the phone's own camera or gallery. -->
<div class="finder" id="finder" data-state="empty">
<div class="finder-empty" id="camera-start-row">
<svg viewBox="0 0 108 64" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 44c6 0 11-3 14-9l5-10a8 8 0 0 1 15 3l6 2-6 3c0 11-8 18-21 18H8l8-7z"/><circle cx="35" cy="27" r="1" fill="currentColor"/><path d="M28 44l-3 8M34 43l-1 9"/><path d="M80 22v22M80 25c-4-9-17-13-17-4 0 6 7 8 17 8M80 25c4-9 17-13 17-4 0 6-7 8-17 8M80 31c-6 0-13 2-13 8 0 4 7 4 13-5M80 31c6 0 13 2 13 8 0 4-7 4-13-5M80 22l-4-7M80 22l4-7"/><path d="M2 60h104" stroke-dasharray="2 5"/></svg>
<p><b>Live camera</b> shows a preview right here; <b>Take or choose</b> opens your phone's own camera or gallery. Or skip the photo.</p>
</div>
<video id="camera-video" playsinline muted aria-label="Camera preview"></video>
<img id="photo-preview" alt="The photo for this sighting">
<span class="corners" aria-hidden="true"></span>
<span class="finder-size" id="photo-size"></span>
<div class="tools still">
<button type="button" class="ftool" id="camera-open"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/></svg><span class="lbl">Live camera</span></button>
<label class="ftool" id="picker-label"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="2"/><path d="m21 16-5-5-9 9"/></svg><span class="lbl">Take or choose</span><input type="file" id="photo-file" accept="image/*" capture="environment" aria-label="Take or choose a photo"></label>
<button type="button" class="ftool icon-only" id="photo-remove" aria-label="Remove photo" hidden><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13"/></svg></button>
</div>
<div class="tools live" id="camera-live">
<button type="button" class="ftool" id="camera-cancel">Cancel</button>
<button type="button" class="shutter" id="camera-capture" aria-label="Capture"></button>
</div>
</div>
<p class="hint" id="camera-hint" role="status" hidden></p>
<p class="hint" id="picker-hint" role="status" hidden></p>
<div class="fields">
<label class="field">Species
<input type="text" id="species" list="species-list" maxlength="80" autocomplete="off" autocapitalize="sentences" placeholder="Robin, Peacock…">
</label>
<div class="field"><span id="count-label">Count</span>
<div class="stepper"><button type="button" id="count-down" aria-label="One fewer">−</button><input type="number" id="count" inputmode="numeric" min="1" max="999" value="1" aria-labelledby="count-label"><button type="button" id="count-up" aria-label="One more">+</button></div>
</div>
</div>
<datalist id="species-list"></datalist>
<label class="field">Note
<textarea id="note" maxlength="1000" placeholder="What it was doing, the weather, what it fed on…"></textarea>
<span class="muted counter" id="counter">0 / 1000</span>
</label>
<!-- The microphone (a voice note, getUserMedia + MediaRecorder) and the location, once. -->
<div class="attach" role="group" aria-label="Add to this sighting">
<button type="button" class="chip" id="mic-record"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/></svg>Voice note</button>
<button type="button" class="chip rec" id="mic-stop" hidden><span class="dot" aria-hidden="true"></span><span id="mic-stop-text">Stop</span><span class="meter" id="mic-meter" aria-hidden="true"></span></button>
<span class="chip on" id="audio-attached" hidden><span id="audio-slot"></span><button type="button" class="x" id="audio-remove" aria-label="Remove voice note">×</button></span>
<button type="button" class="chip" id="location-add"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z"/><circle cx="12" cy="9.5" r="2.5"/></svg><span id="location-add-text">Location</span></button>
<span class="chip on" id="location-attached" hidden><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z"/><circle cx="12" cy="9.5" r="2.5"/></svg><span id="location-text"></span><button type="button" class="x" id="location-remove" aria-label="Remove location">×</button></span>
</div>
<p class="hint" id="mic-hint" role="status" hidden></p>
<p class="hint" id="location-hint" role="status" hidden></p>
<p class="uses"><b>Voice note</b> records up to 15 seconds with the microphone, to listen to before you save. <b>Location</b> notes where you are, once, for a map link.</p>
<div class="save-row">
<button type="button" class="primary" id="save">Save sighting</button>
<span id="save-status" role="status"></span>
</div>
</section>
<section class="journal" aria-labelledby="entries-title">
<div class="journal-head"><h2 id="entries-title">Journal</h2><span class="muted small" id="entries-count"></span></div>
<p class="problem" id="list-problem" hidden></p>
<div id="entries"></div>
<p class="empty" id="entries-empty" hidden>No sightings yet. Add the first one above and press <em>Save sighting</em>.</p>
</section>
<footer>
<nav aria-label="Links">
<a id="guide-link" href="https://connectivitizer.com/docs/guides/mobile-app" target="_blank" rel="noopener noreferrer">How device screens work ↗</a>
<a href="mailto:?subject=Sightings" target="_blank" rel="noopener noreferrer">Write an email ✉</a>
</nav>
<p class="muted">Links open outside this screen, in your browser or mail app, after the Connectivitizer app has asked you. Each sighting with a location has an <em>Open in map</em> link, and its <em>⋯</em> menu can email it.</p>
<p class="muted" id="limits">Kept in the device's memory only.</p>
</footer>
<p class="hint toast" id="links-hint" role="status" hidden></p>
</main>
<script>
"use strict";
const $ = (id) => document.getElementById(id);
// In the Connectivitizer app (and in `cz ui`) there is window.connectivitizer; in the app the
// phone features are behind the switches under Account › Security.
const inApp = Boolean(window.connectivitizer && window.connectivitizer.host && window.connectivitizer.host.name === "Connectivitizer" && window.connectivitizer.host.platform !== "desktop");
const SWITCH = {
camera: "To use the camera here, turn on 'Device pages may ask for the camera' under Account › Security in the Connectivitizer app.",
microphone: "To record a voice note here, turn on 'Device pages may ask for the microphone' under Account › Security in the Connectivitizer app.",
location: "To add your location here, turn on 'Device pages may ask for your location' under Account › Security in the Connectivitizer app.",
links: "To open links from here, turn on 'Device pages may open links' under Account › Security in the Connectivitizer app.",
};
const BROWSER = {
camera: "The browser did not allow the camera. Allow it for this page in the browser's site settings and try again. (In the Connectivitizer app: " + SWITCH.camera + ")",
microphone: "The browser did not allow the microphone. Allow it for this page in the browser's site settings and try again. (In the Connectivitizer app: " + SWITCH.microphone + ")",
location: "The browser did not allow the location. Allow it for this page in the browser's site settings and try again. (In the Connectivitizer app: " + SWITCH.location + ")",
};
const refused = (what) => (inApp ? SWITCH[what] : BROWSER[what]);
let limits = { maxEntries: 30, maxNoteChars: 1000, maxSpeciesChars: 80, maxCount: 999, maxPhotoBytes: 1500000, maxAudioBytes: 1000000, keepHours: 24 };
const MAX_SECONDS = 15;
const MAX_PHOTO_EDGE = 1600;
// A few common names for the species field; anything else can be typed.
const BIRDS = ["Robin", "Blackbird", "Blue tit", "Great tit", "Goldfinch", "Chaffinch", "House sparrow", "Starling", "Wren", "Song thrush", "Barn swallow", "Magpie", "Woodpigeon", "Great spotted woodpecker", "Kingfisher", "Grey heron", "Buzzard", "Kestrel"];
const BUTTERFLIES = ["Swallowtail", "Peacock", "Red admiral", "Small tortoiseshell", "Brimstone", "Orange-tip", "Common blue", "Painted lady", "Comma", "Meadow brown", "Small white", "Large white"];
$("species-list").append(...BIRDS.concat(BUTTERFLIES).map((name) => Object.assign(document.createElement("option"), { value: name })));
const lower = (list) => list.map((name) => name.toLowerCase());
const BIRD_SET = new Set(lower(BIRDS));
const BUTTERFLY_SET = new Set(lower(BUTTERFLIES));
function kindOf(species) {
const name = String(species || "").toLowerCase();
if (BUTTERFLY_SET.has(name) || /butterfly|moth|\bwhite\b|blue$/.test(name)) return "butterfly";
if (BIRD_SET.has(name) || /bird|tit$|finch|sparrow|thrush|warbler|owl|hawk|gull|duck|swan|heron|pigeon|dove|crow|woodpecker/.test(name)) return "bird";
return "other";
}
/** What the next sighting gets. */
const draft = { photo: null, photoUrl: null, audio: null, location: null };
// In the app, a hint that points to Account › Security gets a button that opens it
// (connectivitizer.openSettings(), which the app follows right after a tap).
const canOpenSettings = inApp && typeof window.connectivitizer.openSettings === "function";
function say(id, text) {
const node = $(id);
node.textContent = text || "";
node.hidden = !text;
if (text && canOpenSettings && text.indexOf("Account › Security") >= 0) {
const button = document.createElement("button");
button.type = "button";
button.className = "settings-link";
button.textContent = "Open Account › Security";
button.addEventListener("click", () => window.connectivitizer.openSettings());
node.appendChild(document.createElement("br"));
node.appendChild(button);
}
}
const kb = (bytes) => (bytes >= 1000000 ? (bytes / 1000000).toFixed(1) + " MB" : Math.max(1, Math.round(bytes / 1000)) + " KB");
const clock = (seconds) => Math.floor(seconds / 60) + ":" + String(Math.floor(seconds % 60)).padStart(2, "0");
async function problemOf(response) {
const text = (await response.text()).trim();
return text && text.length < 300 && !/^\s*</.test(text) ? text : "The device answered " + response.status + ".";
}
// ariaLabel, ariaHidden and role as attributes, which every WebView understands.
function element(tag, props, children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props || {})) {
if (key === "role" || key.startsWith("aria")) node.setAttribute(key === "role" ? key : "aria-" + key.slice(4).toLowerCase(), value);
else node[key] = value;
}
for (const child of children || []) if (child) node.append(child);
return node;
}
// Icons drawn from path data, so that nothing is ever parsed as HTML.
const ICONS = {
bird: ["M3 15c2.5 0 4.5-1.3 5.6-3.6l1.8-3.8a3.3 3.3 0 0 1 6.2 1.3l2.4.9-2.4 1.2c0 4.4-3.2 7.5-8.4 7.5H3l3.2-2.8z", "M13.6 9.2h.01", "M9 18.5l-1 3M11.5 18.4l-.3 3"],
butterfly: ["M12 7v12", "M12 9C10.5 5 4 3 4 7.3c0 3 3.4 4.2 8 3.9", "M12 9c1.5-4 8-6 8-1.7 0 3-3.4 4.2-8 3.9", "M12 12c-3 0-6.5 1-6.5 4 0 2.4 3.6 2.2 6.5-2", "M12 12c3 0 6.5 1 6.5 4 0 2.4-3.6 2.2-6.5-2", "M12 7l-2-3.5M12 7l2-3.5"],
other: ["M5 19c0-8 5-14 14-14 0 9-6 14-14 14z", "M5 19l7-7"],
play: ["M8 5.5v13l10.5-6.5z"],
pause: ["M7 5h3.5v14H7zM13.5 5H17v14h-3.5z"],
more: ["M5 12h.01M12 12h.01M19 12h.01"],
pin: ["M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z", "M12 7a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5z"],
};
function icon(name) {
const NS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(NS, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("class", "i");
svg.setAttribute("aria-hidden", "true");
for (const d of ICONS[name]) {
const path = document.createElementNS(NS, "path");
path.setAttribute("d", d);
if (name === "more") path.setAttribute("stroke-width", "3.2");
svg.append(path);
}
return svg;
}
// ------------------------------------------------------------------ species, count and note
function bindStepper(input, down, up) {
const set = (n) => { input.value = String(Math.min(limits.maxCount, Math.max(1, Math.round(n) || 1))); };
down.addEventListener("click", () => set(Number(input.value) - 1));
up.addEventListener("click", () => set(Number(input.value) + 1));
input.addEventListener("change", () => set(Number(input.value)));
return () => Math.min(limits.maxCount, Math.max(1, Math.round(Number(input.value)) || 1));
}
const draftCount = bindStepper($("count"), $("count-down"), $("count-up"));
$("note").addEventListener("input", () => {
$("counter").textContent = Array.from($("note").value).length + " / " + limits.maxNoteChars;
});
// ------------------------------------------------------------------ camera
// A request the person has not answered yet is not an error; but when nothing comes at all, the
// page says where it can be turned on.
function watchdog(hintId, what, ms) {
const timer = setTimeout(() => say(hintId, "Nothing yet? " + refused(what)), ms);
return () => clearTimeout(timer);
}
function mediaProblem(error, what) {
const name = error && error.name;
if (name === "NotAllowedError" || name === "SecurityError" || name === "PermissionDeniedError") return refused(what);
// A WebView that hands the request to no one says "not supported"; in the app that is a refusal too.
if (name === "NotSupportedError") return inApp ? refused(what) : "This browser does not offer the " + what + " to this page.";
if (name === "NotFoundError" || name === "OverconstrainedError" || name === "DevicesNotFoundError") return what === "camera" ? "This phone or computer has no camera that the page can use." : "This phone or computer has no microphone that the page can use.";
if (name === "NotReadableError" || name === "TrackStartError") return "The " + what + " could not be started; another app may be using it. Close apps that use the " + what + " and try again.";
if (name === "AbortError") return "The request was cancelled. Try again.";
return (what === "camera" ? "The camera could not be started: " : "The microphone could not be started: ") + ((error && error.message) || String(error));
}
function noMediaDevices(what) {
if (inApp) return refused(what);
return "This browser lets a page use the " + what + " only over https:// or from http://127.0.0.1 (open the page there)." + (what === "camera" ? " Take or choose works anyway." : "");
}
const finder = (state) => { $("finder").dataset.state = state; };
let cameraStream = null;
function stopCamera() {
if (cameraStream) cameraStream.getTracks().forEach((track) => track.stop());
cameraStream = null;
$("camera-video").srcObject = null;
finder(draft.photo ? "photo" : "empty");
}
$("camera-open").addEventListener("click", async () => {
say("camera-hint", "");
say("picker-hint", "");
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) return say("camera-hint", noMediaDevices("camera"));
$("camera-open").disabled = true;
const done = watchdog("camera-hint", "camera", 15000);
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment", width: { ideal: 1920 }, height: { ideal: 1080 } }, audio: false });
done();
say("camera-hint", "");
cameraStream = stream;
$("camera-video").srcObject = stream;
finder("live");
await $("camera-video").play().catch(() => undefined);
$("camera-capture").focus();
} catch (error) {
done();
say("camera-hint", mediaProblem(error, "camera"));
} finally {
$("camera-open").disabled = false;
}
});
$("camera-cancel").addEventListener("click", stopCamera);
$("camera-capture").addEventListener("click", async () => {
const video = $("camera-video");
if (!video.videoWidth) return say("camera-hint", "The camera has not delivered a picture yet. Wait a moment and try again.");
try {
const photo = await toJpeg(video, video.videoWidth, video.videoHeight);
if (cameraStream) cameraStream.getTracks().forEach((track) => track.stop());
cameraStream = null;
$("camera-video").srcObject = null;
attachPhoto(photo);
} catch (error) {
say("camera-hint", error.message);
}
});
// Draws `source` (a video, an ImageBitmap) at most MAX_PHOTO_EDGE wide or high and makes a JPEG
// that the device takes (at most limits.maxPhotoBytes).
async function toJpeg(source, width, height) {
const scale = Math.min(1, MAX_PHOTO_EDGE / Math.max(width, height));
const canvas = document.createElement("canvas");
canvas.width = Math.round(width * scale);
canvas.height = Math.round(height * scale);
canvas.getContext("2d").drawImage(source, 0, 0, canvas.width, canvas.height);
for (const quality of [0.85, 0.7, 0.55, 0.4]) {
const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", quality));
if (!blob) break;
if (blob.size <= limits.maxPhotoBytes) return blob;
}
throw new Error("The photo could not be made small enough for the device (at most " + kb(limits.maxPhotoBytes) + ").");
}
function attachPhoto(blob) {
if (draft.photoUrl) URL.revokeObjectURL(draft.photoUrl);
draft.photo = blob;
draft.photoUrl = blob ? URL.createObjectURL(blob) : null;
if (blob) $("photo-preview").src = draft.photoUrl;
else $("photo-preview").removeAttribute("src");
$("photo-size").textContent = blob ? "Photo · " + kb(blob.size) : "";
$("photo-remove").hidden = !blob;
finder(cameraStream ? "live" : blob ? "photo" : "empty");
}
$("photo-remove").addEventListener("click", () => attachPhoto(null));
// ------------------------------------------------------------------ photo from the phone
$("photo-file").addEventListener("change", async () => {
const file = $("photo-file").files && $("photo-file").files[0];
$("photo-file").value = "";
say("picker-hint", "");
if (!file) return;
if (!/^image\//.test(file.type || "image/")) return say("picker-hint", "That is not a picture.");
try {
// Phone photos are several MB; the page makes a smaller JPEG of them, upright as the phone took it.
const bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
const photo = await toJpeg(bitmap, bitmap.width, bitmap.height);
bitmap.close && bitmap.close();
if (cameraStream) stopCamera();
attachPhoto(photo);
} catch (error) {
// createImageBitmap fails for formats the browser cannot decode (HEIC on many Android phones).
const tooBig = error instanceof Error && /small enough/.test(error.message);
say("picker-hint", tooBig ? error.message : "This picture cannot be read here. Pick a JPEG or PNG photo.");
}
});
// ------------------------------------------------------------------ voice notes
// A pill with a play button and a waveform that fills as it plays. `load` gives the Blob, on the
// first tap; the waveform is a guess from `seed` until the sound is decoded, then the real one.
let playing = null;
function voicePill(load, seed, seconds) {
const bars = [];
let h = 0;
for (const c of String(seed)) h = (h * 31 + c.charCodeAt(0)) >>> 0;
for (let i = 0; i < 22; i++) {
h = (h * 1103515245 + 12345) >>> 0;
bars.push(element("span", { style: "height:" + (25 + (h % 70)) + "%" }));
}
const play = element("button", { type: "button", className: "play", ariaLabel: "Play voice note" }, [icon("play")]);
const time = element("span", { className: "t", textContent: seconds ? clock(seconds) : "Voice note" });
const pill = element("span", { className: "voice" }, [play, element("span", { className: "wave", ariaHidden: "true" }, bars), time]);
let audio = null;
let length = seconds || 0;
const show = (part) => bars.forEach((bar, i) => bar.classList.toggle("on", i < Math.round(part * bars.length)));
const setIcon = (name, label) => { play.replaceChildren(icon(name)); play.setAttribute("aria-label", label); };
play.addEventListener("click", async () => {
if (!audio) {
play.disabled = true;
time.textContent = "Loading…";
let blob;
try {
blob = await load();
} catch (error) {
play.disabled = false;
time.textContent = "Voice note";
pill.after(element("p", { className: "problem", textContent: "The voice note could not be loaded: " + error.message }));
return;
}
audio = new Audio(URL.createObjectURL(blob));
audio.addEventListener("timeupdate", () => {
if (length) { show(audio.currentTime / length); time.textContent = clock(Math.max(0, length - audio.currentTime)); }
});
audio.addEventListener("play", () => setIcon("pause", "Pause voice note"));
audio.addEventListener("pause", () => setIcon("play", "Play voice note"));
audio.addEventListener("ended", () => { show(0); time.textContent = length ? clock(length) : "Voice note"; });
audio.addEventListener("loadedmetadata", () => { if (!length && isFinite(audio.duration)) length = audio.duration; });
time.textContent = length ? clock(length) : "Voice note";
play.disabled = false;
// The real shape and length (a recording from MediaRecorder often says it has no duration).
decodeShape(blob, bars.length).then((shape) => {
if (!shape) return;
length = shape.seconds;
shape.peaks.forEach((peak, i) => { bars[i].style.height = Math.round(18 + peak * 82) + "%"; });
if (audio.paused) time.textContent = clock(length);
});
}
if (audio.paused) {
if (playing && playing !== audio) playing.pause();
playing = audio;
audio.play().catch(() => undefined);
} else audio.pause();
});
return pill;
}
async function decodeShape(blob, count) {
const Context = window.AudioContext || window.webkitAudioContext;
if (!Context) return null;
let context;
try {
context = new Context();
const sound = await context.decodeAudioData(await blob.arrayBuffer());
const data = sound.getChannelData(0);
const step = Math.max(1, Math.floor(data.length / count));
const peaks = [];
for (let i = 0; i < count; i++) {
let peak = 0;
for (let j = i * step; j < Math.min(data.length, (i + 1) * step); j += 16) peak = Math.max(peak, Math.abs(data[j]));
peaks.push(peak);
}
const top = Math.max(0.01, ...peaks);
return { seconds: sound.duration, peaks: peaks.map((peak) => peak / top) };
} catch {
return null;
} finally {
if (context && context.close) context.close().catch(() => undefined);
}
}
let recorder = null;
let recordTimer = null;
function attachAudio(blob, seconds) {
draft.audio = blob;
$("audio-slot").replaceChildren(blob ? voicePill(async () => blob, "draft" + blob.size, seconds) : "");
$("audio-attached").hidden = !blob;
$("mic-record").hidden = Boolean(blob);
}
$("audio-remove").addEventListener("click", () => attachAudio(null));
function recordingType() {
const types = ["audio/webm;codecs=opus", "audio/webm", "audio/mp4", "audio/ogg;codecs=opus", "audio/ogg"];
return types.find((type) => window.MediaRecorder && MediaRecorder.isTypeSupported && MediaRecorder.isTypeSupported(type)) || "";
}
// A small level meter while recording, where the browser offers one.
function levelMeter(stream) {
const Context = window.AudioContext || window.webkitAudioContext;
const bars = Array.from({ length: 8 }, () => element("span", { style: "height:20%" }));
$("mic-meter").replaceChildren(...bars);
if (!Context) return () => undefined;
try {
const context = new Context();
const analyser = context.createAnalyser();
analyser.fftSize = 512;
context.createMediaStreamSource(stream).connect(analyser);
const data = new Uint8Array(analyser.fftSize);
const levels = [];
const timer = setInterval(() => {
analyser.getByteTimeDomainData(data);
let sum = 0;
for (const value of data) sum += (value - 128) * (value - 128);
levels.push(Math.min(1, Math.sqrt(sum / data.length) / 40));
if (levels.length > bars.length) levels.shift();
levels.forEach((level, i) => { bars[i].style.height = Math.round(20 + level * 80) + "%"; });
}, 120);
return () => { clearInterval(timer); context.close().catch(() => undefined); };
} catch {
return () => undefined;
}
}
$("mic-record").addEventListener("click", async () => {
say("mic-hint", "");
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) return say("mic-hint", noMediaDevices("microphone"));
if (!window.MediaRecorder) return say("mic-hint", "This browser cannot record sound.");
$("mic-record").disabled = true;
const done = watchdog("mic-hint", "microphone", 15000);
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true }, video: false });
} catch (error) {
done();
$("mic-record").disabled = false;
return say("mic-hint", mediaProblem(error, "microphone"));
}
done();
say("mic-hint", "");
const type = recordingType();
const chunks = [];
try {
recorder = new MediaRecorder(stream, Object.assign({ audioBitsPerSecond: 48000 }, type ? { mimeType: type } : {}));
} catch (error) {
stream.getTracks().forEach((track) => track.stop());
$("mic-record").disabled = false;
return say("mic-hint", "This browser cannot record sound: " + error.message);
}
const stopMeter = levelMeter(stream);
const started = Date.now();
recorder.ondataavailable = (event) => { if (event.data && event.data.size) chunks.push(event.data); };
recorder.onstop = () => {
clearInterval(recordTimer);
stopMeter();
stream.getTracks().forEach((track) => track.stop());
const blob = new Blob(chunks, { type: (recorder.mimeType || type || "audio/webm").split(";")[0] });
recorder = null;
$("mic-stop").hidden = true;
$("mic-record").hidden = false;
$("mic-record").disabled = false;
if (!blob.size) return say("mic-hint", "Nothing was recorded. Try again.");
if (blob.size > limits.maxAudioBytes) return say("mic-hint", "The voice note is larger than the device takes (" + kb(limits.maxAudioBytes) + ").");
attachAudio(blob, Math.min(MAX_SECONDS, (Date.now() - started) / 1000));
};
const tick = () => {
const gone = (Date.now() - started) / 1000;
$("mic-stop-text").textContent = "Stop · " + clock(Math.min(gone, MAX_SECONDS)) + " / " + clock(MAX_SECONDS);
if (gone >= MAX_SECONDS && recorder && recorder.state === "recording") recorder.stop();
};
recorder.start(1000);
tick();
recordTimer = setInterval(tick, 250);
$("mic-record").hidden = true;
$("mic-stop").hidden = false;
$("mic-stop").focus();
});
$("mic-stop").addEventListener("click", () => {
if (recorder && recorder.state === "recording") recorder.stop();
});
// ------------------------------------------------------------------ location
const coords = (location) => location.lat.toFixed(5) + ", " + location.lon.toFixed(5);
function showLocation(location) {
draft.location = location;
$("location-attached").hidden = !location;
$("location-add").hidden = Boolean(location);
$("location-text").textContent = location ? "Location added" + (location.accuracy != null ? " ±" + Math.round(location.accuracy) + " m" : "") : "";
$("location-attached").title = location ? coords(location) : "";
}
$("location-remove").addEventListener("click", () => showLocation(null));
$("location-add").addEventListener("click", () => {
say("location-hint", "");
if (!navigator.geolocation) return say("location-hint", inApp ? refused("location") : "This browser offers no location to the page.");
$("location-add").disabled = true;
$("location-add-text").textContent = "Finding you…";
const finished = () => { $("location-add").disabled = false; $("location-add-text").textContent = "Location"; };
// Without an answer (a question nobody answers, a phone without a position) the page says so.
const done = watchdog("location-hint", "location", 25000);
navigator.geolocation.getCurrentPosition(
(position) => {
done();
finished();
say("location-hint", "");
showLocation({ lat: position.coords.latitude, lon: position.coords.longitude, accuracy: position.coords.accuracy });
},
(error) => {
done();
finished();
if (error.code === 1) say("location-hint", refused("location"));
else if (error.code === 2) say("location-hint", "The phone could not find its position. Location may be turned off in the phone's settings.");
else say("location-hint", "Finding the position took too long. Try again, perhaps in the open.");
},
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 60000 },
);
});
// ------------------------------------------------------------------ links
// In the app a link opens only if the person turned links on and then says yes. When the page is
// still in front a moment after the tap, nothing has opened (or the question is still open), so the
// page says where links are turned on. Outside the app a link simply opens in a new tab.
let linkTimer = null;
let toastTimer = null;
document.addEventListener("click", (event) => {
const link = event.target.closest && event.target.closest("a[href]");
if (!link || !inApp) return;
clearTimeout(linkTimer);
clearTimeout(toastTimer);
say("links-hint", "");
let left = false;
const leave = () => { left = true; };
window.addEventListener("blur", leave, { once: true });
document.addEventListener("visibilitychange", leave, { once: true });
linkTimer = setTimeout(() => {
window.removeEventListener("blur", leave);
document.removeEventListener("visibilitychange", leave);
if (!left && document.visibilityState === "visible") {
say("links-hint", "Nothing opened? " + SWITCH.links);
toastTimer = setTimeout(() => say("links-hint", ""), 15000);
}
}, 2500);
});
function mapUrl(location) {
const lat = location.lat.toFixed(6);
const lon = location.lon.toFixed(6);
return "https://www.openstreetmap.org/?mlat=" + lat + "&mlon=" + lon + "#map=17/" + lat + "/" + lon;
}
const titleOf = (entry) => (entry.species || "Unnamed sighting") + (entry.count > 1 ? " ×" + entry.count : "");
// An email with the sighting, short enough for the app (it opens addresses up to 2048 characters).
function mailUrl(entry) {
const when = new Date(entry.createdAt).toLocaleString([], { dateStyle: "medium", timeStyle: "short" });
const where = entry.location ? "\n\nWhere: " + mapUrl(entry.location) : "";
let note = entry.note || "";
for (;;) {
const body = titleOf(entry) + ", " + when + (note ? "\n\n" + note : "") + where;
const url = "mailto:?subject=" + encodeURIComponent("Sighting: " + titleOf(entry)) + "&body=" + encodeURIComponent(body);
if (url.length <= 2000 || note.length < 20) return url;
note = note.slice(0, Math.floor(note.length * 0.8)) + "…";
}
}
// ------------------------------------------------------------------ saving
function resetDraft() {
$("note").value = "";
$("species").value = "";
$("count").value = "1";
$("counter").textContent = "0 / " + limits.maxNoteChars;
attachPhoto(null);
attachAudio(null);
showLocation(null);
}
$("save").addEventListener("click", async () => {
const note = $("note").value.trim();
const species = $("species").value.replace(/\s+/g, " ").trim();
if (!note && !species && !draft.photo && !draft.audio && !draft.location) {
$("save-status").className = "problem";
$("save-status").textContent = "Name what you saw, or add a photo or a note first.";
return;
}
$("save").disabled = true;
$("save-status").className = "muted";
$("save-status").textContent = "Saving…";
let created = null;
try {
const response = await fetch("/entries", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ note, species, count: draftCount(), location: draft.location }) });
if (!response.ok) throw new Error(await problemOf(response));
created = await response.json();
for (const [part, blob] of [["photo", draft.photo], ["audio", draft.audio]]) {
if (!blob) continue;
$("save-status").textContent = part === "photo" ? "Sending the photo…" : "Sending the voice note…";
const upload = await fetch("/entries/" + created.id + "/" + part, { method: "PUT", headers: { "Content-Type": blob.type || (part === "photo" ? "image/jpeg" : "audio/webm") }, body: blob });
if (!upload.ok) throw new Error(await problemOf(upload));
}
resetDraft();
$("save-status").className = "saved";
$("save-status").textContent = "Saved to the journal.";
setTimeout(() => { if ($("save-status").textContent === "Saved to the journal.") $("save-status").textContent = ""; }, 3000);
} catch (error) {
// Half an entry is no use: what was created goes again, and the draft stays for another try.
if (created) await fetch("/entries/" + created.id, { method: "DELETE" }).catch(() => undefined);
$("save-status").className = "problem";
$("save-status").textContent = "Not saved: " + error.message;
} finally {
$("save").disabled = false;
loadEntries();
}
});
// ------------------------------------------------------------------ the journal
const photoUrls = new Map();
const lazyPhotos = "IntersectionObserver" in window
? new IntersectionObserver((seen) => {
for (const item of seen) {
if (!item.isIntersecting) continue;
lazyPhotos.unobserve(item.target);
loadPhoto(item.target);
}
}, { rootMargin: "200px" })
: null;
async function loadPhoto(img) {
const id = img.dataset.id;
if (photoUrls.has(id)) { img.src = photoUrls.get(id); return; }
try {
const response = await fetch("/entries/" + id + "/photo");
if (!response.ok) throw new Error(await problemOf(response));
const url = URL.createObjectURL(await response.blob());
photoUrls.set(id, url);
img.src = url;
} catch (error) {
img.replaceWith(element("p", { className: "problem", style: "padding:12px 14px 0", textContent: "The photo could not be loaded: " + error.message }));
}
}
async function getBlob(path) {
const response = await fetch(path);
if (!response.ok) throw new Error(await problemOf(response));
return response.blob();
}
// Species, count and note of a sighting, changed in place (PUT /entries/{id}).
function editEntry(entry, body) {
const species = element("input", { type: "text", className: "sp", value: entry.species || "", maxLength: limits.maxSpeciesChars, autocomplete: "off", placeholder: "Species" });
species.setAttribute("list", "species-list");
species.setAttribute("aria-label", "Species");
const count = element("input", { type: "number", min: 1, max: limits.maxCount, value: String(entry.count || 1), inputMode: "numeric", ariaLabel: "Count" });
const down = element("button", { type: "button", textContent: "−", ariaLabel: "One fewer" });
const up = element("button", { type: "button", textContent: "+", ariaLabel: "One more" });
const getCount = bindStepper(count, down, up);
const note = element("textarea", { value: entry.note || "", maxLength: limits.maxNoteChars, ariaLabel: "Note" });
const status = element("span", { role: "status" });
const save = element("button", { type: "button", className: "primary", textContent: "Save changes" });
const cancel = element("button", { type: "button", className: "quiet", textContent: "Cancel" });
const form = element("div", { className: "edit" }, [
element("div", { className: "fields" }, [species, element("div", { className: "stepper" }, [down, count, up])]),
note,
element("div", { className: "row" }, [save, cancel, status]),
]);
const before = Array.from(body.children);
body.replaceChildren(form);
species.focus();
cancel.addEventListener("click", () => body.replaceChildren(...before));
save.addEventListener("click", async () => {
save.disabled = true;
status.className = "muted";
status.textContent = "Saving…";
try {
const change = { species: species.value.replace(/\s+/g, " ").trim(), count: getCount(), note: note.value.trim() };
const response = await fetch("/entries/" + entry.id, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(change) });
if (!response.ok) throw new Error(await problemOf(response));
loadEntries();
} catch (error) {
save.disabled = false;
status.className = "problem";
status.textContent = "Not saved: " + error.message;
}
});
}
function renderEntry(entry) {
const kind = kindOf(entry.species);
const body = element("div", { className: "s-body" });
const article = element("article", { className: "card sighting" });
if (entry.photo) {
const img = element("img", { className: "photo", alt: "Photo of " + (entry.species || "this sighting") });
img.dataset.id = entry.id;
article.append(img);
if (lazyPhotos) lazyPhotos.observe(img); else loadPhoto(img);
}
const when = new Date(entry.createdAt);
const title = element("div", { className: "s-title" }, [
element("h4", { className: entry.species ? "" : "unnamed" }, [entry.species || "Unnamed sighting", entry.count > 1 ? element("span", { className: "n", textContent: "×" + entry.count }) : null]),
element("time", { dateTime: entry.createdAt, textContent: when.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) }),
entry.sample ? element("span", { className: "tag", textContent: "Example" }) : null,
]);
// The menu: change, email, delete.
const menu = element("details", { className: "menu" });
const summary = element("summary", { ariaLabel: "More for " + titleOf(entry) }, [icon("more")]);
const edit = element("button", { type: "button", textContent: "Edit" });
const mail = element("a", { href: mailUrl(entry), target: "_blank", rel: "noopener noreferrer", textContent: "Email this entry ✉" });
const remove = element("button", { type: "button", className: "danger", textContent: "Delete" });
menu.append(summary, element("div", { className: "menu-list" }, [edit, mail, remove]));
edit.addEventListener("click", () => { menu.open = false; editEntry(entry, body); });
let armed = null;
remove.addEventListener("click", async () => {
// Two taps, so that a slip of the finger deletes nothing.
if (!armed) {
remove.textContent = "Tap again to delete";
armed = setTimeout(() => { armed = null; remove.textContent = "Delete"; }, 3000);
return;
}
clearTimeout(armed);
remove.disabled = true;
const response = await fetch("/entries/" + entry.id, { method: "DELETE" }).catch((error) => ({ ok: false, text: async () => error.message }));
if (!response.ok && response.status !== 404) {
remove.disabled = false;
armed = null;
remove.textContent = "Delete";
say("list-problem", "Not deleted: " + (await problemOf(response)));
}
loadEntries();
});
body.append(element("div", { className: "s-head" }, [
entry.photo ? null : element("span", { className: "badge " + kind }, [icon(kind)]),
title,
menu,
]));
if (entry.note) body.append(element("p", { className: "note", textContent: entry.note }));
const meta = element("div", { className: "s-meta" });
if (entry.audio) meta.append(voicePill(() => getBlob("/entries/" + entry.id + "/audio"), entry.id, 0));
if (entry.location) {
meta.append(element("a", { className: "chip", href: mapUrl(entry.location), target: "_blank", rel: "noopener noreferrer", title: coords(entry.location) }, [
icon("pin"), "Open in map ↗", entry.location.accuracy != null ? element("span", { className: "acc", textContent: "±" + entry.location.accuracy + " m" }) : null,
]));
}
if (meta.childElementCount) body.append(meta);
article.append(body);
return element("li", { className: "entry" }, [article]);
}
function dayLabel(date) {
const start = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
const days = Math.round((start(new Date()) - start(date)) / 86400000);
if (days === 0) return "Today";
if (days === 1) return "Yesterday";
return date.toLocaleDateString([], { weekday: "long", day: "numeric", month: "long" });
}
const plural = (n, one, many) => n + " " + (n === 1 ? one : many);
// Old entries (from before species and counts) have neither; they count as one unnamed sighting.
function showTally(entries) {
const named = new Set(entries.map((entry) => (entry.species || "").toLowerCase()).filter(Boolean));
$("tally-entries").textContent = entries.length;
$("tally-species").textContent = named.size;
$("tally-count").textContent = entries.reduce((sum, entry) => sum + (entry.count || (entry.species ? 1 : 0)), 0);
}
let loading = false;
async function loadEntries() {
if (loading) return;
loading = true;
try {
const response = await fetch("/entries");
if (!response.ok) throw new Error(await problemOf(response));
const entries = await response.json();
say("list-problem", "");
// Photos of entries that are gone are let go.
const ids = new Set(entries.map((entry) => entry.id));
for (const [id, url] of photoUrls) if (!ids.has(id)) { URL.revokeObjectURL(url); photoUrls.delete(id); }
// Newest first, grouped by day.
const days = [];
for (const entry of entries) {
const label = dayLabel(new Date(entry.createdAt));
if (!days.length || days[days.length - 1].label !== label) days.push({ label, entries: [] });
days[days.length - 1].entries.push(entry);
}
$("entries").replaceChildren(...days.map((day) => element("section", { className: "day" }, [
element("h3", {}, [day.label, element("span", { textContent: plural(day.entries.length, "sighting", "sightings") })]),
element("ol", { className: "trail" }, day.entries.map(renderEntry)),
])));
$("entries-empty").hidden = entries.length > 0;
$("entries-count").textContent = entries.length + " of at most " + limits.maxEntries;
showTally(entries);
} catch (error) {
say("list-problem", "The journal could not be loaded: " + error.message);
} finally {
loading = false;
}
}
// One menu open at a time; a tap elsewhere or Escape closes it.
document.addEventListener("click", (event) => {
for (const open of document.querySelectorAll("details.menu[open]")) if (!open.contains(event.target)) open.open = false;
});
document.addEventListener("keydown", (event) => {
if (event.key !== "Escape") return;
for (const open of document.querySelectorAll("details.menu[open]")) { open.open = false; open.querySelector("summary").focus(); }
});
// ------------------------------------------------------------------ start
$("now").textContent = new Date().toLocaleDateString([], { weekday: "long", day: "numeric", month: "long" });
// The app's bar follows the page's light or dark colours.
if (window.connectivitizer && typeof window.connectivitizer.setTheme === "function") {
const dark = window.matchMedia("(prefers-color-scheme: dark)");
const follow = () => window.connectivitizer.setTheme(dark.matches ? { background: "#141813", foreground: "#ebe7d8" } : null);
follow();
dark.addEventListener && dark.addEventListener("change", follow);
}
if (window.connectivitizer) {
window.connectivitizer.ready.then((device) => {
if (!device) return;
$("where").textContent = (device.title || device.name) + (device.path ? " · " + (device.path === "direct" ? "peer to peer" : "through the relay") : "") + (device.endToEndEncrypted ? " · end-to-end encrypted" : "");
});
} else {
$("where").textContent = "Straight from the device's web server";
}
fetch("/info")
.then((response) => (response.ok ? response.json() : null))
.then((info) => {
if (info && info.limits) limits = Object.assign(limits, info.limits);
$("note").maxLength = limits.maxNoteChars;
$("species").maxLength = limits.maxSpeciesChars;
$("count").max = limits.maxCount;
$("counter").textContent = Array.from($("note").value).length + " / " + limits.maxNoteChars;
$("limits").textContent = "Kept in the device's memory only, never on disk: at most " + limits.maxEntries + " sightings (the oldest go first), each forgotten after " + limits.keepHours + " hours or when the device restarts. Photos up to " + kb(limits.maxPhotoBytes) + ", voice notes up to " + kb(limits.maxAudioBytes) + " and " + MAX_SECONDS + " seconds, notes up to " + limits.maxNoteChars + " characters.";
})
.catch(() => undefined)
.finally(loadEntries);
</script>
</body>
</html>