culture-list.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import type { CultureCategoryKey, CultureItem } from '../../../data/culture-content'
  2. import { createCultureFilterOptions, createCultureFilters, findCultureCategory, getCultureList } from '../../../data/culture-content'
  3. import { getInheritCategories } from '../../../data/inherit-api'
  4. import { getNavBarLayout } from '../../../utils/nav-bar'
  5. import { runRefresh } from '../../../utils/refresh'
  6. import { getArticleDetailUrl } from '../../../utils/routes'
  7. const initialCategory = findCultureCategory(undefined)
  8. // 输入停顿后再搜索,避免每输入一个字就请求一次。
  9. const SEARCH_DEBOUNCE = 400
  10. Page({
  11. data: {
  12. activeCategory: initialCategory.key,
  13. title: initialCategory.title,
  14. categoryIcon: initialCategory.icon,
  15. items: [] as CultureItem[],
  16. keyword: '',
  17. supportsFilters: false,
  18. filters: createCultureFilters(),
  19. filterOptions: createCultureFilterOptions(),
  20. failedImages: {} as Record<string, boolean>,
  21. statusBarHeight: 20,
  22. navHeight: 44,
  23. navRightPadding: 100,
  24. scrollTop: 0,
  25. remoteCategory: '' as CultureCategoryKey | '',
  26. optionsLoaded: false,
  27. loading: false,
  28. loadError: '',
  29. hasMore: false,
  30. nextPage: 1,
  31. requestVersion: 0,
  32. searchTimer: 0,
  33. refreshing: false,
  34. },
  35. onLoad(options) {
  36. const { statusBarHeight, navHeight, navRightPadding } = getNavBarLayout()
  37. const category = findCultureCategory(options.category)
  38. const remoteCategory = category.key
  39. this.setData({
  40. statusBarHeight,
  41. navHeight,
  42. navRightPadding,
  43. activeCategory: category.key,
  44. title: category.title,
  45. categoryIcon: category.icon,
  46. items: [],
  47. supportsFilters: !!category.supportsFilters,
  48. remoteCategory,
  49. keyword: options.keyword || '',
  50. filters: category.supportsFilters ? { category: options.categoryId || '', level: options.levelId || '', district: options.districtId || '' } : createCultureFilters(),
  51. filterOptions: createCultureFilterOptions(),
  52. })
  53. wx.setNavigationBarTitle({ title: category.title })
  54. return this.loadItems()
  55. },
  56. onUnload() {
  57. this.cancelPendingSearch()
  58. this.data.requestVersion++
  59. },
  60. cancelPendingSearch() {
  61. if (this.data.searchTimer) {
  62. clearTimeout(this.data.searchTimer)
  63. this.data.searchTimer = 0
  64. }
  65. },
  66. async onPullRefresh() {
  67. this.setData({ refreshing: true })
  68. await runRefresh([this.loadItems(true, true)])
  69. this.setData({ refreshing: false })
  70. },
  71. // refresh 为下拉刷新:保留当前列表直到新数据返回,已有内容时失败只提示不清空。
  72. async loadItems(reset = true, refresh = false) {
  73. const { remoteCategory, keyword, filters, optionsLoaded, supportsFilters } = this.data
  74. if (!remoteCategory) {
  75. return
  76. }
  77. // 任何重新加载都已带上最新关键词,未触发的延迟搜索可以丢弃。
  78. if (reset) {
  79. this.cancelPendingSearch()
  80. }
  81. const requestVersion = ++this.data.requestVersion
  82. const page = reset ? 1 : this.data.nextPage
  83. if (!refresh) {
  84. this.setData({ loading: true, loadError: '', ...(reset ? { items: [], hasMore: false, scrollTop: 0, failedImages: {} } : {}) })
  85. }
  86. try {
  87. const [options, result] = await Promise.all([
  88. !supportsFilters || optionsLoaded ? Promise.resolve(null) : getInheritCategories(),
  89. getCultureList(remoteCategory, { keyword, categoryId: filters.category, levelId: filters.level, districtId: filters.district }, page),
  90. ])
  91. // 搜索或筛选改变后,丢弃旧请求及旧分页结果。
  92. if (requestVersion !== this.data.requestVersion) {
  93. return
  94. }
  95. if (options) {
  96. const groups = { category: options.categories, level: options.levels, district: options.districts }
  97. this.setData({
  98. optionsLoaded: true,
  99. filterOptions: createCultureFilterOptions().map((option) => {
  100. const values = groups[option.key]
  101. const ids = ['', ...values.map(item => item.id)]
  102. const names = [option.options[0], ...values.map(item => item.name)]
  103. const index = Math.max(0, ids.indexOf(filters[option.key]))
  104. return { ...option, ids, options: names, index, value: index ? names[index] : '' }
  105. }),
  106. })
  107. }
  108. this.setData({
  109. items: reset ? result.items : [...this.data.items, ...result.items],
  110. ...(refresh ? { failedImages: {} } : {}),
  111. loading: false,
  112. loadError: '',
  113. hasMore: result.hasMore,
  114. nextPage: page + 1,
  115. })
  116. }
  117. catch (error) {
  118. if (requestVersion !== this.data.requestVersion) {
  119. return
  120. }
  121. // 刷新会作废进行中的加载更多,这里统一结束加载态。
  122. if (refresh && this.data.items.length) {
  123. this.setData({ loading: false })
  124. throw error
  125. }
  126. this.setData({ loading: false, loadError: error instanceof Error ? error.message : '数据加载失败,请稍后重试' })
  127. }
  128. },
  129. onLoadMore() {
  130. if (this.data.remoteCategory && this.data.hasMore && !this.data.loading && !this.data.loadError) {
  131. return this.loadItems(false)
  132. }
  133. },
  134. onRetry() {
  135. return this.loadItems(!this.data.items.length)
  136. },
  137. onSearchInput(e: WechatMiniprogram.Input) {
  138. const keyword = e.detail.value
  139. this.setData({ keyword })
  140. this.cancelPendingSearch()
  141. this.data.searchTimer = setTimeout(() => {
  142. this.data.searchTimer = 0
  143. this.loadItems()
  144. }, SEARCH_DEBOUNCE)
  145. },
  146. onSearchConfirm() {
  147. // 点击键盘“搜索”时立即执行尚未触发的延迟搜索。
  148. if (this.data.searchTimer) {
  149. return this.loadItems()
  150. }
  151. },
  152. onClearSearch() {
  153. this.setData({ keyword: '' })
  154. return this.loadItems()
  155. },
  156. onFilterChange(e: WechatMiniprogram.PickerChange) {
  157. const key = e.currentTarget.dataset.key
  158. const option = this.data.filterOptions.find(option => option.key === key)
  159. const index = Number(e.detail.value)
  160. if (!this.data.supportsFilters || (this.data.remoteCategory && !this.data.optionsLoaded) || !option || !Number.isInteger(index) || !option.options[index]) {
  161. return
  162. }
  163. const value = option.ids ? option.ids[index] : index === 0 ? '' : option.options[index]
  164. const filters = { ...this.data.filters, [option.key]: value }
  165. // 三个筛选条件与搜索同时生效;清除搜索只清关键词,保留筛选选择。
  166. this.setData({
  167. filters,
  168. filterOptions: this.data.filterOptions.map(item => item.key === option.key ? { ...item, index, value: index ? item.options[index] : '' } : item),
  169. })
  170. return this.loadItems()
  171. },
  172. onResetFilters() {
  173. this.setData({
  174. keyword: '',
  175. filters: createCultureFilters(),
  176. filterOptions: this.data.filterOptions.map(option => ({ ...option, index: 0, value: '' })),
  177. })
  178. return this.loadItems()
  179. },
  180. onItemTap(e: WechatMiniprogram.CustomEvent) {
  181. const id = e.currentTarget.dataset.id as string
  182. if (id) {
  183. wx.navigateTo({ url: getArticleDetailUrl(id) })
  184. }
  185. },
  186. onImageError(e: WechatMiniprogram.CustomEvent) {
  187. const id = e.currentTarget.dataset.id as string
  188. this.setData({ [`failedImages.${id}`]: true })
  189. },
  190. onListScroll(e: WechatMiniprogram.CustomEvent) {
  191. // 保存实际滚动位置,搜索时设为 0 才能触发滚动复位。
  192. this.data.scrollTop = e.detail.scrollTop
  193. },
  194. onBack() {
  195. if (getCurrentPages().length > 1) {
  196. wx.navigateBack()
  197. }
  198. else {
  199. wx.switchTab({ url: '/pages/home/home' })
  200. }
  201. },
  202. })