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.

203 lines
6.8 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.sendSticker = this.sendSticker.bind(this)
  38. }
  39. _getStickersByID(ids) {
  40. return ids.map(id => this.stickersByID.get(id)).filter(sticker => !!sticker)
  41. }
  42. updateFrequentlyUsed() {
  43. const stickerIDs = frequent.get()
  44. const stickers = this._getStickersByID(stickerIDs)
  45. this.setState({
  46. frequentlyUsed: {
  47. ...this.state.frequentlyUsed,
  48. stickerIDs,
  49. stickers
  50. }
  51. })
  52. localStorage.mauFrequentlyUsedStickerCache = JSON.stringify(stickers.map(sticker => [sticker.id, sticker]))
  53. }
  54. componentDidMount() {
  55. fetch(`${PACKS_BASE_URL}/index.json`).then(async indexRes => {
  56. if (indexRes.status >= 400) {
  57. this.setState({
  58. loading: false,
  59. error: indexRes.status !== 404 ? indexRes.statusText : null,
  60. })
  61. return
  62. }
  63. const indexData = await indexRes.json()
  64. HOMESERVER_URL = indexData.homeserver_url || HOMESERVER_URL
  65. // TODO only load pack metadata when scrolled into view?
  66. for (const packFile of indexData.packs) {
  67. const packRes = await fetch(`${PACKS_BASE_URL}/${packFile}`)
  68. const packData = await packRes.json()
  69. for (const sticker of packData.stickers) {
  70. this.stickersByID.set(sticker.id, sticker)
  71. }
  72. this.setState({
  73. packs: [...this.state.packs, packData],
  74. loading: false,
  75. })
  76. }
  77. this.updateFrequentlyUsed()
  78. }, error => this.setState({ loading: false, error }))
  79. this.imageObserver = new IntersectionObserver(this.observeImageIntersections, {
  80. rootMargin: "100px",
  81. })
  82. this.sectionObserver = new IntersectionObserver(this.observeSectionIntersections)
  83. }
  84. observeImageIntersections(intersections) {
  85. for (const entry of intersections) {
  86. const img = entry.target.children.item(0)
  87. if (entry.isIntersecting) {
  88. img.setAttribute("src", img.getAttribute("data-src"))
  89. img.classList.add("visible")
  90. } else {
  91. img.removeAttribute("src")
  92. img.classList.remove("visible")
  93. }
  94. }
  95. }
  96. observeSectionIntersections(intersections) {
  97. for (const entry of intersections) {
  98. const packID = entry.target.getAttribute("data-pack-id")
  99. const navElement = document.getElementById(`nav-${packID}`)
  100. if (entry.isIntersecting) {
  101. navElement.classList.add("visible")
  102. } else {
  103. navElement.classList.remove("visible")
  104. }
  105. }
  106. }
  107. componentDidUpdate() {
  108. for (const elem of this.packListRef.getElementsByClassName("sticker")) {
  109. this.imageObserver.observe(elem)
  110. }
  111. for (const elem of this.packListRef.children) {
  112. this.sectionObserver.observe(elem)
  113. }
  114. }
  115. componentWillUnmount() {
  116. this.imageObserver.disconnect()
  117. this.sectionObserver.disconnect()
  118. }
  119. sendSticker(evt) {
  120. const id = evt.currentTarget.getAttribute("data-sticker-id")
  121. const sticker = this.stickersByID.get(id)
  122. frequent.add(id)
  123. this.updateFrequentlyUsed()
  124. widgetAPI.sendSticker(sticker)
  125. }
  126. render() {
  127. if (this.state.loading) {
  128. return html`<main class="spinner"><${Spinner} size=${80} green /></main>`
  129. } else if (this.state.error) {
  130. return html`<main class="error">
  131. <h1>Failed to load packs</h1>
  132. <p>${this.state.error}</p>
  133. </main>`
  134. } else if (this.state.packs.length === 0) {
  135. return html`<main class="empty"><h1>No packs found 😿</h1></main>`
  136. }
  137. return html`<main class="has-content">
  138. <nav>
  139. <${NavBarItem} pack=${this.state.frequentlyUsed} iconOverride="res/recent.svg" altOverride="🕓️" />
  140. ${this.state.packs.map(pack => html`<${NavBarItem} id=${pack.id} pack=${pack}/>`)}
  141. </nav>
  142. <div class="pack-list ${isMobileSafari ? "ios-safari-hack" : ""}" ref=${elem => this.packListRef = elem}>
  143. <${Pack} pack=${this.state.frequentlyUsed} send=${this.sendSticker} />
  144. ${this.state.packs.map(pack => html`<${Pack} id=${pack.id} pack=${pack} send=${this.sendSticker} />`)}
  145. </div>
  146. </main>`
  147. }
  148. }
  149. // By default we just let the browser handle scrolling to sections, but webviews on Element iOS
  150. // open the link in the browser instead of just scrolling there, so we need to scroll manually:
  151. const scrollToSection = (evt, id) => {
  152. const pack = document.getElementById(`pack-${id}`)
  153. pack.scrollIntoView({ block: "start", behavior: "instant" })
  154. evt.preventDefault()
  155. }
  156. const NavBarItem = ({ pack, iconOverride = null, altOverride = null }) => html`
  157. <a href="#pack-${pack.id}" id="nav-${pack.id}" data-pack-id=${pack.id} title=${pack.title}
  158. onClick=${isMobileSafari ? (evt => scrollToSection(evt, pack.id)) : undefined}>
  159. <div class="sticker ${iconOverride ? "icon" : ""}">
  160. ${iconOverride ? html`
  161. <img src=${iconOverride} alt=${altOverride} class="visible"/>
  162. ` : html`
  163. <img src=${makeThumbnailURL(pack.stickers[0].url)}
  164. alt=${pack.stickers[0].body} class="visible" />
  165. `}
  166. </div>
  167. </a>
  168. `
  169. const Pack = ({ pack, send }) => html`
  170. <section class="stickerpack" id="pack-${pack.id}" data-pack-id=${pack.id}>
  171. <h1>${pack.title}</h1>
  172. <div class="sticker-list">
  173. ${pack.stickers.map(sticker => html`
  174. <${Sticker} key=${sticker.id} content=${sticker} send=${send}/>
  175. `)}
  176. </div>
  177. </section>
  178. `
  179. const Sticker = ({ content, send }) => html`
  180. <div class="sticker" onClick=${send} data-sticker-id=${content.id}>
  181. <img data-src=${makeThumbnailURL(content.url)} alt=${content.body} />
  182. </div>
  183. `
  184. render(html`<${App} />`, document.body)