feat: 공유를 비율 고르기 + 공유하기 하나로 줄이고 이미지에 행사 사진·우리 주소 넣기
- 공유 이미지 9:16·4:5·1:1, 위 로고·지역 날짜 / 카드 / 아래 주소 알약 (시안 A) - 2장 카드는 한 이미지에 묶음, 버튼만 빼고 링크(장소)는 남김 - 웹폰트는 카드 글자에 필요한 조각만 data URL 로 넣어 글꼴이 안 깨지게 - 문구 고르기·링크 복사 제거, 공유하기 한 번에 이미지 + 제목·주소 글 - 행사 사진은 백엔드 /v1/image 가 대신 받음 (IMAGE_PROXY_HOSTS 만 허용) - 공유 주소는 VITE_SITE_URL 하나로
This commit is contained in:
1 parent
2fde88df27
commit
5e2846ff72
17 files changed
+432
-135
No files matched your search
+52
-94
@@ -1,6 +1,7 @@
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { setTokens, subscribeAuth } from '../api/auth'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import {
|
||||
addCommentMutation,
|
||||
deleteCommentMutation,
|
||||
@@ -24,7 +25,7 @@ import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { storyImage } from './storyImage'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Avatar, Ic, Skel, StateBox } from './ui'
|
||||
@@ -446,138 +447,95 @@ function SeasonWeekSheet() {
|
||||
}
|
||||
|
||||
/* ---------- 보내기 ---------- */
|
||||
const SIZE_KEYS = Object.keys(SHARE_SIZES) as ShareSize[]
|
||||
|
||||
function ShareSheet({ share }: { share: SharePayload }) {
|
||||
const { region } = useRegion()
|
||||
const opts = [...share.messages, '직접 쓰기']
|
||||
const [pick, setPick] = useState(0)
|
||||
const [mine, setMine] = useState('')
|
||||
const [toast, setToast] = useState('')
|
||||
const isMine = pick === opts.length - 1
|
||||
const msg = isMine ? mine : opts[pick]
|
||||
|
||||
const url = window.location.origin
|
||||
const text = msg.trim() ? `${msg} — ${share.title} · 날씨각` : `${share.title} · 날씨각`
|
||||
const { kind } = useSky()
|
||||
const [image, setImage] = useState<{ blob: Blob; src: string } | null>(null)
|
||||
const [imageError, setImageError] = useState(false)
|
||||
const [size, setSize] = useState<ShareSize>('story')
|
||||
const [images, setImages] = useState<Partial<Record<ShareSize, { blob: Blob; src: string }>>>({})
|
||||
const [failed, setFailed] = useState<Partial<Record<ShareSize, boolean>>>({})
|
||||
const srcs = useRef<string[]>([])
|
||||
const [toast, setToast] = useState('')
|
||||
const image = images[size]
|
||||
const text = `${share.title} · 날씨각 ${SITE_URL}`
|
||||
|
||||
// 창이 열리면 카드를 스토리 크기 이미지로 미리 만들어 둔다
|
||||
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
|
||||
useEffect(() => {
|
||||
if (!share.card) return
|
||||
let src = ''
|
||||
if (images[size] || failed[size]) return
|
||||
let alive = true
|
||||
storyImage(share.card, { title: share.title, sub: `${region.name} · 날씨각`, sky: kind }).then(
|
||||
const today = new Date().toLocaleDateString('ko-KR', { month: 'long', day: 'numeric', weekday: 'long' })
|
||||
shareImage(share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
|
||||
(blob) => {
|
||||
if (!alive) return
|
||||
src = URL.createObjectURL(blob)
|
||||
setImage({ blob, src })
|
||||
const src = URL.createObjectURL(blob)
|
||||
srcs.current.push(src)
|
||||
setImages((m) => ({ ...m, [size]: { blob, src } }))
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[share] story image', e)
|
||||
if (alive) setImageError(true)
|
||||
console.error('[share] image', e)
|
||||
if (alive) setFailed((m) => ({ ...m, [size]: true }))
|
||||
},
|
||||
)
|
||||
return () => {
|
||||
alive = false
|
||||
if (src) URL.revokeObjectURL(src)
|
||||
}
|
||||
}, [share.card, share.title, region.name, kind])
|
||||
}, [size, images, failed, share.slides, kind, region.name])
|
||||
|
||||
// 휴대폰은 공유창에 이미지 파일을 넘기고(인스타 스토리·카톡 등), 안 되면 이미지를 내려받는다
|
||||
const shareImage = () => {
|
||||
useEffect(() => {
|
||||
const list = srcs.current
|
||||
return () => list.forEach((s) => URL.revokeObjectURL(s))
|
||||
}, [])
|
||||
|
||||
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 공유창이 없으면 이미지를 내려받고 링크를 복사한다
|
||||
const send = () => {
|
||||
if (!image) return
|
||||
const file = new File([image.blob], 'nalssigak.png', { type: 'image/png' })
|
||||
if (navigator.canShare?.({ files: [file] })) {
|
||||
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
|
||||
if (navigator.canShare?.({ files: [file], text })) {
|
||||
navigator.share({ files: [file], title: share.title, text }).then(
|
||||
() => setToast('보냈어요'),
|
||||
(e: unknown) => {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') return
|
||||
setToast('공유하지 못했어요. 이미지를 내려받아 올려 주세요')
|
||||
console.error('[share] send', e)
|
||||
setToast('보내지 못했어요. 한 번 더 눌러 주세요')
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
const a = document.createElement('a')
|
||||
a.href = image.src
|
||||
a.download = 'nalssigak.png'
|
||||
a.download = file.name
|
||||
a.click()
|
||||
setToast('이미지를 내려받았어요. 인스타 스토리에 올려 보세요')
|
||||
}
|
||||
|
||||
// 휴대폰 기본 공유창. 없거나 실패하면 링크 복사로 대신한다.
|
||||
const shareNative = () => {
|
||||
if (!navigator.share) {
|
||||
copy()
|
||||
return
|
||||
}
|
||||
navigator.share({ title: share.title, text, url }).then(
|
||||
() => setToast('보냈어요'),
|
||||
(e: unknown) => {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') return
|
||||
copy()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const copy = () => {
|
||||
if (!navigator.clipboard) {
|
||||
setToast('복사가 막혀 있어요')
|
||||
setToast('이미지를 내려받았어요')
|
||||
return
|
||||
}
|
||||
navigator.clipboard.writeText(`${text} ${url}`).then(
|
||||
() => setToast('보낼 말과 링크를 복사했어요'),
|
||||
() => setToast('복사가 막혀 있어요. 길게 눌러 복사해 주세요'),
|
||||
navigator.clipboard.writeText(text).then(
|
||||
() => setToast('이미지를 내려받고 링크를 복사했어요'),
|
||||
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Body>
|
||||
<div className={cx('flex items-center gap-3 rounded-[20px] p-3.5', `b-bg-${share.bg}`)}>
|
||||
<Ic name={share.icon} className="w-[58px]" />
|
||||
<div>
|
||||
<b className="block font-jua text-[19px] font-normal">{share.title}</b>
|
||||
<small className="font-bold opacity-80">날씨각 · {region.name}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-col gap-1.5" role="radiogroup" aria-label="함께 보낼 말">
|
||||
{opts.map((o, k) => (
|
||||
<label key={o} className="flex cursor-pointer items-center gap-2.5 rounded-[14px] bg-[#f3f6fb] px-3 py-2.5 font-semibold">
|
||||
<input type="radio" name="share-msg" checked={pick === k} onChange={() => setPick(k)} className="accent-(--orange)" />
|
||||
{o}
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 rounded-[16px] bg-[#f3f6fb] p-1" role="radiogroup" aria-label="이미지 크기">
|
||||
{SIZE_KEYS.map((k) => (
|
||||
<button key={k} type="button" role="radio" aria-checked={size === k} aria-label={`${SHARE_SIZES[k].ratio} 비율`} onClick={() => setSize(k)} className={cx('flex cursor-pointer items-center justify-center gap-2 rounded-[12px] py-2 text-sm font-extrabold', size === k ? 'bg-white text-(--ink) shadow-[0_2px_6px_rgb(40_48_74/0.12)]' : 'text-(--ink3)')}>
|
||||
<i className="h-4 rounded-[3px] border-2 border-current" style={{ aspectRatio: `${SHARE_SIZES[k].w} / ${SHARE_SIZES[k].hr}` }} aria-hidden="true" />
|
||||
{SHARE_SIZES[k].ratio}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{isMine && (
|
||||
<textarea
|
||||
value={mine}
|
||||
onChange={(e) => setMine(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={80}
|
||||
placeholder="예: 오늘 한강 갈래? 🌇"
|
||||
aria-label="보낼 말 직접 쓰기"
|
||||
className="mt-1.5 w-full resize-none rounded-[14px] border border-[#dfe5ee] px-3 py-2.5"
|
||||
/>
|
||||
)}
|
||||
{share.card && (
|
||||
<div className="mt-3.5 flex items-center gap-3 rounded-[18px] bg-[#f3f6fb] p-2.5">
|
||||
{image ? <img src={image.src} alt="공유할 이미지 미리보기" className="h-28 rounded-[10px] shadow-[0_4px_10px_rgb(40_48_74/0.15)]" /> : <span className="grid h-28 w-16 place-items-center rounded-[10px] bg-white text-xs font-bold text-(--ink3)">{imageError ? '실패' : '만드는 중'}</span>}
|
||||
<div className="flex flex-1 flex-col gap-1.5">
|
||||
<b className="text-sm font-extrabold">이미지로 보내기</b>
|
||||
<small className="text-xs font-semibold text-(--ink2)">인스타 스토리 크기(9:16)로 만들어요</small>
|
||||
<button type="button" onClick={shareImage} disabled={!image} className="cursor-pointer rounded-[14px] bg-(--orange) py-2.5 font-jua text-[15px] text-white shadow-[inset_0_-4px_0_var(--orange-deep)] disabled:opacity-50">
|
||||
이미지 공유하기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-3.5 grid grid-cols-2 gap-2">
|
||||
<button type="button" onClick={shareNative} className="cursor-pointer rounded-[16px] bg-(--orange-deep) py-3 font-jua text-base text-white">
|
||||
공유하기
|
||||
</button>
|
||||
<button type="button" onClick={copy} className="cursor-pointer rounded-[16px] bg-(--ink) py-3 font-jua text-base text-white">
|
||||
링크 복사
|
||||
</button>
|
||||
<div className="mt-3 flex h-[300px] items-center justify-center rounded-[18px] bg-[#f3f6fb] p-3">
|
||||
{image ? (
|
||||
<img src={image.src} alt={`${SHARE_SIZES[size].ratio} 공유 이미지 미리보기`} className="max-h-full max-w-full rounded-[10px] shadow-[0_4px_12px_rgb(40_48_74/0.18)]" />
|
||||
) : (
|
||||
<span className="text-sm font-bold text-(--ink3)">{failed[size] ? '이미지를 만들지 못했어요' : '이미지 만드는 중'}</span>
|
||||
)}
|
||||
</div>
|
||||
<button type="button" onClick={send} disabled={!image} className="mt-3.5 block w-full cursor-pointer rounded-[16px] bg-(--orange) py-3 font-jua text-base text-white shadow-[inset_0_-4px_0_var(--orange-deep)] disabled:opacity-50">
|
||||
공유하기
|
||||
</button>
|
||||
<p className="mt-3 min-h-5 text-center text-[13px] font-bold text-[#1f9d62]" aria-live="polite">
|
||||
{toast}
|
||||
</p>
|
||||
|
||||
Reference in new issue
Block a user