search.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /*
  2. search.js
  3. Front-end helpers for the Photo search feature. The reactive state and the
  4. Alpine methods live in photoListObject() (photo.js); this file only holds the
  5. pure helpers they delegate to, so the search logic stays out of the big
  6. component object.
  7. Backend endpoints used (all under system/ajgi/interface):
  8. Photo/backend/searchPhotos.js - run a search
  9. Photo/backend/searchSuggest.js - autocomplete suggestions
  10. Photo/backend/indexPhotos.js - incremental (auto) indexing
  11. Photo/backend/indexStatus.js - index statistics
  12. */
  13. // POST a JSON payload to a Photo AGI backend script and resolve with parsed JSON.
  14. function aoPhotoBackend(script, payload) {
  15. return fetch(ao_root + "system/ajgi/interface?script=" + script, {
  16. method: 'POST',
  17. cache: 'no-cache',
  18. headers: { 'Content-Type': 'application/json' },
  19. body: JSON.stringify(payload || {})
  20. }).then(function (resp) {
  21. return resp.json();
  22. });
  23. }
  24. // Map a suggestion type to a Semantic-UI icon class.
  25. function photoSuggestIcon(type) {
  26. switch (type) {
  27. case 'camera':
  28. return 'camera';
  29. case 'lens':
  30. return 'expand';
  31. case 'date':
  32. return 'calendar alternate outline';
  33. case 'type':
  34. return 'file image outline';
  35. case 'file':
  36. return 'image outline';
  37. case 'filter':
  38. return 'filter';
  39. case 'rating':
  40. return 'star';
  41. case 'folder':
  42. return 'folder outline';
  43. case 'shutter':
  44. return 'stopwatch';
  45. case 'size':
  46. return 'hdd outline';
  47. case 'time':
  48. return 'clock outline';
  49. default:
  50. return 'search';
  51. }
  52. }
  53. // The label of a preset token (shutter / time of day), or null
  54. function photoPresetTokenLabel(value) {
  55. var lists = [PHOTO_SHUTTER_PRESETS, PHOTO_TIME_PRESETS];
  56. for (var l = 0; l < lists.length; l++) {
  57. for (var i = 0; i < lists[l].length; i++) {
  58. if (lists[l][i].q === value) return T(lists[l][i].key, lists[l][i].en);
  59. }
  60. }
  61. return null;
  62. }
  63. // "1 MB", "500 KB": a size bound as typed (MB when it has no unit)
  64. function photoSizeBoundLabel(s) {
  65. var m = /^([0-9.]+)\s*(b|k|kb|m|mb|g|gb)?$/i.exec(('' + s).trim());
  66. if (!m) return '' + s;
  67. var u = (m[2] || 'mb').toLowerCase();
  68. var unit = u === 'b' ? 'B' : (u.charAt(0) === 'k' ? 'KB' : (u.charAt(0) === 'g' ? 'GB' : 'MB'));
  69. return m[1] + ' ' + unit;
  70. }
  71. // Label of a range value as typed after "key:" (">=1", "1/250..1/30", "5-10")
  72. function photoTypedRangeLabel(val, fmt) {
  73. fmt = fmt || function (v) { return v; };
  74. var s = ('' + val).trim(), m;
  75. if ((m = /^>=?\s*(.+)$/.exec(s))) return '≥ ' + fmt(m[1]);
  76. if ((m = /^<=?\s*(.+)$/.exec(s))) return '≤ ' + fmt(m[1]);
  77. if ((m = /^(.+?)\.\.(.+)$/.exec(s)) || (m = /^([^\-]+)-([^\-]+)$/.exec(s))) return fmt(m[1]) + ' – ' + fmt(m[2]);
  78. return fmt(s);
  79. }
  80. // Title-case a single word.
  81. function photoCap(s) {
  82. s = '' + s;
  83. return s.charAt(0).toUpperCase() + s.slice(1);
  84. }
  85. var PHOTO_MONTHS = ['January', 'February', 'March', 'April', 'May', 'June',
  86. 'July', 'August', 'September', 'October', 'November', 'December'];
  87. var PHOTO_MONTHS_ABBR = ['jan', 'feb', 'mar', 'apr', 'may', 'jun',
  88. 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
  89. function photoMonthNameToNum(s) {
  90. s = ('' + s).trim().toLowerCase();
  91. var i = PHOTO_MONTHS.findIndex(function (m) { return m.toLowerCase() === s; });
  92. if (i >= 0) return i + 1;
  93. i = PHOTO_MONTHS_ABBR.indexOf(s);
  94. if (i >= 0) return i + 1;
  95. var n = parseInt(s);
  96. if (!isNaN(n) && n >= 1 && n <= 12) return n;
  97. return null;
  98. }
  99. // Month name in the page's language, month 1-12 (the query keeps the number)
  100. function photoMonthName(month) {
  101. return new Date(2000, month - 1, 1).toLocaleDateString(localeTag() || 'en-us', { month: 'long' });
  102. }
  103. // Label of an orientation filter; the query value stays the English word
  104. function photoOrientationLabel(value) {
  105. var names = {
  106. landscape: T('orient/landscape', 'Landscape'),
  107. portrait: T('orient/portrait', 'Portrait'),
  108. square: T('orient/square', 'Square')
  109. };
  110. return names[('' + value).toLowerCase()] || photoCap(value);
  111. }
  112. // searchSuggest.js answers with English labels and hints. Translate those that
  113. // are not data (camera, lens and file names stay as they are), never the value.
  114. function photoLocalizeSuggestion(s) {
  115. var label = s.label, hint = s.hint, m;
  116. if (s.type === 'filter' && (label === 'Landscape' || label === 'Portrait')) {
  117. label = photoOrientationLabel(label);
  118. } else if (s.type === 'rating' && (m = /^(\d)★ & up$/.exec(label))) {
  119. label = T('suggest/andUp', '{n}★ & up', { n: m[1] });
  120. } else if (s.type === 'date' && (m = /month:(\d+)$/.exec(s.value))) {
  121. label = photoMonthName(parseInt(m[1], 10));
  122. } else if (s.type === 'shutter' || s.type === 'size' || s.type === 'time') {
  123. label = photoParseTagToken(s.value.split(' ').pop().replace(/^-/, '')).label;
  124. }
  125. if (/(^|\s)-\S/.test(s.value) && s.type !== 'file') {
  126. label = T('tag/not', 'Not {v}', { v: label });
  127. }
  128. if (hint === 'orientation') {
  129. hint = T('suggest/orientation', 'orientation');
  130. } else if (hint === 'file name') {
  131. hint = T('suggest/fileName', 'file name');
  132. } else if ((m = /^(\d+) photos$/.exec(hint))) {
  133. hint = T('suggest/photos', '{n} photos', { n: m[1] });
  134. }
  135. return { type: s.type, label: label, value: s.value, hint: hint };
  136. }
  137. // Turn a raw query token the user typed into a display tag {label, value, type}.
  138. // `value` is always a token that the backend query parser understands; `label`
  139. // is the friendly text shown on the chip; `type` drives the chip icon/colour.
  140. function photoParseTagToken(token) {
  141. token = ('' + token).trim();
  142. // "-token" leaves out what the token matches
  143. if (token.length > 1 && token.charAt(0) === '-') {
  144. var inner = photoParseTagToken(token.substring(1));
  145. return { label: T('tag/not', 'Not {v}', { v: inner.label }), value: '-' + inner.value, type: inner.type, neg: true };
  146. }
  147. var preset = photoPresetTokenLabel(token);
  148. if (preset) {
  149. return { label: preset, value: token, type: token.indexOf('hour:') === 0 ? 'time' : 'shutter' };
  150. }
  151. var lower = token.toLowerCase();
  152. var colon = token.indexOf(':');
  153. var key = colon > 0 ? lower.substring(0, colon) : '';
  154. var val = colon > 0 ? token.substring(colon + 1) : '';
  155. function unq(s) { return ('' + s).replace(/^"(.*)"$/, '$1'); }
  156. var fm = lower.match(/^f\/?(\d+(?:\.\d+)?)$/);
  157. if (colon < 0 && fm) return { label: 'f/' + fm[1], value: 'f/' + fm[1], type: 'filter' };
  158. var fmm = lower.match(/^(\d+(?:\.\d+)?)mm$/);
  159. if (colon < 0 && fmm) return { label: fmm[1] + 'mm', value: fmm[1] + 'mm', type: 'filter' };
  160. if (colon < 0 && lower.charAt(0) === '.') return { label: lower, value: lower, type: 'type' };
  161. if (colon < 0 && (lower === 'landscape' || lower === 'portrait' || lower === 'square'))
  162. return { label: photoOrientationLabel(lower), value: lower, type: 'filter' };
  163. if (colon < 0 && lower === 'raw') return { label: 'RAW', value: 'raw', type: 'type' };
  164. var mn = (colon < 0) ? photoMonthNameToNum(lower) : null;
  165. if (colon < 0 && mn && /^[a-z]+$/.test(lower)) return { label: photoMonthName(mn), value: 'month:' + mn, type: 'date' };
  166. if (colon < 0 && /^\d{4}$/.test(lower)) return { label: lower, value: lower, type: 'date' };
  167. if (colon > 0) {
  168. switch (key) {
  169. case 'iso': return { label: 'ISO ' + val, value: 'iso:' + val, type: 'filter' };
  170. case 'rating': case 'stars': case 'star': {
  171. var rv = unq(val).replace(/★|\*/g, '').trim();
  172. var label;
  173. var mge = rv.match(/^>=?\s*(\d)/);
  174. var mle = rv.match(/^<=?\s*(\d)/);
  175. if (mge) { label = '★ ≥ ' + mge[1]; }
  176. else if (mle) { label = '★ ≤ ' + mle[1]; }
  177. else if (/^\d$/.test(rv)) { label = rv + '★'; }
  178. else { label = T('tag/rating', 'Rating {v}', { v: rv }); }
  179. return { label: label, value: 'rating:' + rv, type: 'rating' };
  180. }
  181. case 'f': case 'aperture': case 'fnumber': return { label: 'f/' + val.replace(/^\//, ''), value: token, type: 'filter' };
  182. case 'focal': case 'fl': return { label: val.replace(/mm$/i, '') + 'mm', value: token, type: 'filter' };
  183. case 'mp': case 'megapixels': return { label: val + ' MP', value: token, type: 'filter' };
  184. case 'width': case 'w': return { label: T('tag/width', 'Width {v}', { v: val }), value: token, type: 'filter' };
  185. case 'height': case 'h': return { label: T('tag/height', 'Height {v}', { v: val }), value: token, type: 'filter' };
  186. case 'model': case 'camera': return { label: unq(val), value: token, type: 'camera' };
  187. case 'make': case 'brand': return { label: unq(val), value: token, type: 'camera' };
  188. case 'lens': return { label: unq(val), value: token, type: 'lens' };
  189. case 'ext': case 'type':
  190. return {
  191. label: unq(val).split(',').map(function (e) {
  192. e = e.trim().replace(/^\./, '');
  193. return e.toLowerCase() === 'raw' ? 'RAW' : '.' + e;
  194. }).join(', '),
  195. value: token, type: 'type'
  196. };
  197. case 'shutter': case 'exposure': case 'ss':
  198. return { label: photoTypedRangeLabel(unq(val), function (v) { return ('' + v).replace(/s$/i, '') + ' s'; }), value: token, type: 'shutter' };
  199. case 'size': case 'filesize':
  200. return { label: T('tag/size', 'Size {v}', { v: photoTypedRangeLabel(unq(val), photoSizeBoundLabel) }), value: token, type: 'size' };
  201. case 'hour': case 'time':
  202. return { label: photoTypedRangeLabel(unq(val), function (v) { return v + ':00'; }), value: token, type: 'time' };
  203. case 'folder': case 'in': {
  204. var fv = unq(val).replace(/\/+$/, '');
  205. return { label: fv.split('/').pop() || fv, value: token, type: 'folder' };
  206. }
  207. case 'name': case 'filename': return { label: unq(val), value: token, type: 'file' };
  208. case 'orientation': return { label: photoOrientationLabel(unq(val)), value: token, type: 'filter' };
  209. case 'month':
  210. var ms = ('' + val).split(',').map(function (x) { var n = photoMonthNameToNum(x); return n ? photoMonthName(n) : x; });
  211. return { label: ms.join(', '), value: token, type: 'date' };
  212. case 'taken': case 'date': case 'year': return { label: unq(val), value: token, type: 'date' };
  213. case 'modified': case 'mtime': return { label: T('tag/modified', 'Modified {v}', { v: unq(val) }), value: token, type: 'date' };
  214. case 'before': return { label: T('tag/before', 'Before {v}', { v: unq(val) }), value: token, type: 'date' };
  215. case 'after': return { label: T('tag/after', 'After {v}', { v: unq(val) }), value: token, type: 'date' };
  216. default: return { label: token, value: token, type: 'search' };
  217. }
  218. }
  219. return { label: token, value: token, type: 'search' };
  220. }
  221. // Whether the current input token can be committed as a chip on space:
  222. // non-empty, not waiting for a value ("iso:"), and not inside an open quote.
  223. function photoInputCommittable(s) {
  224. s = ('' + s).trim();
  225. if (s.length === 0) return false;
  226. if (s.charAt(s.length - 1) === ':') return false;
  227. if (((s.match(/"/g) || []).length) % 2 !== 0) return false;
  228. return true;
  229. }
  230. // Simple debounce used for the autocomplete fetch.
  231. function photoDebounce(fn, ms) {
  232. var timer = null;
  233. return function () {
  234. var ctx = this;
  235. var args = arguments;
  236. clearTimeout(timer);
  237. timer = setTimeout(function () {
  238. fn.apply(ctx, args);
  239. }, ms);
  240. };
  241. }