tracker
All repositories: gitoria
8.4 KB
// lib/search-helpers.hl — the search's text work (search.hl), also used by the people, the merge and the franchises: a text as// words (lower case, accents folded, punctuation a break), bucket keys, the query from the address (decoded only when it is// valid), the ranking of hits, years, and SLUGS ("Grey's Anatomy" → "Greys-Anatomy"). Mission 028: out of search.hl.import { hexDigits, textOr } from './util.hl'// ---- text → words ---------------------------------------------------------------------------------// lower case, apostrophes dropped ("Grey's" → "greys"), every other punctuation mark a word break, the common Latin// accents folded ("Amélie" → "amelie") — the same for the titles and the querystatic apostrophes = ["'", '’', '`', '´']static breaks = ['.', ',', ':', ';', '!', '?', '(', ')', '[', ']', '{', '}', '"', '“', '”', '„', '-', '–', '—', '/', '&', '+', '*', '#', '_', '|', '…', '·', '@', '=', '~', '<', '>']static folds = [['á', 'a'], ['à', 'a'], ['â', 'a'], ['ä', 'a'], ['ã', 'a'], ['å', 'a'], ['æ', 'ae'], ['ç', 'c'], ['é', 'e'], ['è', 'e'], ['ê', 'e'], ['ë', 'e'],['í', 'i'], ['ì', 'i'], ['î', 'i'], ['ï', 'i'], ['ñ', 'n'], ['ó', 'o'], ['ò', 'o'], ['ô', 'o'], ['ö', 'o'], ['õ', 'o'], ['ø', 'o'], ['œ', 'oe'],['ú', 'u'], ['ù', 'u'], ['û', 'u'], ['ü', 'u'], ['ý', 'y'], ['ÿ', 'y'], ['ß', 'ss'], ['š', 's'], ['ž', 'z'], ['č', 'c'], ['ł', 'l']]static normalize = (&s) => {if (s == null) { return '' }let t = ('' + s).toLowerCase()for (p of apostrophes) { if (t.includes(p)) { t = t.replaceAll(p, '') } }for (p of breaks) { if (t.includes(p)) { t = t.replaceAll(p, ' ') } }for (f of folds) { if (t.includes(f[0])) { t = t.replaceAll(f[0], f[1]) } }return t}static wordsOf = (&s) => {out = []for (w of normalize(&s).split(' ')) { if (w != '') { out.push(w) } }return out}static bucketKeys = (&words) => {seen = {}out = []for (w of words) {let n = 2while (n <= 3) {if (w.length >= n) {k = w.slice(0, n)if (seen[k] != true) { seen[k] = true out.push(k) }}n = n + 1}}return out}static tmdbKeyOf = (&type, &tmdbId) => { return (type == 'movie' ? 'movie:' : 'series:') + tmdbId }static yearWordOf = (&show) => {if (show.year != null) { return '' + show.year }if (show.release != null && hlTypeName(show.release) == 'String' && show.release.length >= 4) { return show.release.slice(0, 4) }return ''}// ---- the query as it comes in the address ------------------------------------------------------------// `/search/<text>`: a full page load hands the page the path segment already DECODED by the server (measured: `%2F` splits// the segment → 404, so the page never puts one in the address), a client-side navigation the RAW one — decoded here.// decodeURIComponent stops the request on a malformed one ('%zz', a broken UTF-8 run), so every %-run is checked first; a// bad one is taken literally. (A text that itself looks like an escape, '%41', is decoded twice on a reload — accepted.)static hexAt = (&s, &i) => {if (i + 3 > s.length) { return -1 }a = hexDigits.indexOf(s.slice(i + 1, i + 2).toLowerCase())b = hexDigits.indexOf(s.slice(i + 2, i + 3).toLowerCase())if (a < 0 || b < 0) { return -1 }return a * 16 + b}// the bytes of one run of %XX are valid UTF-8 (the rules decodeURIComponent applies)static utf8Ok = (&bytes) => {let i = 0while (i < bytes.length) {b = bytes[i]let need = 0let lo = 128let hi = 191if (b < 128) { need = 0 } else if (b >= 194 && b <= 223) { need = 1 } else if (b >= 224 && b <= 239) {need = 2if (b == 224) { lo = 160 }if (b == 237) { hi = 159 }} else if (b >= 240 && b <= 244) {need = 3if (b == 240) { lo = 144 }if (b == 244) { hi = 143 }} else { return false }if (i + need > bytes.length - 1) { return false }let k = 1while (k <= need) {c = bytes[i + k]if (k == 1 && (c < lo || c > hi)) { return false }if (k > 1 && (c < 128 || c > 191)) { return false }k = k + 1}i = i + need + 1}return true}static decodableUri = (&s) => {let i = 0while (i < s.length) {if (s.slice(i, i + 1) == '%') {run = []while (i < s.length && s.slice(i, i + 1) == '%') {v = hexAt(&s, &i)if (v < 0) { return false }run.push(v)i = i + 3}if (!utf8Ok(&run)) { return false }} else {i = i + 1}}return true}static maxQuery = 100static queryOfParam = (&raw) => {if (raw == null || hlTypeName(raw) != 'String' || raw == '') { return '' }t = raw.includes('%') && decodableUri(&raw) ? decodeURIComponent(raw) : rawreturn t.length > maxQuery ? t.slice(0, maxQuery) : t}// lower is better: the whole name (0), the name starts with the query (1), its first word does (2), anything else (3);// then the shorter namestatic scoreOf = (&e, &qw, &qtext) => {if (e.text == qtext) { return 0 }if (e.text.startsWith(qtext)) { return 1 }if (e.words[0].startsWith(qw[0])) { return 2 }return 3}// an entry's words from its stored text (search.hl keeps no words array per entry, mission T17)static entryWords = (&text) => { return text.split(' ') }// matchesAll on a stored entry: a cheap necessary test first (a word that starts with a query word contains it), then the wordsstatic matchesText = (&text, &qw) => {for (q of qw) {if (!text.includes(q)) { return false }}return matchesAll({ words = entryWords(&text) }, &qw)}// GC1: matchesText without a split of the entry: the text is its words joined by ONE space (search.hl addEntry; no empty word), so "a word// starts with q" is "the text starts with q, or holds ' ' + q" (`qsp` = the query words each with the space in front, made once per search).// The same answer as matchesText, and no word list, no map per candidate (a common word has ~100 k candidates)static matchesSpaced = (&text, &qw, &qsp) => {let k = 0while (k < qw.length) {if (!(text.startsWith(qw[k]) || text.includes(qsp[k]))) { return false }k = k + 1}return true}// the score of scoreOf from the stored text alone (the first word starts with the first query word = the text does, the query word// has no space)static scoreText = (&text, &qtext, &q0) => {if (text == qtext) { return 0 }if (text.startsWith(qtext)) { return 1 }if (text.startsWith(q0)) { return 2 }return 3}// would this hit be kept by insertTop on a FULL list? (strictly better than the last one, the list being in order)static beatsLast = (score, len, tie, &last) => {return score < last.score || (score == last.score && (len < last.len || (len == last.len && tie < last.tie)))}static matchesAll = (&e, &qw) => {for (q of qw) {let hit = falsefor (w of e.words) { if (!hit && w.startsWith(q)) { hit = true } }if (!hit) { return false }}return true}// keeps the best `limit` of { score, len, tie, i } in order (hand-written: no list sort(), hybriel#1)static insertTop = (&top, &item, &limit) => {out = []let inserted = falsefor (x of top) {if (!inserted && (item.score < x.score || (item.score == x.score && (item.len < x.len || (item.len == x.len && item.tie < x.tie))))) { out.push(item) inserted = true }if (out.length < limit) { out.push(x) }}if (!inserted && out.length < limit) { out.push(item) }return out}static yearOfDate = (&d) => { return textOr(&d) != null && d.length >= 4 ? d.slice(0, 4) : '' }// ---- slugs ------------------------------------------------------------------------------------------static slugChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'// the slug of a text without the "in use" check — `fallback` when it has no Latin letter at all (people.hl personSlugOf// uses it for new people, tracker#26)static slugBaseOf = (&title, fallback) => {t = normalizeSlugText(&title)let out = ''let dash = falselet i = 0while (i < t.length) {c = t.slice(i, i + 1)if (slugChars.includes(c)) {if (dash && out != '') { out = out + '-' }out = out + cdash = false} else {dash = true}i = i + 1}if (out == '') { out = fallback }if (out.length > 80) { out = out.slice(0, 80) }return out}// the accents folded (keeping the case) and apostrophes dropped, so "Grey's Anatomy" → "Greys-Anatomy"static normalizeSlugText = (&s) => {let t = '' + sfor (p of apostrophes) { if (t.includes(p)) { t = t.replaceAll(p, '') } }for (f of folds) {if (t.includes(f[0])) { t = t.replaceAll(f[0], f[1]) }up = f[0].toUpperCase()if (up != f[0] && t.includes(up)) { t = t.replaceAll(up, f[1].toUpperCase()) }}return t}
Branches
Latest commits
- d049b8b8Log: HM50 live, #52 donemre
- 6d05fa37Log: HM50 Part A mergedmre
- 1c7dab74HM50: the shell reads the framework's online state, netProbe removed (tracker#55)mre
- e8b91697HM50: search address follows the text via navigate(path, replace = true) (tracker#52)mre
- 6fe1896cHM50: re-vendor Hybriel set day50 (source 0ae38232, bin d3ef9d16)mre
- 2f391aa9Log: HM50 startedmre
- 4b59c03dHM50 mission: doc pathmre
- ed526d67HM50 missionmre
- 2f986ca3Log: RT50 passmre
- 1c4715a4RT50 mission: day50 repro retestmre
- 57d1c0dcLog: day50 retest requestmre
- 60b1f419Log: Anton #336 result, wake checkmre
- 919a18aalog: scratchmre
- 6b504440status tidymre
- 9332bd10log: DP70 livemre
- be11daa0DP70 brief fixmre
- 886a7028DP70 brief, HM67 mergedmre
- b41cdd6dMerge hm67-searchids: packed search IDsmre
- 385904eaReport HM67 matched heap measurements and gate proofmre
- e5c9b659Pack retained search IDs into UTF-8 bytesmre