237 lines
7.4 KiB
JavaScript
237 lines
7.4 KiB
JavaScript
// history.js - the model of the history and the favourites.
|
|
//
|
|
// Pure: no GPUI, no herdr, no IO. Every function returns a new list and never
|
|
// touches the one it was given. What is kept on the disk is storage.js; the
|
|
// panel that shows it is Task 7.
|
|
|
|
import { HISTORY_LIMIT, FAVORITES_LIMIT } from "./storage.js";
|
|
|
|
/**
|
|
* @typedef {object} HistoryEntry
|
|
* @property {string} id
|
|
* @property {string} text
|
|
* @property {number} sentAt
|
|
* @property {string} agent - the address of the agent (`t2`)
|
|
* @property {string} agentName
|
|
* @property {string} space
|
|
* @property {string} spaceName
|
|
* @property {string} [tabName]
|
|
*
|
|
* @typedef {object} Favorite
|
|
* @property {string} id
|
|
* @property {string} text
|
|
* @property {number} createdAt
|
|
*
|
|
* @typedef {object} Hit
|
|
* @property {HistoryEntry|Favorite} item
|
|
* @property {[number, number][]} ranges - where the query was found: [start, end)
|
|
*/
|
|
|
|
/**
|
|
* A message was sent: it goes to the end of the history.
|
|
*
|
|
* Duplicates are kept - the same text sent twice is two entries. The oldest
|
|
* entries drop out over the limit (500).
|
|
*
|
|
* @param {HistoryEntry[]} list - chronological, the oldest first
|
|
* @param {HistoryEntry} entry
|
|
* @returns {HistoryEntry[]}
|
|
*/
|
|
export function record(list, entry) {
|
|
return [...(Array.isArray(list) ? list : []), entry].slice(-HISTORY_LIMIT);
|
|
}
|
|
|
|
/**
|
|
* What matches the query - newest first.
|
|
*
|
|
* The query is a fragment, found without regard to case (Polish letters too),
|
|
* every occurrence. An empty query (or one of spaces only) gives everything.
|
|
*
|
|
* @param {(HistoryEntry|Favorite)[]} list
|
|
* @param {string} query
|
|
* @returns {Hit[]}
|
|
*/
|
|
export function search(list, query) {
|
|
const needle = fold(String(query ?? "").trim());
|
|
const items = (Array.isArray(list) ? list : [])
|
|
.map((item, index) => ({ item, index }))
|
|
.sort((a, b) => momentOf(b.item) - momentOf(a.item) || b.index - a.index);
|
|
|
|
if (needle === "") return items.map(({ item }) => ({ item, ranges: [] }));
|
|
|
|
const hits = [];
|
|
for (const { item } of items) {
|
|
const ranges = occurrences(fold(String(item.text ?? "")), needle);
|
|
if (ranges.length > 0) hits.push({ item, ranges });
|
|
}
|
|
return hits;
|
|
}
|
|
|
|
/**
|
|
* The favourite is added, or removed when it is there already. Texts are
|
|
* compared after `trim()`; the oldest favourites drop out over the limit
|
|
* (100). Nothing but spaces is not a favourite - the same list comes back.
|
|
*
|
|
* @param {Favorite[]} favs
|
|
* @param {string} text
|
|
* @param {number} now
|
|
* @returns {Favorite[]}
|
|
*/
|
|
export function toggleFavorite(favs, text, now) {
|
|
const list = Array.isArray(favs) ? favs : [];
|
|
const clean = String(text ?? "").trim();
|
|
if (clean === "") return favs;
|
|
|
|
if (list.some((fav) => fav.text.trim() === clean)) {
|
|
return list.filter((fav) => fav.text.trim() !== clean);
|
|
}
|
|
return [...list, { id: freshId(list, now), text: clean, createdAt: now }].slice(-FAVORITES_LIMIT);
|
|
}
|
|
|
|
/**
|
|
* @param {Favorite[]} favs
|
|
* @param {string} text
|
|
* @returns {boolean}
|
|
*/
|
|
export function isFavorite(favs, text) {
|
|
const clean = String(text ?? "").trim();
|
|
if (clean === "") return false;
|
|
return (Array.isArray(favs) ? favs : []).some((fav) => fav.text.trim() === clean);
|
|
}
|
|
|
|
/** The moment an entry was made - a history entry or a favourite. */
|
|
function momentOf(item) {
|
|
const value = item.sentAt ?? item.createdAt;
|
|
return Number.isFinite(value) ? value : 0;
|
|
}
|
|
|
|
/**
|
|
* The text in the form the comparison uses: every letter in lower case, one
|
|
* character for one character - so a position in the folded text is a position
|
|
* in the original (a letter that would change the length stays as it is).
|
|
*/
|
|
function fold(text) {
|
|
return text
|
|
.split("")
|
|
.map((char) => {
|
|
const lower = char.toLowerCase();
|
|
return lower.length === 1 ? lower : char;
|
|
})
|
|
.join("");
|
|
}
|
|
|
|
/** Where `needle` is in `text`: every place, none overlapping. */
|
|
function occurrences(text, needle) {
|
|
const ranges = [];
|
|
let from = 0;
|
|
for (;;) {
|
|
const at = text.indexOf(needle, from);
|
|
if (at < 0) break;
|
|
ranges.push([at, at + needle.length]);
|
|
from = at + needle.length;
|
|
}
|
|
return ranges;
|
|
}
|
|
|
|
/** An id that no favourite has yet. */
|
|
function freshId(list, now) {
|
|
const taken = new Set(list.map((fav) => fav.id));
|
|
let n = 0;
|
|
let id = `f${now}`;
|
|
while (taken.has(id)) id = `f${now}-${(n += 1)}`;
|
|
return id;
|
|
}
|
|
|
|
// --- what the panel shows ---------------------------------------------------
|
|
//
|
|
// The panel (panel.js) only draws. What it draws - which rows, which part of a
|
|
// row is lit, the line under the text, which empty state - is decided here, so
|
|
// it is tested in plain Node.
|
|
|
|
/**
|
|
* A text cut into the parts that match the query and the parts that do not.
|
|
*
|
|
* @param {string} text
|
|
* @param {[number, number][]} ranges - as `search` returns them
|
|
* @returns {{text:string, hit:boolean}[]}
|
|
*/
|
|
export function segments(text, ranges) {
|
|
const source = String(text ?? "");
|
|
const out = [];
|
|
let at = 0;
|
|
for (const [start, end] of Array.isArray(ranges) ? ranges : []) {
|
|
const from = Math.max(at, Math.min(start, source.length));
|
|
const to = Math.min(end, source.length);
|
|
if (to <= from) continue;
|
|
if (from > at) out.push({ text: source.slice(at, from), hit: false });
|
|
out.push({ text: source.slice(from, to), hit: true });
|
|
at = to;
|
|
}
|
|
if (at < source.length) out.push({ text: source.slice(at), hit: false });
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* A moment as `DD.MM HH:MM`, in the time of this computer.
|
|
*
|
|
* @param {number} ms
|
|
* @returns {string}
|
|
*/
|
|
export function formatMoment(ms) {
|
|
if (!Number.isFinite(ms)) return "";
|
|
const date = new Date(ms);
|
|
const two = (n) => String(n).padStart(2, "0");
|
|
return `${two(date.getDate())}.${two(date.getMonth() + 1)} ${two(date.getHours())}:${two(date.getMinutes())}`;
|
|
}
|
|
|
|
/**
|
|
* The line under the text of a row: when, in which space, to which agent - or,
|
|
* for a favourite, when it was saved.
|
|
*
|
|
* @param {HistoryEntry|Favorite} item
|
|
* @param {"history"|"favorites"} tab
|
|
* @returns {string}
|
|
*/
|
|
export function entryMeta(item, tab) {
|
|
if (tab === "favorites") return `zapisano ${formatMoment(item.createdAt)}`;
|
|
const space = item.spaceName || "?";
|
|
const agent = item.tabName || item.agentName || "?";
|
|
return `${formatMoment(item.sentAt)} · ${space} · ${agent}`;
|
|
}
|
|
|
|
/**
|
|
* Everything the panel draws, for one tab and one query.
|
|
*
|
|
* `empty` says which empty state to show: the whole list is empty
|
|
* (`"history"` / `"favorites"`), or only the query found nothing (`"query"`).
|
|
*
|
|
* @param {{history:HistoryEntry[], favorites:Favorite[], tab:"history"|"favorites", query:string}} input
|
|
* @returns {{tab:string, counts:{history:number, favorites:number}, hits:Hit[], empty:null|"history"|"favorites"|"query"}}
|
|
*/
|
|
export function panelState({ history, favorites, tab, query }) {
|
|
const source = tab === "favorites" ? favorites : history;
|
|
const hits = search(source, query);
|
|
let empty = null;
|
|
if (!source || source.length === 0) empty = tab === "favorites" ? "favorites" : "history";
|
|
else if (hits.length === 0) empty = "query";
|
|
return { tab, counts: { history: history.length, favorites: favorites.length }, hits, empty };
|
|
}
|
|
|
|
/**
|
|
* The row after a step up or down - past the end it comes round.
|
|
*
|
|
* @param {number} index
|
|
* @param {number} step
|
|
* @param {number} count
|
|
* @returns {number}
|
|
*/
|
|
export function moveIndex(index, step, count) {
|
|
if (count <= 0) return 0;
|
|
return (index + step + count) % count;
|
|
}
|
|
|
|
/** The other tab. */
|
|
export function otherTab(tab) {
|
|
return tab === "history" ? "favorites" : "history";
|
|
}
|