@internetarchive/collection-browser 1.14.17-beta.5 → 1.14.18-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. package/.editorconfig +29 -29
  2. package/.husky/pre-commit +4 -4
  3. package/LICENSE +661 -661
  4. package/README.md +83 -83
  5. package/dist/index.d.ts +12 -11
  6. package/dist/index.js +12 -11
  7. package/dist/index.js.map +1 -1
  8. package/dist/src/app-root.d.ts +83 -83
  9. package/dist/src/app-root.js +438 -489
  10. package/dist/src/app-root.js.map +1 -1
  11. package/dist/src/assets/img/icons/arrow-left.d.ts +2 -2
  12. package/dist/src/assets/img/icons/arrow-left.js +2 -2
  13. package/dist/src/assets/img/icons/arrow-right.d.ts +2 -2
  14. package/dist/src/assets/img/icons/arrow-right.js +2 -2
  15. package/dist/src/assets/img/icons/chevron.d.ts +2 -2
  16. package/dist/src/assets/img/icons/chevron.js +2 -2
  17. package/dist/src/assets/img/icons/contract.d.ts +2 -2
  18. package/dist/src/assets/img/icons/contract.js +2 -2
  19. package/dist/src/assets/img/icons/empty-query.d.ts +2 -2
  20. package/dist/src/assets/img/icons/empty-query.js +2 -2
  21. package/dist/src/assets/img/icons/expand.d.ts +2 -2
  22. package/dist/src/assets/img/icons/expand.js +2 -2
  23. package/dist/src/assets/img/icons/eye-closed.d.ts +2 -2
  24. package/dist/src/assets/img/icons/eye-closed.js +2 -2
  25. package/dist/src/assets/img/icons/eye.d.ts +2 -2
  26. package/dist/src/assets/img/icons/eye.js +2 -2
  27. package/dist/src/assets/img/icons/favorite-filled.d.ts +1 -1
  28. package/dist/src/assets/img/icons/favorite-filled.js +2 -2
  29. package/dist/src/assets/img/icons/login-required.d.ts +1 -1
  30. package/dist/src/assets/img/icons/login-required.js +2 -2
  31. package/dist/src/assets/img/icons/mediatype/account.d.ts +1 -1
  32. package/dist/src/assets/img/icons/mediatype/account.js +2 -2
  33. package/dist/src/assets/img/icons/mediatype/audio.d.ts +1 -1
  34. package/dist/src/assets/img/icons/mediatype/audio.js +2 -2
  35. package/dist/src/assets/img/icons/mediatype/collection.d.ts +1 -1
  36. package/dist/src/assets/img/icons/mediatype/collection.js +2 -2
  37. package/dist/src/assets/img/icons/mediatype/data.d.ts +1 -1
  38. package/dist/src/assets/img/icons/mediatype/data.js +2 -2
  39. package/dist/src/assets/img/icons/mediatype/etree.d.ts +1 -1
  40. package/dist/src/assets/img/icons/mediatype/etree.js +2 -2
  41. package/dist/src/assets/img/icons/mediatype/film.d.ts +1 -1
  42. package/dist/src/assets/img/icons/mediatype/film.js +2 -2
  43. package/dist/src/assets/img/icons/mediatype/images.d.ts +1 -1
  44. package/dist/src/assets/img/icons/mediatype/images.js +2 -2
  45. package/dist/src/assets/img/icons/mediatype/radio.d.ts +1 -1
  46. package/dist/src/assets/img/icons/mediatype/radio.js +2 -2
  47. package/dist/src/assets/img/icons/mediatype/search.d.ts +1 -1
  48. package/dist/src/assets/img/icons/mediatype/search.js +2 -2
  49. package/dist/src/assets/img/icons/mediatype/software.d.ts +1 -1
  50. package/dist/src/assets/img/icons/mediatype/software.js +2 -2
  51. package/dist/src/assets/img/icons/mediatype/texts.d.ts +1 -1
  52. package/dist/src/assets/img/icons/mediatype/texts.js +2 -2
  53. package/dist/src/assets/img/icons/mediatype/tv.d.ts +1 -1
  54. package/dist/src/assets/img/icons/mediatype/tv.js +2 -2
  55. package/dist/src/assets/img/icons/mediatype/video.d.ts +1 -1
  56. package/dist/src/assets/img/icons/mediatype/video.js +2 -2
  57. package/dist/src/assets/img/icons/mediatype/web.d.ts +1 -1
  58. package/dist/src/assets/img/icons/mediatype/web.js +2 -2
  59. package/dist/src/assets/img/icons/null-result.d.ts +2 -2
  60. package/dist/src/assets/img/icons/null-result.js +2 -2
  61. package/dist/src/assets/img/icons/restricted.d.ts +1 -1
  62. package/dist/src/assets/img/icons/restricted.js +2 -2
  63. package/dist/src/assets/img/icons/reviews.d.ts +1 -1
  64. package/dist/src/assets/img/icons/reviews.js +2 -2
  65. package/dist/src/assets/img/icons/upload.d.ts +1 -1
  66. package/dist/src/assets/img/icons/upload.js +2 -2
  67. package/dist/src/assets/img/icons/views.d.ts +1 -1
  68. package/dist/src/assets/img/icons/views.js +2 -2
  69. package/dist/src/circular-activity-indicator.d.ts +5 -5
  70. package/dist/src/circular-activity-indicator.js +17 -17
  71. package/dist/src/collection-browser.d.ts +384 -406
  72. package/dist/src/collection-browser.js +1342 -1363
  73. package/dist/src/collection-browser.js.map +1 -1
  74. package/dist/src/collection-facets/facet-row.d.ts +30 -30
  75. package/dist/src/collection-facets/facet-row.js +114 -114
  76. package/dist/src/collection-facets/facet-tombstone-row.d.ts +5 -5
  77. package/dist/src/collection-facets/facet-tombstone-row.js +15 -15
  78. package/dist/src/collection-facets/facets-template.d.ts +17 -17
  79. package/dist/src/collection-facets/facets-template.js +114 -114
  80. package/dist/src/collection-facets/more-facets-content.d.ts +70 -70
  81. package/dist/src/collection-facets/more-facets-content.js +354 -369
  82. package/dist/src/collection-facets/more-facets-content.js.map +1 -1
  83. package/dist/src/collection-facets/more-facets-pagination.d.ts +36 -36
  84. package/dist/src/collection-facets/more-facets-pagination.js +196 -196
  85. package/dist/src/collection-facets/toggle-switch.d.ts +41 -41
  86. package/dist/src/collection-facets/toggle-switch.js +94 -94
  87. package/dist/src/collection-facets.d.ts +103 -103
  88. package/dist/src/collection-facets.js +513 -510
  89. package/dist/src/collection-facets.js.map +1 -1
  90. package/dist/src/data-source/collection-browser-data-source-interface.d.ts +217 -0
  91. package/dist/src/data-source/collection-browser-data-source-interface.js +2 -0
  92. package/dist/src/data-source/collection-browser-data-source-interface.js.map +1 -0
  93. package/dist/src/data-source/collection-browser-data-source.d.ts +352 -434
  94. package/dist/src/data-source/collection-browser-data-source.js +911 -800
  95. package/dist/src/data-source/collection-browser-data-source.js.map +1 -1
  96. package/dist/src/data-source/collection-browser-query-state.d.ts +43 -0
  97. package/dist/src/data-source/collection-browser-query-state.js +2 -0
  98. package/dist/src/data-source/collection-browser-query-state.js.map +1 -0
  99. package/dist/src/data-source/models.d.ts +28 -62
  100. package/dist/src/data-source/models.js +8 -1
  101. package/dist/src/data-source/models.js.map +1 -1
  102. package/dist/src/empty-placeholder.d.ts +23 -23
  103. package/dist/src/empty-placeholder.js +74 -74
  104. package/dist/src/expanded-date-picker.d.ts +43 -43
  105. package/dist/src/expanded-date-picker.js +109 -109
  106. package/dist/src/language-code-handler/language-code-handler.d.ts +37 -37
  107. package/dist/src/language-code-handler/language-code-handler.js +26 -26
  108. package/dist/src/language-code-handler/language-code-mapping.d.ts +1 -1
  109. package/dist/src/language-code-handler/language-code-mapping.js +562 -562
  110. package/dist/src/manage/manage-bar.d.ts +26 -26
  111. package/dist/src/manage/manage-bar.js +53 -53
  112. package/dist/src/manage/manage-bar.js.map +1 -1
  113. package/dist/src/mediatype/mediatype-config.d.ts +3 -3
  114. package/dist/src/mediatype/mediatype-config.js +91 -91
  115. package/dist/src/models.d.ts +197 -180
  116. package/dist/src/models.js +380 -269
  117. package/dist/src/models.js.map +1 -1
  118. package/dist/src/restoration-state-handler.d.ts +70 -70
  119. package/dist/src/restoration-state-handler.js +355 -355
  120. package/dist/src/sort-filter-bar/alpha-bar-tooltip.d.ts +6 -6
  121. package/dist/src/sort-filter-bar/alpha-bar-tooltip.js +24 -24
  122. package/dist/src/sort-filter-bar/alpha-bar.d.ts +21 -21
  123. package/dist/src/sort-filter-bar/alpha-bar.js +128 -128
  124. package/dist/src/sort-filter-bar/img/compact.d.ts +1 -1
  125. package/dist/src/sort-filter-bar/img/compact.js +2 -2
  126. package/dist/src/sort-filter-bar/img/list.d.ts +1 -1
  127. package/dist/src/sort-filter-bar/img/list.js +2 -2
  128. package/dist/src/sort-filter-bar/img/sort-toggle-disabled.d.ts +1 -1
  129. package/dist/src/sort-filter-bar/img/sort-toggle-disabled.js +2 -2
  130. package/dist/src/sort-filter-bar/img/sort-toggle-down.d.ts +1 -1
  131. package/dist/src/sort-filter-bar/img/sort-toggle-down.js +2 -2
  132. package/dist/src/sort-filter-bar/img/sort-toggle-up.d.ts +1 -1
  133. package/dist/src/sort-filter-bar/img/sort-toggle-up.js +2 -2
  134. package/dist/src/sort-filter-bar/img/sort-triangle.d.ts +1 -1
  135. package/dist/src/sort-filter-bar/img/sort-triangle.js +2 -2
  136. package/dist/src/sort-filter-bar/img/tile.d.ts +1 -1
  137. package/dist/src/sort-filter-bar/img/tile.js +2 -2
  138. package/dist/src/sort-filter-bar/sort-filter-bar.d.ts +210 -210
  139. package/dist/src/sort-filter-bar/sort-filter-bar.js +653 -652
  140. package/dist/src/sort-filter-bar/sort-filter-bar.js.map +1 -1
  141. package/dist/src/styles/item-image-styles.d.ts +8 -8
  142. package/dist/src/styles/item-image-styles.js +9 -9
  143. package/dist/src/styles/sr-only.d.ts +1 -1
  144. package/dist/src/styles/sr-only.js +2 -2
  145. package/dist/src/tiles/base-tile-component.d.ts +19 -19
  146. package/dist/src/tiles/base-tile-component.js +63 -63
  147. package/dist/src/tiles/collection-browser-loading-tile.d.ts +5 -5
  148. package/dist/src/tiles/collection-browser-loading-tile.js +15 -15
  149. package/dist/src/tiles/grid/account-tile.d.ts +18 -18
  150. package/dist/src/tiles/grid/account-tile.js +72 -72
  151. package/dist/src/tiles/grid/collection-tile.d.ts +15 -15
  152. package/dist/src/tiles/grid/collection-tile.js +80 -80
  153. package/dist/src/tiles/grid/item-tile.d.ts +28 -27
  154. package/dist/src/tiles/grid/item-tile.js +162 -135
  155. package/dist/src/tiles/grid/item-tile.js.map +1 -1
  156. package/dist/src/tiles/grid/search-tile.d.ts +10 -10
  157. package/dist/src/tiles/grid/search-tile.js +51 -51
  158. package/dist/src/tiles/grid/styles/tile-grid-shared-styles.d.ts +1 -1
  159. package/dist/src/tiles/grid/styles/tile-grid-shared-styles.js +8 -8
  160. package/dist/src/tiles/grid/tile-stats.d.ts +11 -11
  161. package/dist/src/tiles/grid/tile-stats.js +58 -53
  162. package/dist/src/tiles/grid/tile-stats.js.map +1 -1
  163. package/dist/src/tiles/hover/hover-pane-controller.d.ts +219 -219
  164. package/dist/src/tiles/hover/hover-pane-controller.js +352 -352
  165. package/dist/src/tiles/hover/tile-hover-pane.d.ts +15 -15
  166. package/dist/src/tiles/hover/tile-hover-pane.js +38 -38
  167. package/dist/src/tiles/image-block.d.ts +17 -17
  168. package/dist/src/tiles/image-block.js +73 -73
  169. package/dist/src/tiles/item-image.d.ts +39 -36
  170. package/dist/src/tiles/item-image.js +155 -127
  171. package/dist/src/tiles/item-image.js.map +1 -1
  172. package/dist/src/tiles/list/tile-list-compact-header.d.ts +6 -6
  173. package/dist/src/tiles/list/tile-list-compact-header.js +38 -38
  174. package/dist/src/tiles/list/tile-list-compact.d.ts +15 -15
  175. package/dist/src/tiles/list/tile-list-compact.js +115 -115
  176. package/dist/src/tiles/list/tile-list-compact.js.map +1 -1
  177. package/dist/src/tiles/list/tile-list.d.ts +47 -46
  178. package/dist/src/tiles/list/tile-list.js +327 -296
  179. package/dist/src/tiles/list/tile-list.js.map +1 -1
  180. package/dist/src/tiles/mediatype-icon.d.ts +9 -9
  181. package/dist/src/tiles/mediatype-icon.js +47 -47
  182. package/dist/src/tiles/overlay/icon-overlay.d.ts +10 -10
  183. package/dist/src/tiles/overlay/icon-overlay.js +40 -40
  184. package/dist/src/tiles/overlay/icon-text-overlay.d.ts +9 -9
  185. package/dist/src/tiles/overlay/icon-text-overlay.js +38 -38
  186. package/dist/src/tiles/overlay/text-overlay.d.ts +10 -10
  187. package/dist/src/tiles/overlay/text-overlay.js +42 -42
  188. package/dist/src/tiles/text-snippet-block.d.ts +27 -27
  189. package/dist/src/tiles/text-snippet-block.js +73 -73
  190. package/dist/src/tiles/tile-dispatcher.d.ts +64 -64
  191. package/dist/src/tiles/tile-dispatcher.js +232 -231
  192. package/dist/src/tiles/tile-dispatcher.js.map +1 -1
  193. package/dist/src/tiles/tile-display-value-provider.d.ts +47 -43
  194. package/dist/src/tiles/tile-display-value-provider.js +94 -80
  195. package/dist/src/tiles/tile-display-value-provider.js.map +1 -1
  196. package/dist/src/utils/analytics-events.d.ts +25 -25
  197. package/dist/src/utils/analytics-events.js +27 -27
  198. package/dist/src/utils/array-equals.d.ts +4 -4
  199. package/dist/src/utils/array-equals.js +10 -10
  200. package/dist/src/utils/collapse-repeated-quotes.d.ts +11 -0
  201. package/dist/src/utils/collapse-repeated-quotes.js +14 -0
  202. package/dist/src/utils/collapse-repeated-quotes.js.map +1 -0
  203. package/dist/src/utils/format-count.d.ts +7 -7
  204. package/dist/src/utils/format-count.js +76 -76
  205. package/dist/src/utils/format-date.d.ts +2 -2
  206. package/dist/src/utils/format-date.js +25 -25
  207. package/dist/src/utils/format-unit-size.d.ts +2 -2
  208. package/dist/src/utils/format-unit-size.js +33 -33
  209. package/dist/src/utils/local-date-from-utc.d.ts +9 -9
  210. package/dist/src/utils/local-date-from-utc.js +15 -15
  211. package/dist/src/utils/log.d.ts +7 -0
  212. package/dist/src/utils/log.js +16 -0
  213. package/dist/src/utils/log.js.map +1 -0
  214. package/dist/src/utils/resolve-mediatype.d.ts +8 -0
  215. package/dist/src/utils/resolve-mediatype.js +24 -0
  216. package/dist/src/utils/resolve-mediatype.js.map +1 -0
  217. package/dist/src/utils/sha1.d.ts +2 -2
  218. package/dist/src/utils/sha1.js +8 -8
  219. package/dist/test/collection-browser.test.d.ts +1 -1
  220. package/dist/test/collection-browser.test.js +1211 -1149
  221. package/dist/test/collection-browser.test.js.map +1 -1
  222. package/dist/test/collection-facets/facet-row.test.d.ts +1 -1
  223. package/dist/test/collection-facets/facet-row.test.js +203 -203
  224. package/dist/test/collection-facets/facets-template.test.d.ts +1 -1
  225. package/dist/test/collection-facets/facets-template.test.js +105 -105
  226. package/dist/test/collection-facets/more-facets-content.test.d.ts +1 -1
  227. package/dist/test/collection-facets/more-facets-content.test.js +133 -133
  228. package/dist/test/collection-facets/more-facets-content.test.js.map +1 -1
  229. package/dist/test/collection-facets/more-facets-pagination.test.d.ts +1 -1
  230. package/dist/test/collection-facets/more-facets-pagination.test.js +117 -117
  231. package/dist/test/collection-facets/toggle-switch.test.d.ts +1 -1
  232. package/dist/test/collection-facets/toggle-switch.test.js +73 -73
  233. package/dist/test/collection-facets.test.d.ts +2 -2
  234. package/dist/test/collection-facets.test.js +653 -648
  235. package/dist/test/collection-facets.test.js.map +1 -1
  236. package/dist/test/data-source/collection-browser-data-source.test.d.ts +1 -0
  237. package/dist/test/data-source/collection-browser-data-source.test.js +80 -0
  238. package/dist/test/data-source/collection-browser-data-source.test.js.map +1 -0
  239. package/dist/test/empty-placeholder.test.d.ts +1 -1
  240. package/dist/test/empty-placeholder.test.js +63 -63
  241. package/dist/test/expanded-date-picker.test.d.ts +1 -1
  242. package/dist/test/expanded-date-picker.test.js +95 -95
  243. package/dist/test/icon-overlay.test.d.ts +1 -1
  244. package/dist/test/icon-overlay.test.js +24 -24
  245. package/dist/test/image-block.test.d.ts +1 -1
  246. package/dist/test/image-block.test.js +48 -48
  247. package/dist/test/item-image.test.d.ts +1 -1
  248. package/dist/test/item-image.test.js +85 -86
  249. package/dist/test/item-image.test.js.map +1 -1
  250. package/dist/test/manage/manage-bar.test.d.ts +1 -1
  251. package/dist/test/manage/manage-bar.test.js +72 -72
  252. package/dist/test/mediatype-config.test.d.ts +1 -1
  253. package/dist/test/mediatype-config.test.js +16 -16
  254. package/dist/test/mocks/mock-analytics-handler.d.ts +10 -10
  255. package/dist/test/mocks/mock-analytics-handler.js +15 -15
  256. package/dist/test/mocks/mock-search-responses.d.ts +24 -21
  257. package/dist/test/mocks/mock-search-responses.js +840 -709
  258. package/dist/test/mocks/mock-search-responses.js.map +1 -1
  259. package/dist/test/mocks/mock-search-service.d.ts +15 -15
  260. package/dist/test/mocks/mock-search-service.js +53 -50
  261. package/dist/test/mocks/mock-search-service.js.map +1 -1
  262. package/dist/test/restoration-state-handler.test.d.ts +1 -1
  263. package/dist/test/restoration-state-handler.test.js +270 -270
  264. package/dist/test/sort-filter-bar/alpha-bar-tooltip.test.d.ts +1 -1
  265. package/dist/test/sort-filter-bar/alpha-bar-tooltip.test.js +12 -12
  266. package/dist/test/sort-filter-bar/alpha-bar.test.d.ts +1 -1
  267. package/dist/test/sort-filter-bar/alpha-bar.test.js +73 -73
  268. package/dist/test/sort-filter-bar/sort-filter-bar.test.d.ts +1 -1
  269. package/dist/test/sort-filter-bar/sort-filter-bar.test.js +418 -418
  270. package/dist/test/text-overlay.test.d.ts +1 -1
  271. package/dist/test/text-overlay.test.js +48 -48
  272. package/dist/test/text-snippet-block.test.d.ts +1 -1
  273. package/dist/test/text-snippet-block.test.js +57 -57
  274. package/dist/test/tile-stats.test.d.ts +1 -1
  275. package/dist/test/tile-stats.test.js +95 -33
  276. package/dist/test/tile-stats.test.js.map +1 -1
  277. package/dist/test/tiles/grid/account-tile.test.d.ts +1 -1
  278. package/dist/test/tiles/grid/account-tile.test.js +76 -76
  279. package/dist/test/tiles/grid/collection-tile.test.d.ts +1 -1
  280. package/dist/test/tiles/grid/collection-tile.test.js +73 -73
  281. package/dist/test/tiles/grid/item-tile.test.d.ts +1 -1
  282. package/dist/test/tiles/grid/item-tile.test.js +298 -254
  283. package/dist/test/tiles/grid/item-tile.test.js.map +1 -1
  284. package/dist/test/tiles/grid/search-tile.test.d.ts +1 -1
  285. package/dist/test/tiles/grid/search-tile.test.js +51 -51
  286. package/dist/test/tiles/hover/hover-pane-controller.test.d.ts +1 -1
  287. package/dist/test/tiles/hover/hover-pane-controller.test.js +259 -258
  288. package/dist/test/tiles/hover/hover-pane-controller.test.js.map +1 -1
  289. package/dist/test/tiles/hover/tile-hover-pane.test.d.ts +1 -1
  290. package/dist/test/tiles/hover/tile-hover-pane.test.js +13 -13
  291. package/dist/test/tiles/list/tile-list-compact.test.d.ts +1 -1
  292. package/dist/test/tiles/list/tile-list-compact.test.js +143 -143
  293. package/dist/test/tiles/list/tile-list.test.d.ts +1 -1
  294. package/dist/test/tiles/list/tile-list.test.js +283 -239
  295. package/dist/test/tiles/list/tile-list.test.js.map +1 -1
  296. package/dist/test/tiles/tile-dispatcher.test.d.ts +1 -1
  297. package/dist/test/tiles/tile-dispatcher.test.js +106 -94
  298. package/dist/test/tiles/tile-dispatcher.test.js.map +1 -1
  299. package/dist/test/tiles/tile-display-value-provider.test.d.ts +1 -1
  300. package/dist/test/tiles/tile-display-value-provider.test.js +141 -141
  301. package/dist/test/utils/array-equals.test.d.ts +1 -1
  302. package/dist/test/utils/array-equals.test.js +26 -26
  303. package/dist/test/utils/format-count.test.d.ts +1 -1
  304. package/dist/test/utils/format-count.test.js +23 -23
  305. package/dist/test/utils/format-date.test.d.ts +1 -1
  306. package/dist/test/utils/format-date.test.js +17 -17
  307. package/dist/test/utils/format-unit-size.test.d.ts +1 -1
  308. package/dist/test/utils/format-unit-size.test.js +17 -17
  309. package/dist/test/utils/local-date-from-utc.test.d.ts +1 -1
  310. package/dist/test/utils/local-date-from-utc.test.js +26 -26
  311. package/index.ts +3 -5
  312. package/local.archive.org.cert +86 -86
  313. package/local.archive.org.key +27 -27
  314. package/package.json +3 -4
  315. package/renovate.json +6 -6
  316. package/src/app-root.ts +30 -85
  317. package/src/collection-browser.ts +112 -139
  318. package/src/collection-facets/more-facets-content.ts +0 -19
  319. package/src/collection-facets.ts +6 -4
  320. package/src/data-source/collection-browser-data-source-interface.ts +272 -0
  321. package/src/data-source/collection-browser-data-source.ts +314 -379
  322. package/src/data-source/collection-browser-query-state.ts +54 -0
  323. package/src/data-source/models.ts +8 -45
  324. package/src/manage/manage-bar.ts +1 -1
  325. package/src/models.ts +164 -3
  326. package/src/sort-filter-bar/sort-filter-bar.ts +2 -1
  327. package/src/tiles/grid/item-tile.ts +36 -1
  328. package/src/tiles/grid/tile-stats.ts +12 -7
  329. package/src/tiles/item-image.ts +28 -0
  330. package/src/tiles/list/tile-list-compact.ts +1 -1
  331. package/src/tiles/list/tile-list.ts +43 -5
  332. package/src/tiles/tile-dispatcher.ts +2 -1
  333. package/src/tiles/tile-display-value-provider.ts +20 -2
  334. package/src/utils/collapse-repeated-quotes.ts +13 -0
  335. package/src/utils/log.ts +16 -0
  336. package/src/utils/resolve-mediatype.ts +26 -0
  337. package/test/collection-browser.test.ts +161 -50
  338. package/test/collection-facets/more-facets-content.test.ts +4 -2
  339. package/test/collection-facets.test.ts +5 -0
  340. package/test/data-source/collection-browser-data-source.test.ts +103 -0
  341. package/test/item-image.test.ts +34 -36
  342. package/test/mocks/mock-search-responses.ts +144 -0
  343. package/test/mocks/mock-search-service.ts +6 -0
  344. package/test/tile-stats.test.ts +104 -0
  345. package/test/tiles/grid/item-tile.test.ts +55 -0
  346. package/test/tiles/hover/hover-pane-controller.test.ts +19 -17
  347. package/test/tiles/list/tile-list.test.ts +55 -0
  348. package/test/tiles/tile-dispatcher.test.ts +13 -0
  349. package/tsconfig.json +21 -21
  350. package/web-dev-server.config.mjs +30 -30
  351. package/web-test-runner.config.mjs +41 -41
  352. package/types/sentry.d.ts +0 -1
