Files
o2o-weather/frontend/src/b/storyImage.ts
T
minaChoi ffe6153148 feat: 내 각 아이콘·상세, 이야기 내 글·무한 스크롤, 공유 이미지 얇은 띠, 행사 주소 수집
- 내 각: 아이콘 고르기(my_gak.icon), 카드는 아이콘·점수·아쉬운 조건만, 눌러서 상세(시간대·조건별 점수), 공유는 공통 공유 창
- 이야기: 오늘 쓴 내 글 묶음, '내 글' 칩·탭, 무한 스크롤, 사진 카메라 버튼, 지우기 확인, ⋯ 메뉴 하트 옆, 글 시간 서버 계산(1일 전)
- 공유 이미지: 1:1·4:5 는 아래 얇은 띠 한 줄로 카드를 크게
- 행사: 수집 때 주소 저장(event.address), 행사 포스트에 장소·주소·기간
- 히어로 말풍선 '오늘 낮은 / 내일 낮은', 내일을 볼 때 배경도 따라감, 달 보름 순간이 낮이면 뜨는 시각으로
- 단풍 지도 피드 맨 위, 행사·계절 띠 포스트 틀 되돌림, 쇼츠 홈 버튼 가림·닫기 버튼, 하단 여백, 회색 글자 대비
- 토스 앱에선 쇼츠 플레이어를 하나만 띄움
2026-10-27 18:55:42 +09:00

259 lines
10 KiB
TypeScript

import { domToCanvas } from 'modern-screenshot'
import { API_BASE_URL } from '../api/setup'
const W = 1080
const SIDE = 24
// 1:1·4:5 아래 띠 높이: 날씨각 · 동네·날짜 · 주소 한 줄
const FOOT = 84
// 시간대별 배경 (화면 하늘 배경과 같은 색)
const SKY: Record<string, [string, string, string]> = {
morning: ['#ffe0c4', '#fff0e2', '#e4f2ff'],
day: ['#cde7ff', '#e9f5ff', '#f7fbff'],
sunset: ['#ffd0b5', '#f9c3cf', '#ddd2f6'],
night: ['#0e1433', '#1b2356', '#2a2e6e'],
}
/**
* 공유 이미지 크기. 9:16 은 위 로고·지역 날짜, 가운데 카드, 아래 주소 알약.
* 1:1·4:5(strip)는 카드를 크게 두고 아래 얇은 띠 한 줄(날씨각 · 지역 날짜 · 주소)만
*/
export const SHARE_SIZES = {
story: { ratio: '9:16', w: 9, hr: 16, h: 1920, strip: false, 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, strip: true, logoY: 0, logoPx: 40, subY: 0, subPx: 26, pillY: 0, pillH: 0, labelPx: 0, hostPx: 32 },
square: { ratio: '1:1', w: 1, hr: 1, h: 1080, strip: true, logoY: 0, logoPx: 40, subY: 0, subPx: 26, pillY: 0, pillH: 0, labelPx: 0, hostPx: 32 },
} 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)
}
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 * 2, 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),
...(z.strip ? [] : [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 = z.strip ? place(cards.length, aspect, SIDE, z.h - FOOT) : 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 = 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, z.h)
bg.addColorStop(0, c1)
bg.addColorStop(0.45, c2)
bg.addColorStop(1, c3)
ctx.fillStyle = bg
ctx.fillRect(0, 0, W, z.h)
if (!z.strip) {
ctx.textAlign = 'center'
ctx.fillStyle = '#ff7a45'
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 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))
if (z.strip) {
// 아래 띠: 왼쪽 [날씨각 지역 · 날짜], 오른쪽 주소. 카드 양 끝에 맞춘다
const left = Math.min(...boxes.map((b) => b.x))
const right = Math.max(...boxes.map((b) => b.x + b.w))
const y = z.h - FOOT / 2 + 2
ctx.textBaseline = 'middle'
ctx.textAlign = 'left'
ctx.fillStyle = '#ff7a45'
ctx.font = LOGO(z.logoPx)
ctx.fillText('날씨각', left, y)
const logoW = ctx.measureText('날씨각').width
ctx.font = LOGO(z.hostPx)
const hostW = ctx.measureText(opts.host).width
ctx.textAlign = 'right'
ctx.fillText(opts.host, right, y)
ctx.textAlign = 'left'
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = SANS(z.subPx)
ctx.fillText(opts.sub, left + logoW + 16, y, Math.max(0, right - hostW - 24 - (left + logoW + 16)))
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'))
}
// 주소 알약: [오늘 내 동네 각 보기 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.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.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'))
}