feat: 공유를 비율 고르기 + 공유하기 하나로 줄이고 이미지에 행사 사진·우리 주소 넣기

- 공유 이미지 9:16·4:5·1:1, 위 로고·지역 날짜 / 카드 / 아래 주소 알약 (시안 A)
- 2장 카드는 한 이미지에 묶음, 버튼만 빼고 링크(장소)는 남김
- 웹폰트는 카드 글자에 필요한 조각만 data URL 로 넣어 글꼴이 안 깨지게
- 문구 고르기·링크 복사 제거, 공유하기 한 번에 이미지 + 제목·주소 글
- 행사 사진은 백엔드 /v1/image 가 대신 받음 (IMAGE_PROXY_HOSTS 만 허용)
- 공유 주소는 VITE_SITE_URL 하나로
This commit is contained in:
minaChoi committed 2026-10-07 15:43:18 +09:00
1 parent 2fde88df27
commit 5e2846ff72
17 files changed
+432 -135

No files matched your search

+3
View File
@@ -5,6 +5,7 @@
DATA_GO_KR_SERVICE_KEY=
# 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다.
TEAMS_WEBHOOK_URL=
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
DB_HOST=localhost
@@ -29,3 +30,5 @@ PG_BIND=
REDIS_BIND=
# 프론트가 부를 API 주소. 비우면 같은 주소의 /v1 (nginx 가 backend 로 넘김)
VITE_API_BASE_URL=
# 공유할 때 이미지·글에 나가는 우리 주소 (예: https://nalssigak.kr). 비우면 지금 보고 있는 주소
VITE_SITE_URL=
+5
View File
@@ -98,3 +98,8 @@
| [x] | 세션 여러 개가 같은 테스트 DB·Redis를 쓰면 서로 지움 — `TEST_DB_NAME`·`TEST_REDIS_DB`로 폴더마다 다르게 줄 수 있게 함 | 테스트 충돌 (10/7 두 번) | `backend/tests/conftest.py` |
| [x] | 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 돌아가며 고름 (사용자 결정). 피드 행사 카드(최대 3장)가 연주회로 채워짐 — 시작일이 오늘에 가까운 순이라 하루짜리 콘서트(서울 170건)가 위를 차지. 기획엔 "축제·행사"만 있고 콘서트·팝업을 어떻게 섞을지 없음. 안: 종류별 1장씩(축제·전시·팝업 우선) 또는 피드에서 콘서트 제외 | 사용자 지적 | `backend/services/week_service.py` (`events` 정렬), `backend/services/feed_service.py` (`PostType.EVENT`), `docs/피드_기획.html` |
| [ ] | 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 사진 기록·사용자 반응 등 후보 | 노을 탭 다시 기획 (10/7) | `backend/services/calc/sky_score.py` (`situation`) |
| [x] | 공유 이미지: 행사 카드의 장소(지도 링크)가 빠짐 — 버튼과 함께 `<a>`도 빼서 생김. 링크는 남기고 버튼만 빼야 함 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`keep`), `frontend/src/b/ui.tsx` (지도 링크) |
| [x] | 공유 이미지: 행사 사진은 백엔드 `/v1/image`(허용 호스트만)로 대신 받음 (사용자 결정). 행사 사진(한국관광공사·문화정보원)이 CORS 차단으로 하얗게 빠짐. 안: 백엔드가 사진을 대신 받아 주기 / 공유 때만 사진 대신 아이콘 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `backend` 이미지 응답 |
| [x] | 공유 이미지: 2장 카드는 한 이미지에 엇갈려 묶음 (사용자 결정). 여러 장 카드는 보고 있는 1장만 나감(주말 예보는 2번째 장 내용이 빠짐). 1장만 / 장마다 이미지 여러 장 / 2장을 한 이미지에 중 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `frontend/src/b/Post.tsx` (`share`) |
| [x] | 공유 이미지: 카드 아래 긴 제목이 한 줄 폭에 눌려 찌그러짐 — 두 줄 나눔 또는 말줄임 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`fillText`) |
| [x] | 공유 이미지: 카드 아래 제목을 빼고 주소 알약으로 바꿈 (시안 A, 사용자 결정). 카드 안 제목과 카드 아래 제목이 같아 두 번 보임. 아래 줄을 뺄지, 다른 말(지역·날짜)로 바꿀지 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` |
+6
View File
@@ -28,6 +28,8 @@ class Settings(BaseSettings):
data_go_kr_service_key: str = ""
teams_webhook_url: str = ""
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr"
jwt_access_secret: str = ""
jwt_refresh_secret: str = ""
@@ -40,6 +42,10 @@ class Settings(BaseSettings):
"""인코딩 키를 넣어도 디코딩해 둔다. httpx 가 다시 인코딩하므로 이중 인코딩을 막는다."""
return unquote(v) if "%" in v else v
@property
def image_proxy_host_set(self) -> frozenset[str]:
return frozenset(h.strip().lower() for h in self.image_proxy_hosts.split(",") if h.strip())
@property
def db_url(self) -> str:
return f"postgresql+asyncpg://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}"
+2
View File
@@ -9,6 +9,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
from common.models.gmodel import Res_WebPacketProtocol
from router.v1.auth.account import router as auth_router
from router.v1.feed.feed import router as feed_router
from router.v1.image.image import router as image_router
from router.v1.index.index import router as index_router
from router.v1.reaction.reaction import router as reaction_router
from router.v1.region.region import router as region_router
@@ -41,6 +42,7 @@ app.include_router(feed_router)
app.include_router(auth_router)
app.include_router(reaction_router)
app.include_router(watch_router)
app.include_router(image_router)
class Res_Health(Res_WebPacketProtocol):
View File
Whitespace-only changes.
+22
View File
@@ -0,0 +1,22 @@
import httpx
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import Response
from common.logger import LOG
from services.external.image_proxy import TIMEOUT_SEC, ImageFetchFailed, allowed, fetch_image
router = APIRouter(prefix="/v1/image", tags=["image"])
# 이미지 자체를 돌려주므로 다른 API 와 달리 실패는 HTTP 상태 코드로 알린다
@router.get("", summary="행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만)", responses={200: {"content": {"image/*": {}}}, 400: {}, 502: {}})
async def get_image(url: str = Query(..., max_length=2048, description="원본 이미지 주소")) -> Response:
if not allowed(url):
raise HTTPException(status_code=400, detail="url not allowed")
try:
async with httpx.AsyncClient(timeout=TIMEOUT_SEC, headers={"User-Agent": "nalssigak-bot"}) as client:
data, ctype = await fetch_image(client, url)
except (ImageFetchFailed, httpx.HTTPError) as e:
LOG.warning(f"[image] fetch failed {url}: {e!r}")
raise HTTPException(status_code=502, detail="image fetch failed") from e
return Response(content=data, media_type=ctype, headers={"Cache-Control": "public, max-age=86400", "X-Content-Type-Options": "nosniff"})
+39
View File
@@ -0,0 +1,39 @@
from urllib.parse import urlsplit
import httpx
from config.settings import settings
# 공유 이미지에 행사 사진을 그리려고 대신 받아 준다. 사진 서버가 브라우저가 픽셀을 읽는 것(CORS)을 막기 때문. 허용 호스트는 IMAGE_PROXY_HOSTS.
MAX_BYTES = 5 * 1024 * 1024
TIMEOUT_SEC = 10.0
class ImageFetchFailed(Exception):
pass
def allowed(url: str) -> bool:
"""https, 허용한 호스트, 기본 포트, 계정 정보 없음일 때만."""
try:
u = urlsplit(url)
port = u.port
except ValueError:
return False
return u.scheme == "https" and u.hostname in settings.image_proxy_host_set and port in (None, 443) and not u.username and not u.password
async def fetch_image(client: httpx.AsyncClient, url: str) -> tuple[bytes, str]:
"""이미지 바이트와 content-type. 리다이렉트는 따라가지 않는다."""
async with client.stream("GET", url, follow_redirects=False) as res:
if res.status_code != 200:
raise ImageFetchFailed(f"status {res.status_code}")
ctype = res.headers.get("content-type", "").split(";")[0].strip().lower()
if not ctype.startswith("image/") or ctype == "image/svg+xml":
raise ImageFetchFailed(f"content-type {ctype or '-'}")
buf = bytearray()
async for chunk in res.aiter_bytes():
buf += chunk
if len(buf) > MAX_BYTES:
raise ImageFetchFailed("too large")
return bytes(buf), ctype
+93
View File
@@ -0,0 +1,93 @@
import httpx
import pytest
from httpx import ASGITransport, AsyncClient
from router.router import app
from services.external import image_proxy
from services.external.image_proxy import ImageFetchFailed, allowed, fetch_image
OK_URL = "https://tong.visitkorea.or.kr/cms/resource/01/test_image.jpg"
@pytest.mark.parametrize("url,ok", [
(OK_URL, True),
("https://www.culture.go.kr/upload/test.jpg", True),
("http://tong.visitkorea.or.kr/cms/a.jpg", False),
("https://evil.example.com/a.jpg", False),
("https://tong.visitkorea.or.kr.evil.example.com/a.jpg", False),
("https://tong.visitkorea.or.kr:8443/a.jpg", False),
("https://user:pw@tong.visitkorea.or.kr/a.jpg", False),
("https://169.254.169.254/latest/meta-data", False),
("not a url", False),
])
def test_allowed(url, ok):
assert allowed(url) is ok
def _client(handler) -> httpx.AsyncClient:
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
@pytest.mark.anyio
async def test_fetch_image_returns_bytes_and_type():
async with _client(lambda r: httpx.Response(200, content=b"\xff\xd8jpeg", headers={"content-type": "image/jpeg; charset=binary"})) as c:
assert await fetch_image(c, OK_URL) == (b"\xff\xd8jpeg", "image/jpeg")
@pytest.mark.anyio
@pytest.mark.parametrize("res", [
httpx.Response(302, headers={"location": "https://evil.example.com/a.jpg"}),
httpx.Response(404),
httpx.Response(200, content=b"<html>", headers={"content-type": "text/html"}),
httpx.Response(200, content=b"<svg/>", headers={"content-type": "image/svg+xml"}),
])
async def test_fetch_image_rejects_redirect_error_and_non_image(res):
async with _client(lambda r: res) as c:
with pytest.raises(ImageFetchFailed):
await fetch_image(c, OK_URL)
@pytest.mark.anyio
async def test_fetch_image_rejects_too_large(monkeypatch):
monkeypatch.setattr(image_proxy, "MAX_BYTES", 10)
async with _client(lambda r: httpx.Response(200, content=b"x" * 11, headers={"content-type": "image/png"})) as c:
with pytest.raises(ImageFetchFailed):
await fetch_image(c, OK_URL)
@pytest.mark.anyio
async def test_image_api_blocks_other_hosts():
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
res = await c.get("/v1/image", params={"url": "https://evil.example.com/a.jpg"})
assert res.status_code == 400
@pytest.mark.anyio
async def test_image_api_serves_image_with_cache(monkeypatch):
async def fake(_client, url):
assert url == OK_URL
return b"png-bytes", "image/png"
monkeypatch.setattr("router.v1.image.image.fetch_image", fake)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
res = await c.get("/v1/image", params={"url": OK_URL})
assert res.status_code == 200
assert res.content == b"png-bytes"
assert res.headers["content-type"] == "image/png"
assert "max-age=86400" in res.headers["cache-control"]
@pytest.mark.anyio
async def test_image_api_reports_upstream_failure(monkeypatch):
async def fail(_client, _url):
raise ImageFetchFailed("status 404")
monkeypatch.setattr("router.v1.image.image.fetch_image", fail)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
res = await c.get("/v1/image", params={"url": OK_URL})
assert res.status_code == 502
def test_allowed_follows_settings(monkeypatch):
from config.settings import settings
monkeypatch.setattr(settings, "image_proxy_hosts", " cdn.example.org , ")
assert allowed("https://cdn.example.org/a.jpg") is True
assert allowed(OK_URL) is False
+3
View File
@@ -9,6 +9,8 @@ services:
args:
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
VITE_API_BASE_URL: ${VITE_API_BASE_URL:-}
# 공유할 때 나가는 우리 주소. 비우면 지금 보고 있는 주소
VITE_SITE_URL: ${VITE_SITE_URL:-}
ports:
- "${FRONT_PORT:-8080}:80"
restart: unless-stopped
@@ -26,6 +28,7 @@ services:
- /app/node_modules
environment:
- CHOKIDAR_USEPOLLING=true
- VITE_SITE_URL=${VITE_SITE_URL:-}
# 백엔드 API: http://localhost:9810/docs
backend:
+2
View File
@@ -16,6 +16,8 @@ CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
FROM deps AS build
ARG VITE_API_BASE_URL=""
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
ARG VITE_SITE_URL=""
ENV VITE_SITE_URL=$VITE_SITE_URL
COPY . .
RUN npm run build
+2
View File
@@ -11,10 +11,12 @@
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Jua&family=Bagel+Fat+One&family=Gowun+Batang&display=swap"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css"
crossorigin="anonymous"
/>
</head>
<body>
+1
View File
@@ -2,6 +2,7 @@ import { client } from './client/client.gen'
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth'
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '')
type Refresh = 'ok' | 'rejected' | 'unreachable'
+4 -4
View File
@@ -308,11 +308,11 @@ function FullCard({ post }: PostProps) {
const [pop, setPop] = useState(0)
const [likeFailed, setLikeFailed] = useState(0)
const lastTap = useRef(0)
const cardRef = useRef<HTMLDivElement>(null)
const trackRef = useRef<HTMLDivElement>(null)
const [account, avatar] = ACCOUNTS[post.post_type]
const n = post.slides.length
const bgs = post.slides.map((sl) => slideBg(post, sl))
const share = () => open({ type: 'share', share: { title: post.title, icon: post.icon, bg: bgs[0] ?? 'sky', messages: post.share_messages ?? [], card: cardRef.current } })
const share = () => open({ type: 'share', share: { title: post.title, slides: Array.from(trackRef.current?.children ?? []).filter((c) => c instanceof HTMLElement) } })
const comments = () => open({ type: 'comments', postId: post.post_id })
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values)
@@ -368,7 +368,7 @@ function FullCard({ post }: PostProps) {
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div ref={cardRef} className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
{n > 1 && (
<span data-noshot className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
{index + 1}/{n}
@@ -385,7 +385,7 @@ function FullCard({ post }: PostProps) {
if (e.key === 'ArrowRight') slider?.scrollNext()
}}
>
<div className="flex h-full">
<div ref={trackRef} className="flex h-full">
{post.slides.map((s, i) => (
<SlideView key={i} slide={s} bg={bgs[i]} />
))}
+52 -94
View File
@@ -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>
+5 -4
View File
@@ -1,4 +1,4 @@
import { useState, type ReactNode } from 'react'
import { useRef, useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils'
@@ -165,9 +165,10 @@ export function WeekPage() {
// 날씨(고른 날)가 와야 명소를 부를 수 있다
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready'
const pickRef = useRef<HTMLDivElement>(null)
const sendPlan = () => {
if (!sel) return
open({ type: 'share', share: { title: `${sel.weekday}요일 일정`, icon: 'calendar', bg: 'mint', messages: [`${sel.weekday}요일 이렇게 놀자! ${sel.pick} 😆`, '이번 주말 같이 놀자 🙌'] } })
if (!sel || !pickRef.current) return
open({ type: 'share', share: { title: `${sel.weekday}요일 일정`, slides: [pickRef.current] } })
}
return (
@@ -214,7 +215,7 @@ export function WeekPage() {
/>
)}
{sel && (
<div className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
<div ref={pickRef} className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
<Ic name={sel.icon} className="w-16" />
<div>
<b className="block font-jua text-[19px] font-normal">{sel.headline}</b>
+1 -3
View File
@@ -1,7 +1,5 @@
import { createContext, use } from 'react'
import type { SlideBg } from './types'
export type SharePayload = { title: string; icon: string; bg: SlideBg; messages: string[]; card?: HTMLElement | null }
export type SharePayload = { title: string; slides: HTMLElement[] }
export type SheetState =
| { type: 'gak'; indexId: number }
+192 -30
View File
@@ -1,10 +1,10 @@
import { domToCanvas } from 'modern-screenshot'
import { API_BASE_URL } from '../api/setup'
const W = 1080
const H = 1920
const CARD_W = 900
const SIDE = 60
// 시간대별 스토리 배경 (화면 하늘 배경과 같은 색)
// 시간대별 배경 (화면 하늘 배경과 같은 색)
const SKY: Record<string, [string, string, string]> = {
morning: ['#ffe0c4', '#fff0e2', '#e4f2ff'],
day: ['#cde7ff', '#e9f5ff', '#f7fbff'],
@@ -12,56 +12,218 @@ const SKY: Record<string, [string, string, string]> = {
night: ['#0e1433', '#1b2356', '#2a2e6e'],
}
/** 공유 이미지 크기. 위: 로고·지역 날짜, 가운데: 카드, 아래: 주소 */
export const SHARE_SIZES = {
story: { ratio: '9:16', w: 9, hr: 16, h: 1920, logoY: 250, logoPx: 96, subY: 325, subPx: 40, pillY: 1760, pillH: 100, labelPx: 34, hostPx: 46 },
feed: { ratio: '4:5', w: 4, hr: 5, h: 1350, logoY: 140, logoPx: 76, subY: 200, subPx: 34, pillY: 1250, pillH: 84, labelPx: 30, hostPx: 40 },
square: { ratio: '1:1', w: 1, hr: 1, h: 1080, logoY: 115, logoPx: 64, subY: 168, subPx: 30, pillY: 990, pillH: 80, labelPx: 28, hostPx: 38 },
} as const
export type ShareSize = keyof typeof SHARE_SIZES
const LOGO = (px: number) => `${px}px Jua, sans-serif`
const SANS = (px: number) => `bold ${px}px "Pretendard Variable", sans-serif`
const PILL_LABEL = '오늘 내 동네 각 보기'
// 버튼·조작 표시(data-noshot)는 이미지에 넣지 않는다. 링크(장소 등)는 글자라 남긴다
const keep = (n: Node) => !(n instanceof HTMLButtonElement || (n instanceof HTMLElement && n.dataset.noshot != null))
function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
ctx.beginPath()
ctx.roundRect(x, y, w, h, r)
}
/** 게시물 카드 한 장을 인스타 스토리 크기(1080×1920) PNG로 만든다 */
export async function storyImage(card: HTMLElement, opts: { title: string; sub: string; sky: string }): Promise<Blob> {
const shot = await domToCanvas(card, { scale: CARD_W / card.offsetWidth, filter: (n) => !(n instanceof HTMLElement && n.dataset.noshot != null) })
const URL_RE = /url\((['"]?)([^'")]+)\1\)/g
const dataUrls = new Map<string, Promise<string>>()
function dataUrl(url: string): Promise<string> {
let p = dataUrls.get(url)
if (!p) {
p = fetch(url)
.then((r) => {
if (!r.ok) throw new Error(`font ${r.status} ${url}`)
return r.blob()
})
.then((b) => new Promise<string>((resolve, reject) => {
const fr = new FileReader()
fr.onload = () => resolve(fr.result as string)
fr.onerror = () => reject(fr.error)
fr.readAsDataURL(b)
}))
p.catch(() => dataUrls.delete(url))
dataUrls.set(url, p)
}
return p
}
// "U+AC00-AC5F, U+4??" 가 text 의 글자를 하나라도 덮는지
function covers(range: string, codes: number[]) {
if (!range) return true
return range.split(',').some((part) => {
const [a, b] = part.trim().replace(/^u\+/i, '').split('-')
const lo = parseInt(a.replace(/\?/g, '0'), 16)
const hi = parseInt((b ?? a).replace(/\?/g, 'f'), 16)
return codes.some((c) => c >= lo && c <= hi)
})
}
/**
* 카드 글자에 필요한 웹폰트 조각만 data URL 로 넣은 @font-face.
* 이미지는 SVG 로 그려져 문서 폰트를 못 쓰므로 직접 넣어야 글꼴이 안 깨진다 (한글 폰트는 조각 수백 개라 전부 넣지 않는다).
*/
async function fontCss(text: string): Promise<string> {
const codes = [...new Set(Array.from(text, (ch) => ch.codePointAt(0) ?? 0))]
const rules: { css: string; base: string }[] = []
for (const sheet of Array.from(document.styleSheets)) {
let list: CSSRuleList
try {
list = sheet.cssRules
} catch (e) {
console.warn('[share] font css unreadable', sheet.href, e)
continue
}
for (const r of Array.from(list)) {
if (r instanceof CSSFontFaceRule && covers(r.style.getPropertyValue('unicode-range'), codes)) rules.push({ css: r.cssText, base: sheet.href ?? location.href })
}
}
const out = await Promise.all(
rules.map(async ({ css, base }) => {
const urls = [...css.matchAll(URL_RE)].map((m) => m[2])
const data = await Promise.all(urls.map((u) => dataUrl(new URL(u, base).href)))
let i = 0
return css.replace(URL_RE, () => `url("${data[i++]}")`)
}),
)
return out.join('\n')
}
// 다른 사이트 사진은 브라우저가 픽셀을 못 읽는 경우가 있어 백엔드가 대신 받아 준다. 허용 여부는 백엔드(IMAGE_PROXY_HOSTS)가 정한다
function viaProxy(url: string): Promise<string | false> {
if (!URL.canParse(url)) return Promise.resolve(false)
const u = new URL(url)
if (u.origin === location.origin || !u.protocol.startsWith('http')) return Promise.resolve(false)
return dataUrl(`${API_BASE_URL}/v1/image?url=${encodeURIComponent(url)}`).catch((e: unknown) => {
console.warn('[share] image proxy', url, e)
return false as const
})
}
type Box = { x: number; y: number; w: number; h: number }
// 카드 자리. 2장이면 세로 이미지는 지그재그, 나머지는 나란히(오른쪽을 조금 내려) 놓는다
function place(n: number, aspect: number, top: number, bottom: number): Box[] {
const room = bottom - top
if (n === 1) {
const w = Math.min(W - SIDE * 3, room / aspect)
const h = w * aspect
return [{ x: (W - w) / 2, y: top + (room - h) / 2, w, h }]
}
if (room / W > 1.1) {
const h = Math.min(room / 2, ((W - SIDE * 2) * 0.52) * aspect)
const w = h / aspect
const y = top + (room - h * 2) / 2
return [{ x: SIDE, y, w, h }, { x: W - SIDE - w, y: y + h, w, h }]
}
const gap = 40
const w = Math.min((W - SIDE * 2 - gap) / 2, room / aspect / 1.08)
const h = w * aspect
const y = top + (room - h * 1.08) / 2
return [{ x: W / 2 - gap / 2 - w, y, w, h }, { x: W / 2 + gap / 2, y: y + h * 0.08, w, h }]
}
function badge(ctx: CanvasRenderingContext2D, x: number, y: number, n: number) {
ctx.beginPath()
ctx.arc(x, y, 30, 0, Math.PI * 2)
ctx.fillStyle = '#ff7a45'
ctx.fill()
ctx.fillStyle = '#fff'
ctx.font = LOGO(36)
ctx.textBaseline = 'middle'
ctx.fillText(String(n), x, y + 2)
ctx.textBaseline = 'alphabetic'
}
/** 게시물 슬라이드(최대 2장)를 고른 크기의 PNG 한 장으로 만든다 */
export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize; sky: string; sub: string; host: string }): Promise<Blob> {
const z = SHARE_SIZES[opts.size]
const cards = slides.slice(0, 2)
if (!cards.length) throw new Error('no slide to capture')
await Promise.all([
document.fonts.load(LOGO(z.logoPx), '날씨각'),
document.fonts.load(LOGO(z.hostPx), opts.host),
document.fonts.load(LOGO(36), '12'),
document.fonts.load(SANS(z.subPx), opts.sub),
document.fonts.load(SANS(z.labelPx), PILL_LABEL),
])
const css = await fontCss(cards.map((c) => c.textContent ?? '').join(''))
const aspect = cards[0].offsetHeight / cards[0].offsetWidth
const boxes = place(cards.length, aspect, z.subY + 60, z.pillY - z.pillH / 2 - 50)
const shots = await Promise.all(cards.map((c, i) => domToCanvas(c, { scale: boxes[i].w / c.offsetWidth, filter: keep, font: css ? { cssText: css } : false, fetchFn: viaProxy })))
const canvas = document.createElement('canvas')
canvas.width = W
canvas.height = H
canvas.height = z.h
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('canvas 2d context unavailable')
const dark = opts.sky === 'night'
const [c1, c2, c3] = SKY[opts.sky] ?? SKY.day
const bg = ctx.createLinearGradient(0, 0, 0, H)
const bg = ctx.createLinearGradient(0, 0, 0, z.h)
bg.addColorStop(0, c1)
bg.addColorStop(0.45, c2)
bg.addColorStop(1, c3)
ctx.fillStyle = bg
ctx.fillRect(0, 0, W, H)
ctx.fillRect(0, 0, W, z.h)
ctx.textAlign = 'center'
ctx.fillStyle = '#ff7a45'
ctx.font = '84px Jua, sans-serif'
ctx.fillText('날씨각', W / 2, 230)
ctx.font = LOGO(z.logoPx)
ctx.fillText('날씨각', W / 2, z.logoY)
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = SANS(z.subPx)
ctx.fillText(opts.sub, W / 2, z.subY, W - SIDE * 2)
const cardH = (shot.height / shot.width) * CARD_W
const x = (W - CARD_W) / 2
const y = (H - cardH) / 2 + 20
const r = 40 * (boxes[0].w / 900)
shots.forEach((shot, i) => {
const b = boxes[i]
ctx.save()
ctx.shadowColor = 'rgb(40 48 74 / 0.25)'
ctx.shadowBlur = 50
ctx.shadowOffsetY = 20
roundRect(ctx, b.x, b.y, b.w, b.h, r)
ctx.fillStyle = '#fff'
ctx.fill()
ctx.restore()
ctx.save()
roundRect(ctx, b.x, b.y, b.w, b.h, r)
ctx.clip()
ctx.drawImage(shot, b.x, b.y, b.w, b.h)
ctx.restore()
})
if (shots.length > 1) boxes.forEach((b, i) => badge(ctx, b.x + 6, b.y + 6, i + 1))
// 주소 알약: [오늘 내 동네 각 보기 host]
ctx.font = SANS(z.labelPx)
const lw = ctx.measureText(PILL_LABEL).width
ctx.font = LOGO(z.hostPx)
const hw = ctx.measureText(opts.host).width
const gap = 20
const pw = Math.min(W - SIDE * 2, lw + gap + hw + 96)
const px = (W - pw) / 2
ctx.save()
ctx.shadowColor = 'rgb(40 48 74 / 0.25)'
ctx.shadowBlur = 60
ctx.shadowOffsetY = 24
roundRect(ctx, x, y, CARD_W, cardH, 48)
ctx.shadowColor = 'rgb(40 48 74 / 0.14)'
ctx.shadowBlur = 30
ctx.shadowOffsetY = 10
roundRect(ctx, px, z.pillY - z.pillH / 2, pw, z.pillH, z.pillH / 2)
ctx.fillStyle = '#fff'
ctx.fill()
ctx.restore()
ctx.save()
roundRect(ctx, x, y, CARD_W, cardH, 48)
ctx.clip()
ctx.drawImage(shot, x, y, CARD_W, cardH)
ctx.restore()
ctx.fillStyle = dark ? '#f1f3ff' : '#28304a'
ctx.font = '60px Jua, sans-serif'
ctx.fillText(opts.title, W / 2, y + cardH + 120, W - 120)
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = 'bold 38px "Pretendard Variable", sans-serif'
ctx.fillText(opts.sub, W / 2, y + cardH + 190, W - 120)
ctx.textAlign = 'left'
ctx.textBaseline = 'middle'
ctx.fillStyle = '#5a6380'
ctx.font = SANS(z.labelPx)
ctx.fillText(PILL_LABEL, px + 48, z.pillY + 2)
ctx.fillStyle = '#ff7a45'
ctx.font = LOGO(z.hostPx)
ctx.fillText(opts.host, px + 48 + lw + gap, z.pillY + 4, pw - 96 - lw - gap)
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'))
}