Socialify

Folder ..

Viewing preview.tsx
218 lines (204 loc) • 7.1 KB

  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
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import React, { useContext } from 'react'
import classnames from 'clsx'
import Head from 'next/head'
import Router from 'next/router'
import { toClipboard } from 'copee'
import { MdContentCopy, MdDownload } from 'react-icons/md'

import toaster from '../toaster'

import ConfigContext from '../../contexts/ConfigContext'
import { checkWebpSupport } from '../../../common/helpers'
import Card from './card'

const getRelativeImageUrl = (format = 'image') => {
  const [path, query] = Router.asPath.split('?')
  return `${path}/${format}${query ? `?${query}` : ''}`
}

const getImageUrl = (format = 'image') => {
  return `${window.location.protocol}//${
    window.location.host
  }${getRelativeImageUrl(format)}`
}

const copyImageUrl = () => {
  const screenshotImageUrl = getImageUrl()
  const success = toClipboard(screenshotImageUrl)
  if (success) {
    toaster.success('Copied image url to clipboard')
  } else {
    window.open(screenshotImageUrl, '_blank')
  }
}

const copyMarkdown = () => {
  const screenshotImageUrl = getImageUrl()
  const ogTag = `![${Router.query._name}](${screenshotImageUrl})`
  const success = toClipboard(ogTag)
  if (success) {
    toaster.success('Copied markdown to clipboard')
  }
}

const copyImageTag = () => {
  const screenshotImageUrl = getImageUrl()
  const ogTag = `<img src="${screenshotImageUrl}" alt="${Router.query._name}" width="640" height="320" />`
  const success = toClipboard(ogTag)
  if (success) {
    toaster.success('Copied image tag to clipboard')
  }
}

const copyOpenGraphTags = () => {
  const ogTag = `
<meta property="og:image" content="${getImageUrl('png')}" />
<meta property="og:image:width" content="1280" />
<meta property="og:image:height" content="640" />
  `.trim()
  const success = toClipboard(ogTag)
  if (success) {
    toaster.success('Copied open graph tags to clipboard')
  }
}

const handleDownload = (fileType: string) => async () => {
  toaster.info('Downloading...')

  try {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = 1280
      canvas.height = 640
      const context = canvas.getContext('2d')
      if (context && img) {
        context.drawImage(img, 0, 0, canvas.width, canvas.height)
        const dataUrl = canvas.toDataURL(`image/${fileType}`)
        const link = document.createElement('a')
        link.download = `${Router.query._name}.${fileType}`
        link.href = dataUrl
        link.click()
      }
    }
    img.src = getRelativeImageUrl()
  } catch (error) {
    toaster.error('Download failed: Please use a modern browser.')
    console.error(error)
  }
}

const openRelativeURLInNewTab = (fileType: string) => async () => {
  window.open(getRelativeImageUrl(fileType), '_blank')
}

const Preview: React.FC = () => {
  const { config } = useContext(ConfigContext)

  return (
    <section className="mb-3">
      <div
        className={classnames(
          'relative cursor-pointer rounded-lg shadow-2xl overflow-hidden',
          'w-[320px] h-[160px]',
          'min-[384px]:w-[384px] min-[384px]:h-[192px]',
          'min-[400px]:w-[400px] min-[400px]:h-[200px]',
          'min-[480px]:w-[480px] min-[480px]:h-[240px]',
          'min-[640px]:w-[640px] min-[640px]:h-[320px]'
        )}
        onClick={copyImageUrl}>
        <div
          className={classnames(
            'origin-top-left',
            'scale-[0.25]',
            'min-[384px]:scale-[0.3]',
            'min-[400px]:scale-[0.3125]',
            'min-[480px]:scale-[0.375]',
            'min-[640px]:scale-[0.5]'
          )}>
          <Head>
            <link
              href={`https://fonts.googleapis.com/css2?family=Jost:wght@400&display=swap`}
              rel="stylesheet"
              key="preview-card-fonts-1"
            />
            <link
              href={`https://fonts.googleapis.com/css2?family=${config.font}:wght@200;400;500&display=swap`}
              rel="stylesheet"
              key="preview-card-fonts-2"
            />
          </Head>
          <Card {...config} />
        </div>
        <img
          className="absolute top-0 left-0 w-full h-full opacity-0"
          alt="Card"
          src={getRelativeImageUrl()}
        />
      </div>
      <div className="card mt-3 mx-auto w-fit bg-base-100 shadow-xl">
        <div className="card-body px-3 py-2">
          <div
            className={classnames('flex justify-center content-center gap-2')}>
            <div className="dropdown">
              <label tabIndex={0} className="btn btn-primary btn-sm gap-2">
                <MdDownload className="w-5 h-5" />
                Download
              </label>
              <ul
                style={{ width: 'auto' }}
                tabIndex={0}
                className="dropdown-content menu menu-compact p-2 shadow bg-base-100 rounded-box w-52">
                {(checkWebpSupport()
                  ? ['png', 'jpeg', 'webp']
                  : ['png', 'jpeg']
                ).map((fileType) => (
                  <li key={fileType}>
                    {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
                    <a
                      className="font-bold gap-2"
                      onClick={handleDownload(fileType)}>
                      <MdDownload className="w-5 h-5" />
                      {`${config.name?.value ?? ''}.${fileType}`}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
            <div className="dropdown">
              <label tabIndex={0} className="btn btn-primary btn-sm gap-2">
                API URL
              </label>
              <ul
                style={{ width: 'auto' }}
                tabIndex={0}
                className="dropdown-content menu menu-compact p-2 shadow bg-base-100 rounded-box w-52">
                {['svg', 'png'].map((fileType) => (
                  <li key={fileType}>
                    {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
                    <a
                      className="font-bold gap-2"
                      onClick={openRelativeURLInNewTab(fileType)}
                      target="_blank"
                      rel="noopener noreferrer">
                      {`${config.name?.value ?? ''}.${fileType}`}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
            <div className="btn-group">
              <button className="btn btn-sm gap-2" onClick={copyImageUrl}>
                <MdContentCopy className="w-4 h-4" />
                Url
              </button>
              <button
                className="btn btn-sm hidden sm:inline-flex"
                onClick={copyMarkdown}>
                Markdown
              </button>
              <button
                className="btn btn-sm hidden sm:inline-flex"
                onClick={copyImageTag}>
                {'<img />'}
              </button>
              <button
                className="btn btn-sm gap-2 hidden sm:inline-flex"
                onClick={copyOpenGraphTags}>
                Open Graph
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}

export default Preview