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
@@ -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'
|
||||
|
||||
|
||||
@@ -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
@@ -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>
|
||||
|
||||
@@ -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,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
@@ -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'))
|
||||
}
|
||||
Reference in new issue
Block a user