@@ -1,801 +1,912 @@
1
- import { FilterConstraint, FilterMapBuilder, SearchType, } from '@internetarchive/search-service';
2
- import { prefixFilterAggregationKeys, } from '../models';
3
- import { sha1 } from '../utils/sha1';
4
- export class CollectionBrowserDataSource {
5
- constructor(
6
- /** The host element to which this controller should attach listeners */
7
- host,
8
- /** Default size of result pages */
9
- pageSize) {
10
- this.host = host;
11
- this.pageSize = pageSize;
12
- this.pages = {};
13
- this.offset = 0;
14
- this.numTileModels = 0;
15
- /**
16
- * Maps the full query key to the pages being fetched for that query
17
- */
18
- this.pageFetchesInProgress = {};
19
- this.totalResults = 0;
20
- this.endOfDataReached = false;
21
- /**
22
- * @inheritdoc
23
- */
24
- this.collectionTitles = new Map();
25
- /**
26
- * @inheritdoc
27
- */
28
- this.parentCollections = [];
29
- /**
30
- * @inheritdoc
31
- */
32
- this.prefixFilterCountMap = {};
33
- /**
34
- * @inheritdoc
35
- */
36
- this.checkAllTiles = () => {
37
- this.map(model => ({ ...model, checked: true }));
38
- };
39
- /**
40
- * @inheritdoc
41
- */
42
- this.uncheckAllTiles = () => {
43
- this.map(model => ({ ...model, checked: false }));
44
- };
45
- /**
46
- * @inheritdoc
47
- */
48
- this.removeCheckedTiles = () => {
49
- // To make sure our data source remains page-aligned, we will offset our data source by
50
- // the number of removed tiles, so that we can just add the offset when the infinite
51
- // scroller queries for cell contents.
52
- // This only matters while we're still viewing the same set of results. If the user changes
53
- // their query/filters/sort, then the data source is overwritten and the offset cleared.
54
- const { checkedTileModels, uncheckedTileModels } = this;
55
- const numChecked = checkedTileModels.length;
56
- if (numChecked === 0)
57
- return;
58
- this.offset += numChecked;
59
- const newPages = {};
60
- // Which page the remaining tile models start on, post-offset
61
- let offsetPageNumber = Math.floor(this.offset / this.pageSize) + 1;
62
- let indexOnPage = this.offset % this.pageSize;
63
- // Fill the pages up to that point with empty models
64
- for (let page = 1; page <= offsetPageNumber; page += 1) {
65
- const remainingHidden = this.offset - this.pageSize * (page - 1);
66
- const offsetCellsOnPage = Math.min(this.pageSize, remainingHidden);
67
- newPages[page] = Array(offsetCellsOnPage).fill(undefined);
68
- }
69
- // Shift all the remaining tiles into their new positions in the data source
70
- for (const model of uncheckedTileModels) {
71
- if (!newPages[offsetPageNumber])
72
- newPages[offsetPageNumber] = [];
73
- newPages[offsetPageNumber].push(model);
74
- indexOnPage += 1;
75
- if (indexOnPage >= this.pageSize) {
76
- offsetPageNumber += 1;
77
- indexOnPage = 0;
78
- }
79
- }
80
- // Swap in the new pages
81
- this.pages = newPages;
82
- this.numTileModels -= numChecked;
83
- this.host.requestUpdate();
84
- };
85
- this.host.addController(this);
86
- }
87
- /**
88
- * @inheritdoc
89
- */
90
- get size() {
91
- return this.numTileModels;
92
- }
93
- /**
94
- * @inheritdoc
95
- */
96
- addPage(pageNum, pageTiles) {
97
- this.pages[pageNum] = pageTiles;
98
- this.numTileModels += pageTiles.length;
99
- this.host.requestUpdate();
100
- }
101
- /**
102
- * @inheritdoc
103
- */
104
- getPage(pageNum) {
105
- return this.pages[pageNum];
106
- }
107
- /**
108
- * @inheritdoc
109
- */
110
- getAllPages() {
111
- return this.pages;
112
- }
113
- /**
114
- * @inheritdoc
115
- */
116
- hasPage(pageNum) {
117
- return !!this.pages[pageNum];
118
- }
119
- /**
120
- * @inheritdoc
121
- */
122
- getTileModelAt(index) {
123
- var _a;
124
- const pageNum = Math.floor(index / this.pageSize) + 1;
125
- const indexOnPage = index % this.pageSize;
126
- return (_a = this.pages[pageNum]) === null || _a === void 0 ? void 0 : _a[indexOnPage];
127
- }
128
- /**
129
- * @inheritdoc
130
- */
131
- indexOf(tile) {
132
- return Object.values(this.pages).flat().indexOf(tile);
133
- }
134
- /**
135
- * @inheritdoc
136
- */
137
- setPageSize(pageSize) {
138
- this.reset();
139
- this.pageSize = pageSize;
140
- }
141
- /**
142
- * @inheritdoc
143
- */
144
- reset() {
145
- this.pages = {};
146
- this.aggregations = {};
147
- this.yearHistogramAggregation = undefined;
148
- this.pageFetchesInProgress = {};
149
- this.pageElements = undefined;
150
- this.parentCollections = [];
151
- this.prefixFilterCountMap = {};
152
- this.offset = 0;
153
- this.numTileModels = 0;
154
- this.totalResults = 0;
155
- this.endOfDataReached = false;
156
- this.host.requestUpdate();
157
- }
158
- /**
159
- * @inheritdoc
160
- */
161
- async handleQueryChange() {
162
- this.reset();
163
- await Promise.all([
164
- this.doInitialPageFetch(),
165
- this.host.suppressFacets ? null : this.fetchFacets(),
166
- ]);
167
- }
168
- /**
169
- * @inheritdoc
170
- */
171
- map(callback) {
172
- this.pages = Object.fromEntries(Object.entries(this.pages).map(([page, tileModels]) => [
173
- page,
174
- tileModels.map((model, index, array) => model ? callback(model, index, array) : model),
175
- ]));
176
- this.host.requestUpdate();
177
- this.host.refreshVisibleResults();
178
- }
179
- /**
180
- * @inheritdoc
181
- */
182
- get checkedTileModels() {
183
- return this.getFilteredTileModels(model => model.checked);
184
- }
185
- /**
186
- * @inheritdoc
187
- */
188
- get uncheckedTileModels() {
189
- return this.getFilteredTileModels(model => !model.checked);
190
- }
191
- /**
192
- * Returns a flattened, filtered array of all the tile models in the data source
193
- * for which the given predicate returns a truthy value.
194
- *
195
- * @param predicate A callback function to apply on each tile model, as with Array.filter
196
- * @returns A filtered array of tile models satisfying the predicate
197
- */
198
- getFilteredTileModels(predicate) {
199
- return Object.values(this.pages)
200
- .flat()
201
- .filter((model, index, array) => model ? predicate(model, index, array) : false);
202
- }
203
- // DATA FETCHES
204
- /**
205
- * @inheritdoc
206
- */
207
- get canPerformSearch() {
208
- var _a;
209
- if (!this.host.searchService)
210
- return false;
211
- const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
212
- const hasNonEmptyQuery = !!trimmedQuery;
213
- const isCollectionSearch = !!this.host.withinCollection;
214
- const isProfileSearch = !!this.host.withinProfile;
215
- const hasProfileElement = !!this.host.profileElement;
216
- const isMetadataSearch = this.host.searchType === SearchType.METADATA;
217
- // Metadata searches within a collection/profile are allowed to have no query.
218
- // Otherwise, a non-empty query must be set.
219
- return (hasNonEmptyQuery ||
220
- (isCollectionSearch && isMetadataSearch) ||
221
- (isProfileSearch && hasProfileElement && isMetadataSearch));
222
- }
223
- /**
224
- * The query key is a string that uniquely identifies the current search.
225
- * It consists of:
226
- * - The current base query
227
- * - The current collection/profile target & page element
228
- * - The current search type
229
- * - Any currently-applied facets
230
- * - Any currently-applied date range
231
- * - Any currently-applied prefix filters
232
- * - The current sort options
233
- *
234
- * This lets us keep track of queries so we don't persist data that's
235
- * no longer relevant.
236
- */
237
- get pageFetchQueryKey() {
238
- var _a, _b, _c, _d, _e;
239
- const profileKey = `${this.host.withinProfile}--${this.host.profileElement}`;
240
- const pageTarget = (_a = this.host.withinCollection) !== null && _a !== void 0 ? _a : profileKey;
241
- const sortField = (_c = (_b = this.host.sortParam) === null || _b === void 0 ? void 0 : _b.field) !== null && _c !== void 0 ? _c : 'none';
242
- const sortDirection = (_e = (_d = this.host.sortParam) === null || _d === void 0 ? void 0 : _d.direction) !== null && _e !== void 0 ? _e : 'none';
243
- return `${this.fullQuery}-${pageTarget}-${this.host.searchType}-${sortField}-${sortDirection}`;
244
- }
245
- /**
246
- * Similar to `pageFetchQueryKey` above, but excludes sort fields since they
247
- * are not relevant in determining aggregation queries.
248
- */
249
- get facetFetchQueryKey() {
250
- var _a;
251
- const profileKey = `${this.host.withinProfile}--${this.host.profileElement}`;
252
- const pageTarget = (_a = this.host.withinCollection) !== null && _a !== void 0 ? _a : profileKey;
253
- return `${this.fullQuery}-${pageTarget}-${this.host.searchType}`;
254
- }
255
- /**
256
- * Constructs a search service FilterMap object from the combination of
257
- * all the currently-applied filters. This includes any facets, letter
258
- * filters, and date range.
259
- */
260
- get filterMap() {
261
- const builder = new FilterMapBuilder();
262
- // Add the date range, if applicable
263
- if (this.host.minSelectedDate) {
264
- builder.addFilter('year', this.host.minSelectedDate, FilterConstraint.GREATER_OR_EQUAL);
265
- }
266
- if (this.host.maxSelectedDate) {
267
- builder.addFilter('year', this.host.maxSelectedDate, FilterConstraint.LESS_OR_EQUAL);
268
- }
269
- // Add any selected facets
270
- if (this.host.selectedFacets) {
271
- for (const [facetName, facetValues] of Object.entries(this.host.selectedFacets)) {
272
- const { name, values } = this.prepareFacetForFetch(facetName, facetValues);
273
- for (const [value, bucket] of Object.entries(values)) {
274
- let constraint;
275
- if (bucket.state === 'selected') {
276
- constraint = FilterConstraint.INCLUDE;
277
- }
278
- else if (bucket.state === 'hidden') {
279
- constraint = FilterConstraint.EXCLUDE;
280
- }
281
- if (constraint) {
282
- builder.addFilter(name, value, constraint);
283
- }
284
- }
285
- }
286
- }
287
- // Add any letter filters
288
- if (this.host.selectedTitleFilter) {
289
- builder.addFilter('firstTitle', this.host.selectedTitleFilter, FilterConstraint.INCLUDE);
290
- }
291
- if (this.host.selectedCreatorFilter) {
292
- builder.addFilter('firstCreator', this.host.selectedCreatorFilter, FilterConstraint.INCLUDE);
293
- }
294
- const filterMap = builder.build();
295
- return filterMap;
296
- }
297
- /**
298
- * Produces a compact unique ID for a search request that can help with debugging
299
- * on the backend by making related requests easier to trace through different services.
300
- * (e.g., tying the hits/aggregations requests for the same page back to a single hash).
301
- *
302
- * @param params The search service parameters for the request
303
- * @param kind The kind of request (hits-only, aggregations-only, or both)
304
- * @returns A Promise resolving to the uid to apply to the request
305
- */
306
- async requestUID(params, kind) {
307
- var _a;
308
- const paramsToHash = JSON.stringify({
309
- pageType: params.pageType,
310
- pageTarget: params.pageTarget,
311
- query: params.query,
312
- fields: params.fields,
313
- filters: params.filters,
314
- sort: params.sort,
315
- searchType: this.host.searchType,
316
- });
317
- const fullQueryHash = (await sha1(paramsToHash)).slice(0, 20); // First 80 bits of SHA-1 are plenty for this
318
- const sessionId = (await this.host.getSessionId()).slice(0, 20); // Likewise
319
- const page = (_a = params.page) !== null && _a !== void 0 ? _a : 0;
320
- const kindPrefix = kind.charAt(0); // f = full, h = hits, a = aggregations
321
- const currentTime = Date.now();
322
- return `R:${fullQueryHash}-S:${sessionId}-P:${page}-K:${kindPrefix}-T:${currentTime}`;
323
- }
324
- /**
325
- * @inheritdoc
326
- */
327
- get pageSpecifierParams() {
328
- if (this.host.withinCollection) {
329
- return {
330
- pageType: 'collection_details',
331
- pageTarget: this.host.withinCollection,
332
- };
333
- }
334
- if (this.host.withinProfile) {
335
- return {
336
- pageType: 'account_details',
337
- pageTarget: this.host.withinProfile,
338
- pageElements: this.host.profileElement
339
- ? [this.host.profileElement]
340
- : [],
341
- };
342
- }
343
- return null;
344
- }
345
- /**
346
- * The full query, including year facets and date range clauses
347
- */
348
- get fullQuery() {
349
- var _a, _b;
350
- let fullQuery = (_b = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
351
- const { facetQuery, dateRangeQueryClause, sortFilterQueries } = this;
352
- if (facetQuery) {
353
- fullQuery += ` AND ${facetQuery}`;
354
- }
355
- if (dateRangeQueryClause) {
356
- fullQuery += ` AND ${dateRangeQueryClause}`;
357
- }
358
- if (sortFilterQueries) {
359
- fullQuery += ` AND ${sortFilterQueries}`;
360
- }
361
- return fullQuery.trim();
362
- }
363
- /**
364
- * Generates a query string representing the current set of applied facets
365
- *
366
- * Example: `mediatype:("collection" OR "audio" OR -"etree") AND year:("2000" OR "2001")`
367
- */
368
- get facetQuery() {
369
- var _a;
370
- if (!this.host.selectedFacets)
371
- return undefined;
372
- const facetClauses = [];
373
- for (const [facetName, facetValues] of Object.entries(this.host.selectedFacets)) {
374
- facetClauses.push(this.buildFacetClause(facetName, facetValues));
375
- }
376
- return (_a = this.joinFacetClauses(facetClauses)) === null || _a === void 0 ? void 0 : _a.trim();
377
- }
378
- get dateRangeQueryClause() {
379
- if (!this.host.minSelectedDate || !this.host.maxSelectedDate) {
380
- return undefined;
381
- }
382
- return `year:[${this.host.minSelectedDate} TO ${this.host.maxSelectedDate}]`;
383
- }
384
- get sortFilterQueries() {
385
- const queries = [this.titleQuery, this.creatorQuery];
386
- return queries.filter(q => q).join(' AND ');
387
- }
388
- /**
389
- * Returns a query clause identifying the currently selected title filter,
390
- * e.g., `firstTitle:X`.
391
- */
392
- get titleQuery() {
393
- return this.host.selectedTitleFilter
394
- ? `firstTitle:${this.host.selectedTitleFilter}`
395
- : undefined;
396
- }
397
- /**
398
- * Returns a query clause identifying the currently selected creator filter,
399
- * e.g., `firstCreator:X`.
400
- */
401
- get creatorQuery() {
402
- return this.host.selectedCreatorFilter
403
- ? `firstCreator:${this.host.selectedCreatorFilter}`
404
- : undefined;
405
- }
406
- /**
407
- * Builds an OR-joined facet clause for the given facet name and values.
408
- *
409
- * E.g., for name `subject` and values
410
- * `{ foo: { state: 'selected' }, bar: { state: 'hidden' } }`
411
- * this will produce the clause
412
- * `subject:("foo" OR -"bar")`.
413
- *
414
- * @param facetName The facet type (e.g., 'collection')
415
- * @param facetValues The facet buckets, mapped by their keys
416
- */
417
- buildFacetClause(facetName, facetValues) {
418
- const { name: facetQueryName, values } = this.prepareFacetForFetch(facetName, facetValues);
419
- const facetEntries = Object.entries(values);
420
- if (facetEntries.length === 0)
421
- return '';
422
- const facetValuesArray = [];
423
- for (const [key, facetData] of facetEntries) {
424
- const plusMinusPrefix = facetData.state === 'hidden' ? '-' : '';
425
- facetValuesArray.push(`${plusMinusPrefix}"${key}"`);
426
- }
427
- const valueQuery = facetValuesArray.join(` OR `);
428
- return `${facetQueryName}:(${valueQuery})`;
429
- }
430
- /**
431
- * Handles some special pre-request normalization steps for certain facet types
432
- * that require them.
433
- *
434
- * @param facetName The name of the facet type (e.g., 'language')
435
- * @param facetValues An array of values for that facet type
436
- */
437
- prepareFacetForFetch(facetName, facetValues) {
438
- // eslint-disable-next-line prefer-const
439
- let [normalizedName, normalizedValues] = [facetName, facetValues];
440
- // The full "search engine" name of the lending field is "lending___status"
441
- if (facetName === 'lending') {
442
- normalizedName = 'lending___status';
443
- }
444
- return {
445
- name: normalizedName,
446
- values: normalizedValues,
447
- };
448
- }
449
- /**
450
- * Takes an array of facet clauses, and combines them into a
451
- * full AND-joined facet query string. Empty clauses are ignored.
452
- */
453
- joinFacetClauses(facetClauses) {
454
- const nonEmptyFacetClauses = facetClauses.filter(clause => clause.length > 0);
455
- return nonEmptyFacetClauses.length > 0
456
- ? `(${nonEmptyFacetClauses.join(' AND ')})`
457
- : undefined;
458
- }
459
- /**
460
- * Fires a backend request to fetch a set of aggregations (representing UI facets) for
461
- * the current search state.
462
- */
463
- async fetchFacets() {
464
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
465
- const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
466
- if (!this.canPerformSearch)
467
- return;
468
- const { facetFetchQueryKey } = this;
469
- const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
470
- const params = {
471
- ...this.pageSpecifierParams,
472
- query: trimmedQuery || '',
473
- rows: 0,
474
- filters: this.filterMap,
475
- // Fetch a few extra buckets beyond the 6 we show, in case some get suppressed
476
- aggregationsSize: 10,
477
- // Note: we don't need an aggregations param to fetch the default aggregations from the PPS.
478
- // The default aggregations for the search_results page type should be what we need here.
479
- };
480
- params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
481
- this.host.setFacetsLoading(true);
482
- const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
483
- const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
484
- // This is checking to see if the query has changed since the data was fetched.
485
- // If so, we just want to discard this set of aggregations because they are
486
- // likely no longer valid for the newer query.
487
- const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
488
- if (queryChangedSinceFetch)
489
- return;
490
- if (!success) {
491
- const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
492
- const detailMsg = (_e = (_d = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _d === void 0 ? void 0 : _d.details) === null || _e === void 0 ? void 0 : _e.message;
493
- if (!errorMsg && !detailMsg) {
494
- // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
495
- (_g = (_f = window === null || window === void 0 ? void 0 : window.Sentry) === null || _f === void 0 ? void 0 : _f.captureMessage) === null || _g === void 0 ? void 0 : _g.call(_f, 'Missing or malformed facet response from backend', 'error');
496
- }
497
- return;
498
- }
499
- const { aggregations, collectionTitles } = success.response;
500
- this.aggregations = aggregations;
501
- if (collectionTitles) {
502
- for (const [id, title] of Object.entries(collectionTitles)) {
503
- this.collectionTitles.set(id, title);
504
- }
505
- }
506
- this.yearHistogramAggregation =
507
- (_j = (_h = success === null || success === void 0 ? void 0 : success.response) === null || _h === void 0 ? void 0 : _h.aggregations) === null || _j === void 0 ? void 0 : _j.year_histogram;
508
- this.host.setFacetsLoading(false);
509
- this.host.requestUpdate();
510
- }
511
- /**
512
- * Performs the initial page fetch(es) for the current search state.
513
- */
514
- async doInitialPageFetch() {
515
- this.host.setSearchResultsLoading(true);
516
- // Try to batch 2 initial page requests when possible
517
- await this.fetchPage(this.host.initialPageNumber, 2);
518
- this.host.setSearchResultsLoading(false);
519
- }
520
- /**
521
- * Fetches one or more pages of results and updates the data source.
522
- *
523
- * @param pageNumber The page number to fetch
524
- * @param numInitialPages If this is an initial page fetch (`pageNumber = 1`),
525
- * specifies how many pages to batch together in one request. Ignored
526
- * if `pageNumber != 1`, defaulting to a single page.
527
- */
528
- async fetchPage(pageNumber, numInitialPages = 1) {
529
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
530
- console.log(`fetchPage(${pageNumber})`, {
531
- canPerformSearch: this.canPerformSearch,
532
- baseQuery: this.host.baseQuery,
533
- });
534
- const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
535
- if (!this.canPerformSearch)
536
- return;
537
- console.log(`fetchPage - canPerformSearch`, {
538
- hasPage: this.hasPage(pageNumber),
539
- endOfDataReached: this.endOfDataReached,
540
- pageFetchesInProgress: this.pageFetchesInProgress,
541
- selectedFacets: JSON.stringify(this.host.selectedFacets),
542
- });
543
- // if we already have data, don't fetch again
544
- if (this.hasPage(pageNumber))
545
- return;
546
- if (this.endOfDataReached)
547
- return;
548
- // Batch multiple initial page requests together if needed (e.g., can request
549
- // pages 1 and 2 together in a single request).
550
- const numPages = pageNumber === 1 ? numInitialPages : 1;
551
- const numRows = this.pageSize * numPages;
552
- // if a fetch is already in progress for this query and page, don't fetch again
553
- const { pageFetchQueryKey } = this;
554
- const pageFetches = (_b = this.pageFetchesInProgress[pageFetchQueryKey]) !== null && _b !== void 0 ? _b : new Set();
555
- if (pageFetches.has(pageNumber)) {
556
- console.log(`Skipping fetch for page ${pageNumber} because one is already in progress`);
557
- return;
558
- }
559
- for (let i = 0; i < numPages; i += 1) {
560
- pageFetches.add(pageNumber + i);
561
- }
562
- this.pageFetchesInProgress[pageFetchQueryKey] = pageFetches;
563
- const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
564
- const params = {
565
- ...this.pageSpecifierParams,
566
- query: trimmedQuery || '',
567
- page: pageNumber,
568
- rows: numRows,
569
- sort: sortParams,
570
- filters: this.filterMap,
571
- aggregations: { omit: true },
572
- };
573
- params.uid = await this.requestUID(params, 'hits');
574
- console.log('=== FIRING PAGE REQUEST ===');
575
- const searchResponse = await ((_c = this.host.searchService) === null || _c === void 0 ? void 0 : _c.search(params, this.host.searchType));
576
- console.log('=== RECEIVED PAGE RESPONSE IN CB === ');
577
- const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
578
- // This is checking to see if the query has changed since the data was fetched.
579
- // If so, we just want to discard the data since there should be a new query
580
- // right behind it.
581
- const queryChangedSinceFetch = pageFetchQueryKey !== this.pageFetchQueryKey;
582
- if (queryChangedSinceFetch)
583
- return;
584
- if (!success) {
585
- const errorMsg = (_d = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _d === void 0 ? void 0 : _d.message;
586
- const detailMsg = (_f = (_e = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _e === void 0 ? void 0 : _e.details) === null || _f === void 0 ? void 0 : _f.message;
587
- this.host.queryErrorMessage = `${errorMsg !== null && errorMsg !== void 0 ? errorMsg : ''}${detailMsg ? `; ${detailMsg}` : ''}`;
588
- if (!this.host.queryErrorMessage) {
589
- this.host.queryErrorMessage =
590
- 'Missing or malformed response from backend';
591
- // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
592
- (_h = (_g = window === null || window === void 0 ? void 0 : window.Sentry) === null || _g === void 0 ? void 0 : _g.captureMessage) === null || _h === void 0 ? void 0 : _h.call(_g, this.queryErrorMessage, 'error');
593
- }
594
- for (let i = 0; i < numPages; i += 1) {
595
- (_j = this.pageFetchesInProgress[pageFetchQueryKey]) === null || _j === void 0 ? void 0 : _j.delete(pageNumber + i);
596
- }
597
- this.host.setSearchResultsLoading(false);
598
- this.host.requestUpdate();
599
- return;
600
- }
601
- this.totalResults = success.response.totalResults - this.offset;
602
- this.host.setTotalResultCount(this.totalResults);
603
- // display event to offshoot when result count is zero.
604
- if (this.totalResults === 0) {
605
- this.host.emitEmptyResults();
606
- }
607
- if (this.host.withinCollection) {
608
- this.collectionExtraInfo = success.response.collectionExtraInfo;
609
- // For collections, we want the UI to respect the default sort option
610
- // which can be specified in metadata, or otherwise assumed to be week:desc
611
- this.host.applyDefaultCollectionSort(this.collectionExtraInfo);
612
- if (this.collectionExtraInfo) {
613
- this.parentCollections = [].concat((_l = (_k = this.collectionExtraInfo.public_metadata) === null || _k === void 0 ? void 0 : _k.collection) !== null && _l !== void 0 ? _l : []);
614
- }
615
- }
616
- else if (this.host.withinProfile) {
617
- console.log('host is within profile, setting acct info:', success.response.accountExtraInfo);
618
- this.accountExtraInfo = success.response.accountExtraInfo;
619
- this.pageElements = success.response.pageElements;
620
- }
621
- const { results, collectionTitles } = success.response;
622
- if (results && results.length > 0) {
623
- // Load any collection titles present on the response into the cache,
624
- // or queue up preload fetches for them if none were present.
625
- if (collectionTitles) {
626
- for (const [id, title] of Object.entries(collectionTitles)) {
627
- this.collectionTitles.set(id, title);
628
- }
629
- }
630
- // Update the data source for each returned page
631
- for (let i = 0; i < numPages; i += 1) {
632
- const pageStartIndex = this.pageSize * i;
633
- this.addTilesToDataSource(pageNumber + i, results.slice(pageStartIndex, pageStartIndex + this.pageSize));
634
- }
635
- }
636
- // When we reach the end of the data, we can set the infinite scroller's
637
- // item count to the real total number of results (rather than the
638
- // temporary estimates based on pages rendered so far).
639
- const resultCountDiscrepancy = numRows - results.length;
640
- if (resultCountDiscrepancy > 0) {
641
- this.endOfDataReached = true;
642
- this.host.setTileCount(this.totalResults);
643
- }
644
- for (let i = 0; i < numPages; i += 1) {
645
- (_m = this.pageFetchesInProgress[pageFetchQueryKey]) === null || _m === void 0 ? void 0 : _m.delete(pageNumber + i);
646
- }
647
- this.host.requestUpdate();
648
- }
649
- /**
650
- * Update the datasource from the fetch response
651
- *
652
- * @param pageNumber
653
- * @param results
654
- */
655
- addTilesToDataSource(pageNumber, results) {
656
- // copy our existing datasource so when we set it below, it gets set
657
- // instead of modifying the existing dataSource since object changes
658
- // don't trigger a re-render
659
- // const datasource = { ...this.dataSource };
660
- const tiles = [];
661
- results === null || results === void 0 ? void 0 : results.forEach(result => {
662
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13;
663
- if (!result.identifier)
664
- return;
665
- let loginRequired = false;
666
- let contentWarning = false;
667
- // Check if item and item in "modifying" collection, setting above flags
668
- if (((_a = result.collection) === null || _a === void 0 ? void 0 : _a.values.length) &&
669
- ((_b = result.mediatype) === null || _b === void 0 ? void 0 : _b.value) !== 'collection') {
670
- for (const collection of (_d = (_c = result.collection) === null || _c === void 0 ? void 0 : _c.values) !== null && _d !== void 0 ? _d : []) {
671
- if (collection === 'loggedin') {
672
- loginRequired = true;
673
- if (contentWarning)
674
- break;
675
- }
676
- if (collection === 'no-preview') {
677
- contentWarning = true;
678
- if (loginRequired)
679
- break;
680
- }
681
- }
682
- }
683
- tiles.push({
684
- averageRating: (_e = result.avg_rating) === null || _e === void 0 ? void 0 : _e.value,
685
- checked: false,
686
- collections: (_g = (_f = result.collection) === null || _f === void 0 ? void 0 : _f.values) !== null && _g !== void 0 ? _g : [],
687
- collectionFilesCount: (_j = (_h = result.collection_files_count) === null || _h === void 0 ? void 0 : _h.value) !== null && _j !== void 0 ? _j : 0,
688
- collectionSize: (_l = (_k = result.collection_size) === null || _k === void 0 ? void 0 : _k.value) !== null && _l !== void 0 ? _l : 0,
689
- commentCount: (_o = (_m = result.num_reviews) === null || _m === void 0 ? void 0 : _m.value) !== null && _o !== void 0 ? _o : 0,
690
- creator: (_p = result.creator) === null || _p === void 0 ? void 0 : _p.value,
691
- creators: (_r = (_q = result.creator) === null || _q === void 0 ? void 0 : _q.values) !== null && _r !== void 0 ? _r : [],
692
- dateAdded: (_s = result.addeddate) === null || _s === void 0 ? void 0 : _s.value,
693
- dateArchived: (_t = result.publicdate) === null || _t === void 0 ? void 0 : _t.value,
694
- datePublished: (_u = result.date) === null || _u === void 0 ? void 0 : _u.value,
695
- dateReviewed: (_v = result.reviewdate) === null || _v === void 0 ? void 0 : _v.value,
696
- description: (_w = result.description) === null || _w === void 0 ? void 0 : _w.values.join('\n'),
697
- favCount: (_y = (_x = result.num_favorites) === null || _x === void 0 ? void 0 : _x.value) !== null && _y !== void 0 ? _y : 0,
698
- href: this.collapseRepeatedQuotes((_z = result.__href__) === null || _z === void 0 ? void 0 : _z.value),
699
- identifier: result.identifier,
700
- issue: (_0 = result.issue) === null || _0 === void 0 ? void 0 : _0.value,
701
- itemCount: (_2 = (_1 = result.item_count) === null || _1 === void 0 ? void 0 : _1.value) !== null && _2 !== void 0 ? _2 : 0,
702
- mediatype: this.getMediatype(result),
703
- snippets: (_4 = (_3 = result.highlight) === null || _3 === void 0 ? void 0 : _3.values) !== null && _4 !== void 0 ? _4 : [],
704
- source: (_5 = result.source) === null || _5 === void 0 ? void 0 : _5.value,
705
- subjects: (_7 = (_6 = result.subject) === null || _6 === void 0 ? void 0 : _6.values) !== null && _7 !== void 0 ? _7 : [],
706
- title: (_9 = (_8 = result.title) === null || _8 === void 0 ? void 0 : _8.value) !== null && _9 !== void 0 ? _9 : '',
707
- volume: (_10 = result.volume) === null || _10 === void 0 ? void 0 : _10.value,
708
- viewCount: (_12 = (_11 = result.downloads) === null || _11 === void 0 ? void 0 : _11.value) !== null && _12 !== void 0 ? _12 : 0,
709
- weeklyViewCount: (_13 = result.week) === null || _13 === void 0 ? void 0 : _13.value,
710
- loginRequired,
711
- contentWarning,
712
- });
713
- });
714
- this.addPage(pageNumber, tiles);
715
- const visiblePages = this.host.currentVisiblePageNumbers;
716
- const needsReload = visiblePages.includes(pageNumber);
717
- if (needsReload) {
718
- this.host.refreshVisibleResults();
719
- }
720
- }
721
- /**
722
- * Returns the mediatype string for the given search result, taking into account
723
- * the special `favorited_search` hit type.
724
- * @param result The search result to extract a mediatype from
725
- */
726
- getMediatype(result) {
727
- var _a, _b, _c;
728
- /**
729
- * hit_type == 'favorited_search' is basically a new hit_type
730
- * - we are getting from PPS.
731
- * - which gives response for fav- collection
732
- * - having favorited items like account/collection/item etc..
733
- * - as user can also favorite a search result (a search page)
734
- * - so we need to have response (having fav- items and fav- search results)
735
- *
736
- * if backend hit_type == 'favorited_search'
737
- * - let's assume a "search" as new mediatype
738
- */
739
- if (((_a = result === null || result === void 0 ? void 0 : result.rawMetadata) === null || _a === void 0 ? void 0 : _a.hit_type) === 'favorited_search') {
740
- return 'search';
741
- }
742
- return (_c = (_b = result.mediatype) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : 'data';
743
- }
744
- /**
745
- * Returns the input string, but removing one set of quotes from all instances of
746
- * ""clauses wrapped in two sets of quotes"". This assumes the quotes are already
747
- * URL-encoded.
748
- *
749
- * This should be a temporary measure to address the fact that the __href__ field
750
- * sometimes acquires extra quotation marks during query rewriting. Once there is a
751
- * full Lucene parser in place that handles quoted queries correctly, this can likely
752
- * be removed.
753
- */
754
- collapseRepeatedQuotes(str) {
755
- return str === null || str === void 0 ? void 0 : str.replace(/%22%22(?!%22%22)(.+?)%22%22/g, '%22$1%22');
756
- }
757
- /**
758
- * Fetches the aggregation buckets for the given prefix filter type.
759
- */
760
- async fetchPrefixFilterBuckets(filterType) {
761
- var _a, _b, _c, _d, _e, _f, _g;
762
- const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
763
- if (!this.canPerformSearch)
764
- return [];
765
- const filterAggregationKey = prefixFilterAggregationKeys[filterType];
766
- const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
767
- const params = {
768
- ...this.pageSpecifierParams,
769
- query: trimmedQuery || '',
770
- rows: 0,
771
- filters: this.filterMap,
772
- // Only fetch the firstTitle or firstCreator aggregation
773
- aggregations: { simpleParams: [filterAggregationKey] },
774
- // Fetch all 26 letter buckets
775
- aggregationsSize: 26,
776
- };
777
- params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
778
- const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
779
- return ((_g = (_f = (_e = (_d = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.aggregations) === null || _e === void 0 ? void 0 : _e[filterAggregationKey]) === null || _f === void 0 ? void 0 : _f.buckets) !== null && _g !== void 0 ? _g : []);
780
- }
781
- /**
782
- * Fetches and caches the prefix filter counts for the given filter type.
783
- */
784
- async updatePrefixFilterCounts(filterType) {
785
- const { facetFetchQueryKey } = this;
786
- const buckets = await this.fetchPrefixFilterBuckets(filterType);
787
- // Don't update the filter counts for an outdated query (if it has been changed
788
- // since we sent the request)
789
- const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
790
- if (queryChangedSinceFetch)
791
- return;
792
- // Unpack the aggregation buckets into a simple map like { 'A': 50, 'B': 25, ... }
793
- this.prefixFilterCountMap = { ...this.prefixFilterCountMap }; // Clone the object to trigger an update
794
- this.prefixFilterCountMap[filterType] = buckets.reduce((acc, bucket) => {
795
- acc[bucket.key.toUpperCase()] = bucket.doc_count;
796
- return acc;
797
- }, {});
798
- this.host.requestUpdate();
799
- }
800
- }
1
+ import { FilterConstraint, FilterMapBuilder, SearchType, } from '@internetarchive/search-service';
2
+ import { prefixFilterAggregationKeys, TileModel, SortField, SORT_OPTIONS, } from '../models';
3
+ import { FACETLESS_PAGE_ELEMENTS } from './models';
4
+ import { sha1 } from '../utils/sha1';
5
+ import { log } from '../utils/log';
6
+ export class CollectionBrowserDataSource {
7
+ // eslint-disable-next-line no-useless-constructor
8
+ constructor(
9
+ /** The host element to which this controller should attach listeners */
10
+ host,
11
+ /** Default size of result pages */
12
+ pageSize = 50) {
13
+ this.host = host;
14
+ this.pageSize = pageSize;
15
+ /**
16
+ * All pages of tile models that have been fetched so far, indexed by their page
17
+ * number (with the first being page 1).
18
+ */
19
+ this.pages = {};
20
+ /**
21
+ * Tile offset to apply when looking up tiles in the pages, in order to maintain
22
+ * page alignment after tiles are removed.
23
+ */
24
+ this.offset = 0;
25
+ /**
26
+ * Total number of tile models stored in this data source's pages
27
+ */
28
+ this.numTileModels = 0;
29
+ /**
30
+ * A set of fetch IDs that are valid for the current query state
31
+ */
32
+ this.fetchesInProgress = new Set();
33
+ /**
34
+ * A record of the query key used for the last search.
35
+ * If this changes, we need to load new results.
36
+ */
37
+ this.previousQueryKey = '';
38
+ /**
39
+ * Whether the initial page of search results for the current query state
40
+ * is presently being fetched.
41
+ */
42
+ this.searchResultsLoading = false;
43
+ /**
44
+ * Whether the facets (aggregations) for the current query state are
45
+ * presently being fetched.
46
+ */
47
+ this.facetsLoading = false;
48
+ /**
49
+ * Whether further query changes should be ignored and not trigger fetches
50
+ */
51
+ this.suppressFetches = false;
52
+ /**
53
+ * @inheritdoc
54
+ */
55
+ this.totalResults = 0;
56
+ /**
57
+ * @inheritdoc
58
+ */
59
+ this.endOfDataReached = false;
60
+ /**
61
+ * @inheritdoc
62
+ */
63
+ this.queryInitialized = false;
64
+ /**
65
+ * @inheritdoc
66
+ */
67
+ this.collectionTitles = new Map();
68
+ /**
69
+ * @inheritdoc
70
+ */
71
+ this.parentCollections = [];
72
+ /**
73
+ * @inheritdoc
74
+ */
75
+ this.prefixFilterCountMap = {};
76
+ /**
77
+ * Internal property to store the private value backing the `initialSearchComplete` getter.
78
+ */
79
+ this._initialSearchCompletePromise = new Promise(res => {
80
+ this._initialSearchCompleteResolver = res;
81
+ });
82
+ /**
83
+ * @inheritdoc
84
+ */
85
+ this.checkAllTiles = () => {
86
+ this.map(model => {
87
+ const cloned = model.clone();
88
+ cloned.checked = true;
89
+ return cloned;
90
+ });
91
+ };
92
+ /**
93
+ * @inheritdoc
94
+ */
95
+ this.uncheckAllTiles = () => {
96
+ this.map(model => {
97
+ const cloned = model.clone();
98
+ cloned.checked = false;
99
+ return cloned;
100
+ });
101
+ };
102
+ /**
103
+ * @inheritdoc
104
+ */
105
+ this.removeCheckedTiles = () => {
106
+ // To make sure our data source remains page-aligned, we will offset our data source by
107
+ // the number of removed tiles, so that we can just add the offset when the infinite
108
+ // scroller queries for cell contents.
109
+ // This only matters while we're still viewing the same set of results. If the user changes
110
+ // their query/filters/sort, then the data source is overwritten and the offset cleared.
111
+ const { checkedTileModels, uncheckedTileModels } = this;
112
+ const numChecked = checkedTileModels.length;
113
+ if (numChecked === 0)
114
+ return;
115
+ this.offset += numChecked;
116
+ const newPages = {};
117
+ // Which page the remaining tile models start on, post-offset
118
+ let offsetPageNumber = Math.floor(this.offset / this.pageSize) + 1;
119
+ let indexOnPage = this.offset % this.pageSize;
120
+ // Fill the pages up to that point with empty models
121
+ for (let page = 1; page <= offsetPageNumber; page += 1) {
122
+ const remainingHidden = this.offset - this.pageSize * (page - 1);
123
+ const offsetCellsOnPage = Math.min(this.pageSize, remainingHidden);
124
+ newPages[page] = Array(offsetCellsOnPage).fill(undefined);
125
+ }
126
+ // Shift all the remaining tiles into their new positions in the data source
127
+ for (const model of uncheckedTileModels) {
128
+ if (!newPages[offsetPageNumber])
129
+ newPages[offsetPageNumber] = [];
130
+ newPages[offsetPageNumber].push(model);
131
+ indexOnPage += 1;
132
+ if (indexOnPage >= this.pageSize) {
133
+ offsetPageNumber += 1;
134
+ indexOnPage = 0;
135
+ }
136
+ }
137
+ // Swap in the new pages
138
+ this.pages = newPages;
139
+ this.numTileModels -= numChecked;
140
+ this.requestHostUpdate();
141
+ this.refreshVisibleResults();
142
+ };
143
+ // Just setting some property values
144
+ }
145
+ /**
146
+ * @inheritdoc
147
+ */
148
+ get initialSearchComplete() {
149
+ return this._initialSearchCompletePromise;
150
+ }
151
+ hostConnected() {
152
+ this.setSearchResultsLoading(this.searchResultsLoading);
153
+ this.setFacetsLoading(this.facetsLoading);
154
+ }
155
+ hostUpdate() {
156
+ // This reactive controller hook is run whenever the host component (collection-browser) performs an update.
157
+ // We check whether the host's state has changed in a way which should trigger a reset & new results fetch.
158
+ // Only the currently-installed data source should react to the update
159
+ if (!this.activeOnHost)
160
+ return;
161
+ // Copy loading states onto the host
162
+ this.setSearchResultsLoading(this.searchResultsLoading);
163
+ this.setFacetsLoading(this.facetsLoading);
164
+ // Can't perform searches without a search service
165
+ if (!this.host.searchService)
166
+ return;
167
+ // We should only reset if part of the full query state has changed
168
+ const queryKeyChanged = this.pageFetchQueryKey !== this.previousQueryKey;
169
+ if (!queryKeyChanged)
170
+ return;
171
+ // We should only reset if either:
172
+ // (a) our state permits a valid search, or
173
+ // (b) we have a blank query that we want to show empty results for
174
+ const shouldShowEmptyQueryResults = this.host.clearResultsOnEmptyQuery && this.host.baseQuery === '';
175
+ if (!(this.canPerformSearch || shouldShowEmptyQueryResults))
176
+ return;
177
+ if (this.activeOnHost)
178
+ this.host.emitQueryStateChanged();
179
+ this.handleQueryChange();
180
+ }
181
+ /**
182
+ * Returns whether this data source is the one currently installed on the host component.
183
+ */
184
+ get activeOnHost() {
185
+ return this.host.dataSource === this;
186
+ }
187
+ /**
188
+ * @inheritdoc
189
+ */
190
+ get size() {
191
+ return this.numTileModels;
192
+ }
193
+ /**
194
+ * @inheritdoc
195
+ */
196
+ reset() {
197
+ log('Resetting CB data source');
198
+ this.pages = {};
199
+ this.aggregations = {};
200
+ this.yearHistogramAggregation = undefined;
201
+ this.pageElements = undefined;
202
+ this.parentCollections = [];
203
+ this.queryErrorMessage = undefined;
204
+ this.offset = 0;
205
+ this.numTileModels = 0;
206
+ this.totalResults = 0;
207
+ this.endOfDataReached = false;
208
+ this.queryInitialized = false;
209
+ // Invalidate any fetches in progress
210
+ this.fetchesInProgress.clear();
211
+ if (this.activeOnHost)
212
+ this.host.setTotalResultCount(0);
213
+ this.requestHostUpdate();
214
+ }
215
+ /**
216
+ * @inheritdoc
217
+ */
218
+ addPage(pageNum, pageTiles) {
219
+ this.pages[pageNum] = pageTiles;
220
+ this.numTileModels += pageTiles.length;
221
+ this.requestHostUpdate();
222
+ }
223
+ /**
224
+ * @inheritdoc
225
+ */
226
+ getPage(pageNum) {
227
+ return this.pages[pageNum];
228
+ }
229
+ /**
230
+ * @inheritdoc
231
+ */
232
+ getAllPages() {
233
+ return this.pages;
234
+ }
235
+ /**
236
+ * @inheritdoc
237
+ */
238
+ hasPage(pageNum) {
239
+ return !!this.pages[pageNum];
240
+ }
241
+ /**
242
+ * @inheritdoc
243
+ */
244
+ getTileModelAt(index) {
245
+ var _a;
246
+ const pageNum = Math.floor(index / this.pageSize) + 1;
247
+ const indexOnPage = index % this.pageSize;
248
+ return (_a = this.pages[pageNum]) === null || _a === void 0 ? void 0 : _a[indexOnPage];
249
+ }
250
+ /**
251
+ * @inheritdoc
252
+ */
253
+ indexOf(tile) {
254
+ return Object.values(this.pages).flat().indexOf(tile);
255
+ }
256
+ /**
257
+ * @inheritdoc
258
+ */
259
+ getPageSize() {
260
+ return this.pageSize;
261
+ }
262
+ /**
263
+ * @inheritdoc
264
+ */
265
+ setPageSize(pageSize) {
266
+ this.reset();
267
+ this.pageSize = pageSize;
268
+ }
269
+ /**
270
+ * @inheritdoc
271
+ */
272
+ setFetchesSuppressed(suppressed) {
273
+ this.suppressFetches = suppressed;
274
+ }
275
+ /**
276
+ * @inheritdoc
277
+ */
278
+ async handleQueryChange() {
279
+ // Don't react to the change if fetches are suppressed for this data source
280
+ if (this.suppressFetches)
281
+ return;
282
+ this.reset();
283
+ // Reset the `initialSearchComplete` promise with a new value for the imminent search
284
+ this._initialSearchCompletePromise = new Promise(res => {
285
+ this._initialSearchCompleteResolver = res;
286
+ });
287
+ const shouldFetchFacets = !this.host.suppressFacets &&
288
+ !FACETLESS_PAGE_ELEMENTS.includes(this.host.profileElement);
289
+ // Fire the initial page & facet requests
290
+ this.queryInitialized = true;
291
+ await Promise.all([
292
+ this.doInitialPageFetch(),
293
+ shouldFetchFacets ? this.fetchFacets() : null,
294
+ ]);
295
+ // Resolve the `initialSearchComplete` promise for this search
296
+ this._initialSearchCompleteResolver(true);
297
+ }
298
+ /**
299
+ * @inheritdoc
300
+ */
301
+ map(callback) {
302
+ this.pages = Object.fromEntries(Object.entries(this.pages).map(([page, tileModels]) => [
303
+ page,
304
+ tileModels.map((model, index, array) => model ? callback(model, index, array) : model),
305
+ ]));
306
+ this.requestHostUpdate();
307
+ this.refreshVisibleResults();
308
+ }
309
+ /**
310
+ * @inheritdoc
311
+ */
312
+ get checkedTileModels() {
313
+ return this.getFilteredTileModels(model => model.checked);
314
+ }
315
+ /**
316
+ * @inheritdoc
317
+ */
318
+ get uncheckedTileModels() {
319
+ return this.getFilteredTileModels(model => !model.checked);
320
+ }
321
+ /**
322
+ * Returns a flattened, filtered array of all the tile models in the data source
323
+ * for which the given predicate returns a truthy value.
324
+ *
325
+ * @param predicate A callback function to apply on each tile model, as with Array.filter
326
+ * @returns A filtered array of tile models satisfying the predicate
327
+ */
328
+ getFilteredTileModels(predicate) {
329
+ return Object.values(this.pages)
330
+ .flat()
331
+ .filter((model, index, array) => model ? predicate(model, index, array) : false);
332
+ }
333
+ /**
334
+ * @inheritdoc
335
+ */
336
+ get canPerformSearch() {
337
+ var _a;
338
+ if (!this.host.searchService)
339
+ return false;
340
+ const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
341
+ const hasNonEmptyQuery = !!trimmedQuery;
342
+ const isCollectionSearch = !!this.host.withinCollection;
343
+ const isProfileSearch = !!this.host.withinProfile;
344
+ const hasProfileElement = !!this.host.profileElement;
345
+ const isMetadataSearch = this.host.searchType === SearchType.METADATA;
346
+ // Metadata searches within a collection/profile are allowed to have no query.
347
+ // Otherwise, a non-empty query must be set.
348
+ return (hasNonEmptyQuery ||
349
+ (isCollectionSearch && isMetadataSearch) ||
350
+ (isProfileSearch && hasProfileElement && isMetadataSearch));
351
+ }
352
+ /**
353
+ * Sets the state for whether the initial set of search results for the
354
+ * current query is loading
355
+ */
356
+ setSearchResultsLoading(loading) {
357
+ this.searchResultsLoading = loading;
358
+ if (this.activeOnHost) {
359
+ this.host.setSearchResultsLoading(loading);
360
+ }
361
+ }
362
+ /**
363
+ * Sets the state for whether the facets for a query is loading
364
+ */
365
+ setFacetsLoading(loading) {
366
+ this.facetsLoading = loading;
367
+ if (this.activeOnHost) {
368
+ this.host.setFacetsLoading(loading);
369
+ }
370
+ }
371
+ /**
372
+ * Requests that the host perform an update, provided this data
373
+ * source is actively installed on it.
374
+ */
375
+ requestHostUpdate() {
376
+ if (this.activeOnHost) {
377
+ this.host.requestUpdate();
378
+ }
379
+ }
380
+ /**
381
+ * Requests that the host refresh its visible tiles, provided this
382
+ * data source is actively installed on it.
383
+ */
384
+ refreshVisibleResults() {
385
+ if (this.activeOnHost) {
386
+ this.host.refreshVisibleResults();
387
+ }
388
+ }
389
+ /**
390
+ * The query key is a string that uniquely identifies the current search.
391
+ * It consists of:
392
+ * - The current base query
393
+ * - The current collection/profile target & page element
394
+ * - The current search type
395
+ * - Any currently-applied facets
396
+ * - Any currently-applied date range
397
+ * - Any currently-applied prefix filters
398
+ * - The current sort options
399
+ *
400
+ * This lets us internally keep track of queries so we don't persist data that's
401
+ * no longer relevant. Not meant to be human-readable.
402
+ */
403
+ get pageFetchQueryKey() {
404
+ var _a, _b, _c;
405
+ const profileKey = `pf;${this.host.withinProfile}--pe;${this.host.profileElement}`;
406
+ const pageTarget = (_a = this.host.withinCollection) !== null && _a !== void 0 ? _a : profileKey;
407
+ const sortField = (_b = this.host.selectedSort) !== null && _b !== void 0 ? _b : 'none';
408
+ const sortDirection = (_c = this.host.sortDirection) !== null && _c !== void 0 ? _c : 'none';
409
+ return `fq:${this.fullQuery}-pt:${pageTarget}-st:${this.host.searchType}-sf:${sortField}-sd:${sortDirection}`;
410
+ }
411
+ /**
412
+ * Similar to `pageFetchQueryKey` above, but excludes sort fields since they
413
+ * are not relevant in determining aggregation queries.
414
+ */
415
+ get facetFetchQueryKey() {
416
+ var _a;
417
+ const profileKey = `pf;${this.host.withinProfile}--pe;${this.host.profileElement}`;
418
+ const pageTarget = (_a = this.host.withinCollection) !== null && _a !== void 0 ? _a : profileKey;
419
+ return `fq:${this.fullQuery}-pt:${pageTarget}-st:${this.host.searchType}`;
420
+ }
421
+ /**
422
+ * Constructs a search service FilterMap object from the combination of
423
+ * all the currently-applied filters. This includes any facets, letter
424
+ * filters, and date range.
425
+ */
426
+ get filterMap() {
427
+ const builder = new FilterMapBuilder();
428
+ // Add the date range, if applicable
429
+ if (this.host.minSelectedDate) {
430
+ builder.addFilter('year', this.host.minSelectedDate, FilterConstraint.GREATER_OR_EQUAL);
431
+ }
432
+ if (this.host.maxSelectedDate) {
433
+ builder.addFilter('year', this.host.maxSelectedDate, FilterConstraint.LESS_OR_EQUAL);
434
+ }
435
+ // Add any selected facets
436
+ if (this.host.selectedFacets) {
437
+ for (const [facetName, facetValues] of Object.entries(this.host.selectedFacets)) {
438
+ const { name, values } = this.prepareFacetForFetch(facetName, facetValues);
439
+ for (const [value, bucket] of Object.entries(values)) {
440
+ let constraint;
441
+ if (bucket.state === 'selected') {
442
+ constraint = FilterConstraint.INCLUDE;
443
+ }
444
+ else if (bucket.state === 'hidden') {
445
+ constraint = FilterConstraint.EXCLUDE;
446
+ }
447
+ if (constraint) {
448
+ builder.addFilter(name, value, constraint);
449
+ }
450
+ }
451
+ }
452
+ }
453
+ // Add any letter filters
454
+ if (this.host.selectedTitleFilter) {
455
+ builder.addFilter('firstTitle', this.host.selectedTitleFilter, FilterConstraint.INCLUDE);
456
+ }
457
+ if (this.host.selectedCreatorFilter) {
458
+ builder.addFilter('firstCreator', this.host.selectedCreatorFilter, FilterConstraint.INCLUDE);
459
+ }
460
+ const filterMap = builder.build();
461
+ return filterMap;
462
+ }
463
+ /**
464
+ * Produces a compact unique ID for a search request that can help with debugging
465
+ * on the backend by making related requests easier to trace through different services.
466
+ * (e.g., tying the hits/aggregations requests for the same page back to a single hash).
467
+ *
468
+ * @param params The search service parameters for the request
469
+ * @param kind The kind of request (hits-only, aggregations-only, or both)
470
+ * @returns A Promise resolving to the uid to apply to the request
471
+ */
472
+ async requestUID(params, kind) {
473
+ var _a;
474
+ const paramsToHash = JSON.stringify({
475
+ pageType: params.pageType,
476
+ pageTarget: params.pageTarget,
477
+ query: params.query,
478
+ fields: params.fields,
479
+ filters: params.filters,
480
+ sort: params.sort,
481
+ searchType: this.host.searchType,
482
+ });
483
+ const fullQueryHash = (await sha1(paramsToHash)).slice(0, 20); // First 80 bits of SHA-1 are plenty for this
484
+ const sessionId = (await this.host.getSessionId()).slice(0, 20); // Likewise
485
+ const page = (_a = params.page) !== null && _a !== void 0 ? _a : 0;
486
+ const kindPrefix = kind.charAt(0); // f = full, h = hits, a = aggregations
487
+ const currentTime = Date.now();
488
+ return `R:${fullQueryHash}-S:${sessionId}-P:${page}-K:${kindPrefix}-T:${currentTime}`;
489
+ }
490
+ /**
491
+ * @inheritdoc
492
+ */
493
+ get pageSpecifierParams() {
494
+ if (this.host.withinCollection) {
495
+ return {
496
+ pageType: 'collection_details',
497
+ pageTarget: this.host.withinCollection,
498
+ };
499
+ }
500
+ if (this.host.withinProfile) {
501
+ return {
502
+ pageType: 'account_details',
503
+ pageTarget: this.host.withinProfile,
504
+ pageElements: this.host.profileElement
505
+ ? [this.host.profileElement]
506
+ : [],
507
+ };
508
+ }
509
+ return null;
510
+ }
511
+ /**
512
+ * The full query, including year facets and date range clauses
513
+ */
514
+ get fullQuery() {
515
+ var _a, _b;
516
+ let fullQuery = (_b = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
517
+ const { facetQuery, dateRangeQueryClause, sortFilterQueries } = this;
518
+ if (facetQuery) {
519
+ fullQuery += ` AND ${facetQuery}`;
520
+ }
521
+ if (dateRangeQueryClause) {
522
+ fullQuery += ` AND ${dateRangeQueryClause}`;
523
+ }
524
+ if (sortFilterQueries) {
525
+ fullQuery += ` AND ${sortFilterQueries}`;
526
+ }
527
+ return fullQuery.trim();
528
+ }
529
+ /**
530
+ * Generates a query string representing the current set of applied facets
531
+ *
532
+ * Example: `mediatype:("collection" OR "audio" OR -"etree") AND year:("2000" OR "2001")`
533
+ */
534
+ get facetQuery() {
535
+ var _a;
536
+ if (!this.host.selectedFacets)
537
+ return undefined;
538
+ const facetClauses = [];
539
+ for (const [facetName, facetValues] of Object.entries(this.host.selectedFacets)) {
540
+ facetClauses.push(this.buildFacetClause(facetName, facetValues));
541
+ }
542
+ return (_a = this.joinFacetClauses(facetClauses)) === null || _a === void 0 ? void 0 : _a.trim();
543
+ }
544
+ get dateRangeQueryClause() {
545
+ if (!this.host.minSelectedDate || !this.host.maxSelectedDate) {
546
+ return undefined;
547
+ }
548
+ return `year:[${this.host.minSelectedDate} TO ${this.host.maxSelectedDate}]`;
549
+ }
550
+ get sortFilterQueries() {
551
+ const queries = [this.titleQuery, this.creatorQuery];
552
+ return queries.filter(q => q).join(' AND ');
553
+ }
554
+ /**
555
+ * Returns a query clause identifying the currently selected title filter,
556
+ * e.g., `firstTitle:X`.
557
+ */
558
+ get titleQuery() {
559
+ return this.host.selectedTitleFilter
560
+ ? `firstTitle:${this.host.selectedTitleFilter}`
561
+ : undefined;
562
+ }
563
+ /**
564
+ * Returns a query clause identifying the currently selected creator filter,
565
+ * e.g., `firstCreator:X`.
566
+ */
567
+ get creatorQuery() {
568
+ return this.host.selectedCreatorFilter
569
+ ? `firstCreator:${this.host.selectedCreatorFilter}`
570
+ : undefined;
571
+ }
572
+ /**
573
+ * Builds an OR-joined facet clause for the given facet name and values.
574
+ *
575
+ * E.g., for name `subject` and values
576
+ * `{ foo: { state: 'selected' }, bar: { state: 'hidden' } }`
577
+ * this will produce the clause
578
+ * `subject:("foo" OR -"bar")`.
579
+ *
580
+ * @param facetName The facet type (e.g., 'collection')
581
+ * @param facetValues The facet buckets, mapped by their keys
582
+ */
583
+ buildFacetClause(facetName, facetValues) {
584
+ const { name: facetQueryName, values } = this.prepareFacetForFetch(facetName, facetValues);
585
+ const facetEntries = Object.entries(values);
586
+ if (facetEntries.length === 0)
587
+ return '';
588
+ const facetValuesArray = [];
589
+ for (const [key, facetData] of facetEntries) {
590
+ const plusMinusPrefix = facetData.state === 'hidden' ? '-' : '';
591
+ facetValuesArray.push(`${plusMinusPrefix}"${key}"`);
592
+ }
593
+ const valueQuery = facetValuesArray.join(` OR `);
594
+ return `${facetQueryName}:(${valueQuery})`;
595
+ }
596
+ /**
597
+ * Handles some special pre-request normalization steps for certain facet types
598
+ * that require them.
599
+ *
600
+ * @param facetName The name of the facet type (e.g., 'language')
601
+ * @param facetValues An array of values for that facet type
602
+ */
603
+ prepareFacetForFetch(facetName, facetValues) {
604
+ // eslint-disable-next-line prefer-const
605
+ let [normalizedName, normalizedValues] = [facetName, facetValues];
606
+ // The full "search engine" name of the lending field is "lending___status"
607
+ if (facetName === 'lending') {
608
+ normalizedName = 'lending___status';
609
+ }
610
+ return {
611
+ name: normalizedName,
612
+ values: normalizedValues,
613
+ };
614
+ }
615
+ /**
616
+ * Takes an array of facet clauses, and combines them into a
617
+ * full AND-joined facet query string. Empty clauses are ignored.
618
+ */
619
+ joinFacetClauses(facetClauses) {
620
+ const nonEmptyFacetClauses = facetClauses.filter(clause => clause.length > 0);
621
+ return nonEmptyFacetClauses.length > 0
622
+ ? `(${nonEmptyFacetClauses.join(' AND ')})`
623
+ : undefined;
624
+ }
625
+ /**
626
+ * Fires a backend request to fetch a set of aggregations (representing UI facets) for
627
+ * the current search state.
628
+ */
629
+ async fetchFacets() {
630
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
631
+ const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
632
+ if (!this.canPerformSearch)
633
+ return;
634
+ const { facetFetchQueryKey } = this;
635
+ if (this.fetchesInProgress.has(facetFetchQueryKey))
636
+ return;
637
+ this.fetchesInProgress.add(facetFetchQueryKey);
638
+ const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
639
+ const params = {
640
+ ...this.pageSpecifierParams,
641
+ query: trimmedQuery || '',
642
+ rows: 0,
643
+ filters: this.filterMap,
644
+ // Fetch a few extra buckets beyond the 6 we show, in case some get suppressed
645
+ aggregationsSize: 10,
646
+ // Note: we don't need an aggregations param to fetch the default aggregations from the PPS.
647
+ // The default aggregations for the search_results page type should be what we need here.
648
+ };
649
+ params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
650
+ this.setFacetsLoading(true);
651
+ const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
652
+ const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
653
+ // This is checking to see if the query has changed since the data was fetched.
654
+ // If so, we just want to discard this set of aggregations because they are
655
+ // likely no longer valid for the newer query.
656
+ const queryChangedSinceFetch = !this.fetchesInProgress.has(facetFetchQueryKey);
657
+ this.fetchesInProgress.delete(facetFetchQueryKey);
658
+ if (queryChangedSinceFetch)
659
+ return;
660
+ if (!success) {
661
+ const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
662
+ const detailMsg = (_e = (_d = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _d === void 0 ? void 0 : _d.details) === null || _e === void 0 ? void 0 : _e.message;
663
+ if (!errorMsg && !detailMsg) {
664
+ // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
665
+ (_g = (_f = window === null || window === void 0 ? void 0 : window.Sentry) === null || _f === void 0 ? void 0 : _f.captureMessage) === null || _g === void 0 ? void 0 : _g.call(_f, 'Missing or malformed facet response from backend', 'error');
666
+ }
667
+ this.setFacetsLoading(false);
668
+ return;
669
+ }
670
+ const { aggregations, collectionTitles } = success.response;
671
+ this.aggregations = aggregations;
672
+ if (collectionTitles) {
673
+ for (const [id, title] of Object.entries(collectionTitles)) {
674
+ this.collectionTitles.set(id, title);
675
+ }
676
+ }
677
+ this.yearHistogramAggregation =
678
+ (_j = (_h = success === null || success === void 0 ? void 0 : success.response) === null || _h === void 0 ? void 0 : _h.aggregations) === null || _j === void 0 ? void 0 : _j.year_histogram;
679
+ this.setFacetsLoading(false);
680
+ this.requestHostUpdate();
681
+ }
682
+ /**
683
+ * Performs the initial page fetch(es) for the current search state.
684
+ */
685
+ async doInitialPageFetch() {
686
+ this.setSearchResultsLoading(true);
687
+ // Try to batch 2 initial page requests when possible
688
+ await this.fetchPage(this.host.initialPageNumber, 2);
689
+ }
690
+ /**
691
+ * Fetches one or more pages of results and updates the data source.
692
+ *
693
+ * @param pageNumber The page number to fetch
694
+ * @param numInitialPages If this is an initial page fetch (`pageNumber = 1`),
695
+ * specifies how many pages to batch together in one request. Ignored
696
+ * if `pageNumber != 1`, defaulting to a single page.
697
+ */
698
+ async fetchPage(pageNumber, numInitialPages = 1) {
699
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
700
+ const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
701
+ if (!this.canPerformSearch)
702
+ return;
703
+ // if we already have data, don't fetch again
704
+ if (this.hasPage(pageNumber))
705
+ return;
706
+ if (this.endOfDataReached)
707
+ return;
708
+ // Batch multiple initial page requests together if needed (e.g., can request
709
+ // pages 1 and 2 together in a single request).
710
+ let numPages = pageNumber === 1 ? numInitialPages : 1;
711
+ const numRows = this.pageSize * numPages;
712
+ // if a fetch is already in progress for this query and page, don't fetch again
713
+ const { pageFetchQueryKey } = this;
714
+ const currentPageKey = `${pageFetchQueryKey}-p:${pageNumber}`;
715
+ if (this.fetchesInProgress.has(currentPageKey))
716
+ return;
717
+ for (let i = 0; i < numPages; i += 1) {
718
+ this.fetchesInProgress.add(`${pageFetchQueryKey}-p:${pageNumber + i}`);
719
+ }
720
+ this.previousQueryKey = pageFetchQueryKey;
721
+ let sortParams = this.host.sortParam ? [this.host.sortParam] : [];
722
+ // TODO eventually the PPS should handle these defaults natively
723
+ const isDefaultProfileSort = this.host.withinProfile && this.host.selectedSort === SortField.default;
724
+ if (isDefaultProfileSort && this.host.defaultSortParam) {
725
+ const sortOption = SORT_OPTIONS[this.host.defaultSortParam.field];
726
+ if (sortOption.searchServiceKey) {
727
+ sortParams = [
728
+ {
729
+ field: sortOption.searchServiceKey,
730
+ direction: 'desc',
731
+ },
732
+ ];
733
+ }
734
+ }
735
+ const params = {
736
+ ...this.pageSpecifierParams,
737
+ query: trimmedQuery || '',
738
+ page: pageNumber,
739
+ rows: numRows,
740
+ sort: sortParams,
741
+ filters: this.filterMap,
742
+ aggregations: { omit: true },
743
+ };
744
+ params.uid = await this.requestUID(params, 'hits');
745
+ log('=== FIRING PAGE REQUEST ===', params);
746
+ const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
747
+ log('=== RECEIVED PAGE RESPONSE IN CB ===', searchResponse);
748
+ const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
749
+ // This is checking to see if the fetch has been invalidated since it was fired off.
750
+ // If so, we just want to discard the response since it is for an obsolete query state.
751
+ if (!this.fetchesInProgress.has(currentPageKey))
752
+ return;
753
+ for (let i = 0; i < numPages; i += 1) {
754
+ this.fetchesInProgress.delete(`${pageFetchQueryKey}-p:${pageNumber + i}`);
755
+ }
756
+ if (!success) {
757
+ const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
758
+ const detailMsg = (_e = (_d = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _d === void 0 ? void 0 : _d.details) === null || _e === void 0 ? void 0 : _e.message;
759
+ this.queryErrorMessage = `${errorMsg !== null && errorMsg !== void 0 ? errorMsg : ''}${detailMsg ? `; ${detailMsg}` : ''}`;
760
+ if (!this.queryErrorMessage) {
761
+ this.queryErrorMessage = 'Missing or malformed response from backend';
762
+ // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
763
+ (_g = (_f = window === null || window === void 0 ? void 0 : window.Sentry) === null || _f === void 0 ? void 0 : _f.captureMessage) === null || _g === void 0 ? void 0 : _g.call(_f, this.queryErrorMessage, 'error');
764
+ }
765
+ this.setSearchResultsLoading(false);
766
+ this.requestHostUpdate();
767
+ return;
768
+ }
769
+ this.totalResults = success.response.totalResults - this.offset;
770
+ if (this.activeOnHost) {
771
+ this.host.setTotalResultCount(this.totalResults);
772
+ // display event to offshoot when result count is zero.
773
+ if (this.totalResults === 0) {
774
+ this.host.emitEmptyResults();
775
+ }
776
+ }
777
+ if (this.host.withinCollection) {
778
+ this.collectionExtraInfo = success.response.collectionExtraInfo;
779
+ // For collections, we want the UI to respect the default sort option
780
+ // which can be specified in metadata, or otherwise assumed to be week:desc
781
+ if (this.activeOnHost) {
782
+ this.host.applyDefaultCollectionSort(this.collectionExtraInfo);
783
+ }
784
+ if (this.collectionExtraInfo) {
785
+ this.parentCollections = [].concat((_j = (_h = this.collectionExtraInfo.public_metadata) === null || _h === void 0 ? void 0 : _h.collection) !== null && _j !== void 0 ? _j : []);
786
+ }
787
+ }
788
+ else if (this.host.withinProfile) {
789
+ this.accountExtraInfo = success.response.accountExtraInfo;
790
+ this.pageElements = success.response.pageElements;
791
+ }
792
+ const { results, collectionTitles } = success.response;
793
+ if (results && results.length > 0) {
794
+ // Load any collection titles present on the response into the cache,
795
+ // or queue up preload fetches for them if none were present.
796
+ if (collectionTitles) {
797
+ for (const [id, title] of Object.entries(collectionTitles)) {
798
+ this.collectionTitles.set(id, title);
799
+ }
800
+ }
801
+ // Update the data source for each returned page.
802
+ // For loans and web archives, we must account for receiving more pages than we asked for.
803
+ if (this.host.profileElement === 'lending' ||
804
+ this.host.profileElement === 'web_archives') {
805
+ numPages = Math.ceil(results.length / this.pageSize);
806
+ this.endOfDataReached = true;
807
+ if (this.activeOnHost)
808
+ this.host.setTileCount(this.totalResults);
809
+ }
810
+ for (let i = 0; i < numPages; i += 1) {
811
+ const pageStartIndex = this.pageSize * i;
812
+ this.addTilesToDataSource(pageNumber + i, results.slice(pageStartIndex, pageStartIndex + this.pageSize));
813
+ }
814
+ }
815
+ // When we reach the end of the data, we can set the infinite scroller's
816
+ // item count to the real total number of results (rather than the
817
+ // temporary estimates based on pages rendered so far).
818
+ const resultCountDiscrepancy = numRows - results.length;
819
+ if (resultCountDiscrepancy > 0) {
820
+ this.endOfDataReached = true;
821
+ if (this.activeOnHost)
822
+ this.host.setTileCount(this.totalResults);
823
+ }
824
+ this.setSearchResultsLoading(false);
825
+ this.requestHostUpdate();
826
+ }
827
+ /**
828
+ * Update the datasource from the fetch response
829
+ *
830
+ * @param pageNumber
831
+ * @param results
832
+ */
833
+ addTilesToDataSource(pageNumber, results) {
834
+ const tiles = [];
835
+ results === null || results === void 0 ? void 0 : results.forEach(result => {
836
+ if (!result.identifier)
837
+ return;
838
+ tiles.push(new TileModel(result));
839
+ });
840
+ this.addPage(pageNumber, tiles);
841
+ const visiblePages = this.host.currentVisiblePageNumbers;
842
+ const needsReload = visiblePages.includes(pageNumber);
843
+ if (needsReload) {
844
+ this.refreshVisibleResults();
845
+ }
846
+ }
847
+ /**
848
+ * Fetches the aggregation buckets for the given prefix filter type.
849
+ */
850
+ async fetchPrefixFilterBuckets(filterType) {
851
+ var _a, _b, _c, _d, _e, _f, _g;
852
+ const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
853
+ if (!this.canPerformSearch)
854
+ return [];
855
+ const filterAggregationKey = prefixFilterAggregationKeys[filterType];
856
+ const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
857
+ const params = {
858
+ ...this.pageSpecifierParams,
859
+ query: trimmedQuery || '',
860
+ rows: 0,
861
+ filters: this.filterMap,
862
+ // Only fetch the firstTitle or firstCreator aggregation
863
+ aggregations: { simpleParams: [filterAggregationKey] },
864
+ // Fetch all 26 letter buckets
865
+ aggregationsSize: 26,
866
+ };
867
+ params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
868
+ const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
869
+ return ((_g = (_f = (_e = (_d = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.aggregations) === null || _e === void 0 ? void 0 : _e[filterAggregationKey]) === null || _f === void 0 ? void 0 : _f.buckets) !== null && _g !== void 0 ? _g : []);
870
+ }
871
+ /**
872
+ * Fetches and caches the prefix filter counts for the given filter type.
873
+ */
874
+ async updatePrefixFilterCounts(filterType) {
875
+ const { facetFetchQueryKey } = this;
876
+ const buckets = await this.fetchPrefixFilterBuckets(filterType);
877
+ // Don't update the filter counts for an outdated query (if it has been changed
878
+ // since we sent the request)
879
+ const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
880
+ if (queryChangedSinceFetch)
881
+ return;
882
+ // Unpack the aggregation buckets into a simple map like { 'A': 50, 'B': 25, ... }
883
+ this.prefixFilterCountMap = { ...this.prefixFilterCountMap }; // Clone the object to trigger an update
884
+ this.prefixFilterCountMap[filterType] = buckets.reduce((acc, bucket) => {
885
+ acc[bucket.key.toUpperCase()] = bucket.doc_count;
886
+ return acc;
887
+ }, {});
888
+ this.requestHostUpdate();
889
+ }
890
+ /**
891
+ * @inheritdoc
892
+ */
893
+ async updatePrefixFiltersForCurrentSort() {
894
+ if (['title', 'creator'].includes(this.host.selectedSort)) {
895
+ const filterType = this.host.selectedSort;
896
+ if (!this.prefixFilterCountMap[filterType]) {
897
+ this.updatePrefixFilterCounts(filterType);
898
+ }
899
+ }
900
+ }
901
+ /**
902
+ * @inheritdoc
903
+ */
904
+ refreshLetterCounts() {
905
+ if (Object.keys(this.prefixFilterCountMap).length > 0) {
906
+ this.prefixFilterCountMap = {};
907
+ }
908
+ this.updatePrefixFiltersForCurrentSort();
909
+ this.requestHostUpdate();
910
+ }
911
+ }
801
912
  //# sourceMappingURL=collection-browser-data-source.js.map