gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2156cc7f2156cc7flog: HM54 reviewmre2156cc7f/lib/search-helpers.hl

8.4 KB

  1. // lib/search-helpers.hl — the search's text work (search.hl), also used by the people, the merge and the franchises: a text as
  2. // words (lower case, accents folded, punctuation a break), bucket keys, the query from the address (decoded only when it is
  3. // valid), the ranking of hits, years, and SLUGS ("Grey's Anatomy" → "Greys-Anatomy"). Mission 028: out of search.hl.
  4. import { hexDigits, textOr } from './util.hl'
  5. // ---- text → words ---------------------------------------------------------------------------------
  6. // lower case, apostrophes dropped ("Grey's" → "greys"), every other punctuation mark a word break, the common Latin
  7. // accents folded ("Amélie" → "amelie") — the same for the titles and the query
  8. static apostrophes = ["'", '’', '`', '´']
  9. static breaks = ['.', ',', ':', ';', '!', '?', '(', ')', '[', ']', '{', '}', '"', '“', '”', '„', '-', '–', '—', '/', '&', '+', '*', '#', '_', '|', '…', '·', '@', '=', '~', '<', '>']
  10. static folds = [['á', 'a'], ['à', 'a'], ['â', 'a'], ['ä', 'a'], ['ã', 'a'], ['å', 'a'], ['æ', 'ae'], ['ç', 'c'], ['é', 'e'], ['è', 'e'], ['ê', 'e'], ['ë', 'e'],
  11. ['í', 'i'], ['ì', 'i'], ['î', 'i'], ['ï', 'i'], ['ñ', 'n'], ['ó', 'o'], ['ò', 'o'], ['ô', 'o'], ['ö', 'o'], ['õ', 'o'], ['ø', 'o'], ['œ', 'oe'],
  12. ['ú', 'u'], ['ù', 'u'], ['û', 'u'], ['ü', 'u'], ['ý', 'y'], ['ÿ', 'y'], ['ß', 'ss'], ['š', 's'], ['ž', 'z'], ['č', 'c'], ['ł', 'l']]
  13. static normalize = (&s) => {
  14. if (s == null) { return '' }
  15. let t = ('' + s).toLowerCase()
  16. for (p of apostrophes) { if (t.includes(p)) { t = t.replaceAll(p, '') } }
  17. for (p of breaks) { if (t.includes(p)) { t = t.replaceAll(p, ' ') } }
  18. for (f of folds) { if (t.includes(f[0])) { t = t.replaceAll(f[0], f[1]) } }
  19. return t
  20. }
  21. static wordsOf = (&s) => {
  22. out = []
  23. for (w of normalize(&s).split(' ')) { if (w != '') { out.push(w) } }
  24. return out
  25. }
  26. static bucketKeys = (&words) => {
  27. seen = {}
  28. out = []
  29. for (w of words) {
  30. let n = 2
  31. while (n <= 3) {
  32. if (w.length >= n) {
  33. let k = w.slice(0, n)
  34. if (seen[k] != true) { seen[k] = true out.push(k) }
  35. }
  36. n = n + 1
  37. }
  38. }
  39. return out
  40. }
  41. static tmdbKeyOf = (&type, &tmdbId) => { return (type == 'movie' ? 'movie:' : 'series:') + tmdbId }
  42. static yearWordOf = (&show) => {
  43. if (show.year != null) { return '' + show.year }
  44. if (show.release != null && hlTypeName(show.release) == 'String' && show.release.length >= 4) { return show.release.slice(0, 4) }
  45. return ''
  46. }
  47. // ---- the query as it comes in the address ------------------------------------------------------------
  48. // `/search/<text>`: a full page load hands the page the path segment already DECODED by the server (measured: `%2F` splits
  49. // the segment → 404, so the page never puts one in the address), a client-side navigation the RAW one — decoded here.
  50. // decodeURIComponent stops the request on a malformed one ('%zz', a broken UTF-8 run), so every %-run is checked first; a
  51. // bad one is taken literally. (A text that itself looks like an escape, '%41', is decoded twice on a reload — accepted.)
  52. static hexAt = (&s, &i) => {
  53. if (i + 3 > s.length) { return -1 }
  54. a = hexDigits.indexOf(s.slice(i + 1, i + 2).toLowerCase())
  55. b = hexDigits.indexOf(s.slice(i + 2, i + 3).toLowerCase())
  56. if (a < 0 || b < 0) { return -1 }
  57. return a * 16 + b
  58. }
  59. // the bytes of one run of %XX are valid UTF-8 (the rules decodeURIComponent applies)
  60. static utf8Ok = (&bytes) => {
  61. let i = 0
  62. while (i < bytes.length) {
  63. let b = bytes[i]
  64. let need = 0
  65. let lo = 128
  66. let hi = 191
  67. if (b < 128) { need = 0 } else if (b >= 194 && b <= 223) { need = 1 } else if (b >= 224 && b <= 239) {
  68. need = 2
  69. if (b == 224) { lo = 160 }
  70. if (b == 237) { hi = 159 }
  71. } else if (b >= 240 && b <= 244) {
  72. need = 3
  73. if (b == 240) { lo = 144 }
  74. if (b == 244) { hi = 143 }
  75. } else { return false }
  76. if (i + need > bytes.length - 1) { return false }
  77. let k = 1
  78. while (k <= need) {
  79. let c = bytes[i + k]
  80. if (k == 1 && (c < lo || c > hi)) { return false }
  81. if (k > 1 && (c < 128 || c > 191)) { return false }
  82. k = k + 1
  83. }
  84. i = i + need + 1
  85. }
  86. return true
  87. }
  88. static decodableUri = (&s) => {
  89. let i = 0
  90. while (i < s.length) {
  91. if (s.slice(i, i + 1) == '%') {
  92. let run = []
  93. while (i < s.length && s.slice(i, i + 1) == '%') {
  94. let v = hexAt(&s, &i)
  95. if (v < 0) { return false }
  96. run.push(v)
  97. i = i + 3
  98. }
  99. if (!utf8Ok(&run)) { return false }
  100. } else {
  101. i = i + 1
  102. }
  103. }
  104. return true
  105. }
  106. static maxQuery = 100
  107. static queryOfParam = (&raw) => {
  108. if (raw == null || hlTypeName(raw) != 'String' || raw == '') { return '' }
  109. t = raw.includes('%') && decodableUri(&raw) ? decodeURIComponent(raw) : raw
  110. return t.length > maxQuery ? t.slice(0, maxQuery) : t
  111. }
  112. // lower is better: the whole name (0), the name starts with the query (1), its first word does (2), anything else (3);
  113. // then the shorter name
  114. static scoreOf = (&e, &qw, &qtext) => {
  115. if (e.text == qtext) { return 0 }
  116. if (e.text.startsWith(qtext)) { return 1 }
  117. if (e.words[0].startsWith(qw[0])) { return 2 }
  118. return 3
  119. }
  120. // an entry's words from its stored text (search.hl keeps no words array per entry, mission T17)
  121. static entryWords = (&text) => { return text.split(' ') }
  122. // matchesAll on a stored entry: a cheap necessary test first (a word that starts with a query word contains it), then the words
  123. static matchesText = (&text, &qw) => {
  124. for (q of qw) {
  125. if (!text.includes(q)) { return false }
  126. }
  127. return matchesAll({ words = entryWords(&text) }, &qw)
  128. }
  129. // 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
  130. // 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).
  131. // The same answer as matchesText, and no word list, no map per candidate (a common word has ~100 k candidates)
  132. static matchesSpaced = (&text, &qw, &qsp) => {
  133. let k = 0
  134. while (k < qw.length) {
  135. if (!(text.startsWith(qw[k]) || text.includes(qsp[k]))) { return false }
  136. k = k + 1
  137. }
  138. return true
  139. }
  140. // the score of scoreOf from the stored text alone (the first word starts with the first query word = the text does, the query word
  141. // has no space)
  142. static scoreText = (&text, &qtext, &q0) => {
  143. if (text == qtext) { return 0 }
  144. if (text.startsWith(qtext)) { return 1 }
  145. if (text.startsWith(q0)) { return 2 }
  146. return 3
  147. }
  148. // would this hit be kept by insertTop on a FULL list? (strictly better than the last one, the list being in order)
  149. static beatsLast = (score, len, tie, &last) => {
  150. return score < last.score || (score == last.score && (len < last.len || (len == last.len && tie < last.tie)))
  151. }
  152. static matchesAll = (&e, &qw) => {
  153. for (q of qw) {
  154. let hit = false
  155. for (w of e.words) { if (!hit && w.startsWith(q)) { hit = true } }
  156. if (!hit) { return false }
  157. }
  158. return true
  159. }
  160. // keeps the best `limit` of { score, len, tie, i } in order (hand-written: no list sort(), hybriel#1)
  161. static insertTop = (&top, &item, &limit) => {
  162. out = []
  163. let inserted = false
  164. for (x of top) {
  165. 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 }
  166. if (out.length < limit) { out.push(x) }
  167. }
  168. if (!inserted && out.length < limit) { out.push(item) }
  169. return out
  170. }
  171. static yearOfDate = (&d) => { return textOr(&d) != null && d.length >= 4 ? d.slice(0, 4) : '' }
  172. // ---- slugs ------------------------------------------------------------------------------------------
  173. static slugChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  174. // the slug of a text without the "in use" check — `fallback` when it has no Latin letter at all (people.hl personSlugOf
  175. // uses it for new people, tracker#26)
  176. static slugBaseOf = (&title, fallback) => {
  177. t = normalizeSlugText(&title)
  178. let out = ''
  179. let dash = false
  180. let i = 0
  181. while (i < t.length) {
  182. let c = t.slice(i, i + 1)
  183. if (slugChars.includes(c)) {
  184. if (dash && out != '') { out = out + '-' }
  185. out = out + c
  186. dash = false
  187. } else {
  188. dash = true
  189. }
  190. i = i + 1
  191. }
  192. if (out == '') { out = fallback }
  193. if (out.length > 80) { out = out.slice(0, 80) }
  194. return out
  195. }
  196. // the accents folded (keeping the case) and apostrophes dropped, so "Grey's Anatomy" → "Greys-Anatomy"
  197. static normalizeSlugText = (&s) => {
  198. let t = '' + s
  199. for (p of apostrophes) { if (t.includes(p)) { t = t.replaceAll(p, '') } }
  200. for (f of folds) {
  201. if (t.includes(f[0])) { t = t.replaceAll(f[0], f[1]) }
  202. let up = f[0].toUpperCase()
  203. if (up != f[0] && t.includes(up)) { t = t.replaceAll(up, f[1].toUpperCase()) }
  204. }
  205. return t
  206. }

