You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

209 lines
6.9 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. // Copyright (c) 2020 Tulir Asokan
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. import { html, render, Component } from "https://unpkg.com/htm/preact/index.mjs?module"
  7. import { Spinner } from "./spinner.js"
  8. import * as widgetAPI from "./widget-api.js"
  9. import * as frequent from "./frequently-used.js"
  10. // The base URL for fetching packs. The app will first fetch ${PACK_BASE_URL}/index.json,
  11. // then ${PACK_BASE_URL}/${packFile} for each packFile in the packs object of the index.json file.
  12. const PACKS_BASE_URL = "packs"
  13. // This is updated from packs/index.json
  14. let HOMESERVER_URL = "https://matrix-client.matrix.org"
  15. const makeThumbnailURL = mxc => `${HOMESERVER_URL}/_matrix/media/r0/thumbnail/${mxc.substr(6)}?height=128&width=128&method=scale`
  16. // We need to detect iOS webkit because it has a bug related to scrolling non-fixed divs
  17. // This is also used to fix scrolling to sections on Element iOS
  18. const isMobileSafari = navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/)
  19. class App extends Component {
  20. constructor(props) {
  21. super(props)
  22. this.state = {
  23. packs: [],
  24. loading: true,
  25. error: null,
  26. frequentlyUsed: {
  27. id: "frequently-used",
  28. title: "Frequently used",
  29. stickerIDs: frequent.get(),
  30. stickers: [],
  31. },
  32. }
  33. this.stickersByID = new Map(JSON.parse(localStorage.mauFrequentlyUsedStickerCache || "[]"))
  34. this.state.frequentlyUsed.stickers = this._getStickersByID(this.state.frequentlyUsed.stickerIDs)
  35. this.imageObserver = null
  36. this.packListRef = null
  37. this.navRef = null
  38. this.sendSticker = this.sendSticker.bind(this)
  39. this.navScroll = this.navScroll.bind(this)
  40. }
  41. _getStickersByID(ids) {
  42. return ids.map(id => this.stickersByID.get(id)).filter(sticker => !!sticker)
  43. }
  44. updateFrequentlyUsed() {
  45. const stickerIDs = frequent.get()
  46. const stickers = this._getStickersByID(stickerIDs)
  47. this.setState({
  48. frequentlyUsed: {
  49. ...this.state.frequentlyUsed,
  50. stickerIDs,
  51. stickers
  52. }
  53. })
  54. localStorage.mauFrequentlyUsedStickerCache = JSON.stringify(stickers.map(sticker => [sticker.id, sticker]))
  55. }
  56. componentDidMount() {
  57. fetch(`${PACKS_BASE_URL}/index.json`).then(async indexRes => {
  58. if (indexRes.status >= 400) {
  59. this.setState({
  60. loading: false,
  61. error: indexRes.status !== 404 ? indexRes.statusText : null,
  62. })
  63. return
  64. }
  65. const indexData = await indexRes.json()
  66. HOMESERVER_URL = indexData.homeserver_url || HOMESERVER_URL
  67. // TODO only load pack metadata when scrolled into view?
  68. for (const packFile of indexData.packs) {
  69. const packRes = await fetch(`${PACKS_BASE_URL}/${packFile}`)
  70. const packData = await packRes.json()
  71. for (const sticker of packData.stickers) {
  72. this.stickersByID.set(sticker.id, sticker)
  73. }
  74. this.setState({
  75. packs: [...this.state.packs, packData],
  76. loading: false,
  77. })
  78. }
  79. this.updateFrequentlyUsed()
  80. }, error => this.setState({ loading: false, error }))
  81. this.imageObserver = new IntersectionObserver(this.observeImageIntersections, {
  82. rootMargin: "100px",
  83. })
  84. this.sectionObserver = new IntersectionObserver(this.observeSectionIntersections)
  85. }
  86. observeImageIntersections(intersections) {
  87. for (const entry of intersections) {
  88. const img = entry.target.children.item(0)
  89. if (entry.isIntersecting) {
  90. img.setAttribute("src", img.getAttribute("data-src"))
  91. img.classList.add("visible")
  92. } else {
  93. img.removeAttribute("src")
  94. img.classList.remove("visible")
  95. }
  96. }
  97. }
  98. observeSectionIntersections(intersections) {
  99. for (const entry of intersections) {
  100. const packID = entry.target.getAttribute("data-pack-id")
  101. const navElement = document.getElementById(`nav-${packID}`)
  102. if (entry.isIntersecting) {
  103. navElement.classList.add("visible")
  104. } else {
  105. navElement.classList.remove("visible")
  106. }
  107. }
  108. }
  109. componentDidUpdate() {
  110. for (const elem of this.packListRef.getElementsByClassName("sticker")) {
  111. this.imageObserver.observe(elem)
  112. }
  113. for (const elem of this.packListRef.children) {
  114. this.sectionObserver.observe(elem)
  115. }
  116. }
  117. componentWillUnmount() {
  118. this.imageObserver.disconnect()
  119. this.sectionObserver.disconnect()
  120. }
  121. sendSticker(evt) {
  122. const id = evt.currentTarget.getAttribute("data-sticker-id")
  123. const sticker = this.stickersByID.get(id)
  124. frequent.add(id)
  125. this.updateFrequentlyUsed()
  126. widgetAPI.sendSticker(sticker)
  127. }
  128. navScroll(evt) {
  129. this.navRef.scrollLeft += evt.deltaY * 12
  130. }
  131. render() {
  132. if (this.state.loading) {
  133. return html`<main class="spinner"><${Spinner} size=${80} green /></main>`
  134. } else if (this.state.error) {
  135. return html`<main class="error">
  136. <h1>Failed to load packs</h1>
  137. <p>${this.state.error}</p>
  138. </main>`
  139. } else if (this.state.packs.length === 0) {
  140. return html`<main class="empty"><h1>No packs found 😿</h1></main>`
  141. }
  142. return html`<main class="has-content">
  143. <nav onWheel=${this.navScroll} ref=${elem => this.navRef = elem}>
  144. <${NavBarItem} pack=${this.state.frequentlyUsed} iconOverride="res/recent.svg" altOverride="🕓️" />
  145. ${this.state.packs.map(pack => html`<${NavBarItem} id=${pack.id} pack=${pack}/>`)}
  146. </nav>
  147. <div class="pack-list ${isMobileSafari ? "ios-safari-hack" : ""}" ref=${elem => this.packListRef = elem}>
  148. <${Pack} pack=${this.state.frequentlyUsed} send=${this.sendSticker} />
  149. ${this.state.packs.map(pack => html`<${Pack} id=${pack.id} pack=${pack} send=${this.sendSticker} />`)}
  150. </div>
  151. </main>`
  152. }
  153. }
  154. // By default we just let the browser handle scrolling to sections, but webviews on Element iOS
  155. // open the link in the browser instead of just scrolling there, so we need to scroll manually:
  156. const scrollToSection = (evt, id) => {
  157. const pack = document.getElementById(`pack-${id}`)
  158. pack.scrollIntoView({ block: "start", behavior: "instant" })
  159. evt.preventDefault()
  160. }
  161. const NavBarItem = ({ pack, iconOverride = null, altOverride = null }) => html`
  162. <a href="#pack-${pack.id}" id="nav-${pack.id}" data-pack-id=${pack.id} title=${pack.title}
  163. onClick=${isMobileSafari ? (evt => scrollToSection(evt, pack.id)) : undefined}>
  164. <div class="sticker ${iconOverride ? "icon" : ""}">
  165. ${iconOverride ? html`
  166. <img src=${iconOverride} alt=${altOverride} class="visible"/>
  167. ` : html`
  168. <img src=${makeThumbnailURL(pack.stickers[0].url)}
  169. alt=${pack.stickers[0].body} class="visible" />
  170. `}
  171. </div>
  172. </a>
  173. `
  174. const Pack = ({ pack, send }) => html`
  175. <section class="stickerpack" id="pack-${pack.id}" data-pack-id=${pack.id}>
  176. <h1>${pack.title}</h1>
  177. <div class="sticker-list">
  178. ${pack.stickers.map(sticker => html`
  179. <${Sticker} key=${sticker.id} content=${sticker} send=${send}/>
  180. `)}
  181. </div>
  182. </section>
  183. `
  184. const Sticker = ({ content, send }) => html`
  185. <div class="sticker" onClick=${send} data-sticker-id=${content.id}>
  186. <img data-src=${makeThumbnailURL(content.url)} alt=${content.body} />
  187. </div>
  188. `
  189. render(html`<${App} />`, document.body)