about summary refs log tree commit diff
path: root/src/view/com/composer/useExternalLinkFetch.e2e.ts
blob: 257a3e8e526f42a35c342dc7c6389f306d9b476b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import {useEffect, useState} from 'react'

import {useAgent} from '#/state/session'
import * as apilib from 'lib/api/index'
import {getLinkMeta} from 'lib/link-meta/link-meta'
import {ComposerOpts} from 'state/shell/composer'

export function useExternalLinkFetch({}: {
  setQuote: (opts: ComposerOpts['quote']) => void
}) {
  const agent = useAgent()
  const [extLink, setExtLink] = useState<apilib.ExternalEmbedDraft | undefined>(
    undefined,
  )

  useEffect(() => {
    let aborted = false
    const cleanup = () => {
      aborted = true
    }
    if (!extLink) {
      return cleanup
    }
    if (!extLink.meta) {
      getLinkMeta(agent, extLink.uri).then(meta => {
        if (aborted) {
          return
        }
        setExtLink({
          uri: extLink.uri,
          isLoading: !!meta.image,
          meta,
        })
      })
      return cleanup
    }
    if (extLink.isLoading) {
      setExtLink({
        ...extLink,
        isLoading: false, // done
      })
    }
    return cleanup
  }, [extLink, agent])

  return {extLink, setExtLink}
}