Branches

Latest commits

  • 2156cc7flog: HM54 reviewmre
  • 9fb82efclog: HM54 gap, fill continuesmre
  • b632eb8dlog: HM53 done, HM54 startedmre
  • 3356fcfclog: #52 blocked, HM53 startedmre
  • 833dcfc9Merge hm52-search: report only, tracker#52 blocked by framework gapmre
  • 73010cc0HM52: report replace-navigation search draft regressionmre
  • 1742e92bstatus: DP64 and HM52 runningmre
  • 29ad5b58log: #64 merged, DP64 and HM52 startedmre
  • fafddbf9Merge hm64-catalog: tracker#64 catalog from packed entriesmre
  • b2e2206dlog: #63 livemre
  • 5831e0e0log: HM64 donemre
  • 4042b923Flatten catalog membership rows into paired slotsmre
  • ea8a759elog: #61 #62 live, DP63 and HM64 startedmre
  • 40439456Merge hm63-searchtext: tracker#63 packed search textmre
  • b7e6b48ePack normalized search text behind numeric offsetsmre
  • b35f53e1log: DP62 stale runtime decisionmre
  • f9593602log: Apollo deploy rule correctionmre
  • 3c95f7f3log: DP62 and HM63 startedmre
  • 9c4397c9mission HM63mre
  • 8dfe42c8mission DP62mre