feat: 다른 사이트에 붙이는 날씨각 위젯 — 누구나 붙이는 카드(/embed/card, 기본형·상세형, 배경 3종)와 사용 방법 페이지(/widget, 스크립트·iframe 코드)
- 카드: 군산각 카드를 옮겨 그림, 토끼 로딩, 실패하면 '날씨각에서 날씨 보기' 링크, 8초 제한, nginx 대체 화면, '자세히 보기' 버튼만 링크 - 크기: 폭은 자리에 맞춰 자동, 높이는 폭에 따라 비율대로(기본형 245~320px, 상세형 400~520px) - 부하: 지역별 카드 데이터 5분 저장, 저장분이 비면 지역마다 한 요청만 새로 만듦, 노출 수는 Redis 에 쌓았다가 관리자 조회 때 DB(widget_view_daily)로 옮김 - 사용 방법 페이지: 지역(앱 지역은 바꾸지 않음)·모양·배경 고르기, 미리보기, 코드 복사. 들어오는 길은 문의 창 버튼(토스에서는 숨김)과 검색 - GA: 위젯_안내_보기, 위젯_옵션_고름, 위젯_코드_복사 - 문서: docs/위젯_운영.md, 백엔드 테스트 실행법(CLAUDE.md)
This commit is contained in:
1 parent
1a98adc155
commit
dc8201e5f5
38 files changed
+4219
-28
No files matched your search
@@ -42,6 +42,30 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 다른 사이트에 붙이는 날씨 카드: 백엔드가 HTML 을 만든다 (Referer 는 노출 집계에 쓴다)
|
||||
# 백엔드가 죽었거나(502) 10초 안에 답하지 않으면(504) 오류 화면 대신 조용한 화면(quiet.html, 200)을 준다.
|
||||
# 404(잘못된 입력)는 백엔드가 만든 조용한 화면 그대로 둔다. 백엔드는 카드 만들기를 8초에 끊는다(CARD_BUILD_TIMEOUT_SEC)
|
||||
location = /embed/card {
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $api http://backend:9800;
|
||||
proxy_pass $api/v1/embed/card$is_args$args;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_connect_timeout 3s;
|
||||
proxy_read_timeout 10s;
|
||||
proxy_intercept_errors on;
|
||||
error_page 500 502 503 504 = @embed_quiet;
|
||||
}
|
||||
|
||||
location @embed_quiet {
|
||||
add_header Cache-Control "no-store";
|
||||
try_files /embed/quiet.html =404;
|
||||
}
|
||||
# 카드가 쓰는 정적 파일. 이름에 해시가 없어 짧게 캐시하고, 고치면 주소의 ?v= 를 올린다
|
||||
location /embed/ {
|
||||
add_header Cache-Control "public, max-age=3600";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# API 는 같은 주소로 받아 backend 컨테이너로 넘긴다
|
||||
location /v1/ {
|
||||
# 카드뉴스 올리기(/v1/card)는 1080×1350 JPEG 최대 20장을 base64 로 한 번에 보낸다 (기본 1m 로는 413)
|
||||
|
||||
@@ -0,0 +1,858 @@
|
||||
/* 날씨각 카드 — 다른 사이트가 iframe 으로 붙이는 /embed/card 의 모양 (그리는 것은 card.js).
|
||||
군산각(https://gunsan.webforai.kr/ 의 style.css, 2026-11-25 받은 것)에서 .wx 카드 규칙과 그 규칙이 쓰는 @keyframes,
|
||||
.vh 를 옮겨 왔다. 원본과 다른 곳:
|
||||
1. 원본의 html.js(스크립트가 도는 페이지) → :root. 이 화면은 늘 card.js 가 그린다. 우선순위(클래스 수)는 원본과 같다.
|
||||
2. 카드 높이 401px(상세형 home)·246px(기본형 side) → 100%. 상자가 iframe 을 꽉 채우고, iframe 높이를 그 값으로 준다.
|
||||
기본 높이를 400px(상세형)·245px(기본형)로 맞추려고 아래 여백을 1px 줄였다(:root .wx-home, :root .wx-side).
|
||||
3. 군산각 :root 변수(--ink 등) 중 카드가 쓰는 것과, 군산각 기본 규칙 중 카드 안에서 먹던 것(box-sizing, p·ol 바깥
|
||||
여백, body 의 글자 설정, img·a 기본값)을 아래 첫 두 덩어리에 옮겼다. 기본 규칙은 :where(.wx) 로 카드 안에만,
|
||||
원본처럼 낮은 우선순위로 둔다.
|
||||
4. 뺀 것: 외국어판(.wx-intl, .wx-fold·.wx-fl·.wx-fd), 군산각 옆 패널이 낮은 창에서 접히는 규칙
|
||||
(@media (min-width: 1200px) and (max-height: …)), 시계로 미리 칠하는 html[data-wxt] 갈래.
|
||||
5. 더한 것: html·body 초기화, 상세형(home)의 한마디·요약 한 줄, 상태 줄 두 줄까지 (넘친 글이 반쯤 잘려 보이지 않게),
|
||||
스크립트가 돌지 않을 때의 링크(.wx-ns), 상세형(home) 날짜가 통째로 안 들어가면 숨기기(.is-nodt, card.js 가 붙인다).
|
||||
6. 그리기 전 자리 표시(빈 원과 띠, --wx-skel)를 빼고 토끼 로딩 화면(.wx-load, 날씨각 앱 첫 화면과 같은 토끼와
|
||||
'날씨 불러오는 중…')을 둔다. 못 그리면(is-failed) 가운데 흰 알약 링크 '날씨각에서 날씨 보기 ›'(원본은 '○○ 날씨 보기'와
|
||||
새 창 그림 .icon·.wx-x, 둘 다 뺐다). 8초가 지나도 is-ready·is-failed 가 안 붙으면(card.js 가 안 옴) 스크립트 없이
|
||||
애니메이션 지연만으로 토끼를 감추고 같은 링크를 보인다. 나중에라도 그려지면 그린 카드가 이긴다.
|
||||
7. 기본형(side)도 상세형(home)처럼 모서리를 28px 로 둥글게 했다(원본은 각진 모서리).
|
||||
로딩·실패 화면은 상자(.wx) 안에 있어 같은 모서리로 잘린다.
|
||||
8. 원본은 다 그린 카드 전체가 링크(.wx-go::after 가 카드를 덮음)다. 여기서는 '자세히 보기 ›' 버튼만 링크다 — 붙인 사이트
|
||||
방문자가 카드를 잘못 눌러 페이지를 떠나지 않게. ::after 는 버튼의 눌리는 자리를 위아래로 넓히는 데만 쓴다.
|
||||
배경(상자 클래스 wx-bg-*, card.js 는 몰라도 된다):
|
||||
- sky: 군산각 그대로, 시간대별 하늘.
|
||||
- light: 밝은 바탕 사이트용. 시간대별 하늘을 옅은 파스텔로, 어두운 글자, 얇은 안쪽 테두리, 별 없음, 흰 구름.
|
||||
- dark: 어두운 바탕 사이트용. 시간대별 하늘을 짙게, 흰 글자, 밤에는 별, 푸른 회색 구름.
|
||||
해·달·구름·비·눈과 움직임은 셋이 같다. */
|
||||
|
||||
/* 군산각 :root 값 (--focus 는 원본도 var(--sea), --link 는 var(--sea-hi)) */
|
||||
:root {
|
||||
--ink: #172033;
|
||||
--sea: #2F6FC9;
|
||||
--sea-hi: #255DAF;
|
||||
--sea-deep: #1D4F96;
|
||||
--link: var(--sea-hi);
|
||||
--focus: var(--sea);
|
||||
--ease-out: cubic-bezier(.16, 1, .3, 1);
|
||||
--fb: cubic-bezier(.25, .1, .25, 1);
|
||||
--font: 'Pretendard', 'Pretendard Fallback Noto', 'Pretendard Fallback WQY', 'Pretendard Fallback Inter', -apple-system, BlinkMacSystemFont, 'Apple SD Gothic Neo', 'Noto Sans KR', 'Malgun Gothic', sans-serif;
|
||||
}
|
||||
|
||||
/* 카드 화면: 카드 하나뿐이다. 바탕은 붙인 사이트가 비쳐 보이게 투명, 스크롤바 없음 */
|
||||
html {
|
||||
-webkit-text-size-adjust: 100%;
|
||||
text-size-adjust: 100%;
|
||||
}
|
||||
html, body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* 군산각 기본 규칙 중 카드 안에서 먹던 것 (*, p·ol, li, img, a, body 의 글자) */
|
||||
:where(.wx, .wx *, .wx *::before, .wx *::after) {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
:where(.wx) :where(p, ol) {
|
||||
margin: 0;
|
||||
}
|
||||
:where(.wx) :where(p, li) {
|
||||
text-wrap: pretty;
|
||||
}
|
||||
:where(.wx) :where(img) {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
:where(.wx) :where(a) {
|
||||
color: var(--link);
|
||||
text-decoration: none;
|
||||
transition: color .2s var(--fb);
|
||||
}
|
||||
:where(.wx) {
|
||||
font: 400 17px/1.47 var(--font);
|
||||
letter-spacing: -.01em;
|
||||
word-break: keep-all;
|
||||
overflow-wrap: break-word;
|
||||
line-break: strict;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
.vh {
|
||||
position: absolute !important;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 카드 (군산각 style.css 의 .wx 규칙) */
|
||||
.wx {
|
||||
position: relative;
|
||||
color: var(--ink);
|
||||
}
|
||||
.wx-h {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
}
|
||||
.wx-t {
|
||||
font: 700 13.5px/1.3 var(--font);
|
||||
color: var(--sea-deep);
|
||||
letter-spacing: -.01em;
|
||||
}
|
||||
.wx-dt, .wx-ar {
|
||||
display: none;
|
||||
}
|
||||
.wx-go {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-height: 24px;
|
||||
font: 700 12.5px/1.3 var(--font);
|
||||
color: var(--sea-deep);
|
||||
text-decoration: underline;
|
||||
text-decoration-thickness: 1px;
|
||||
text-underline-offset: .18em;
|
||||
}
|
||||
.wx-go:hover {
|
||||
color: var(--ink);
|
||||
}
|
||||
.wx-b:empty {
|
||||
display: none;
|
||||
}
|
||||
.wx-home .wx-h {
|
||||
padding: 16px 18px;
|
||||
}
|
||||
.wx-home .wx-t {
|
||||
font-size: 15px;
|
||||
}
|
||||
@media (max-width: 1023px) {
|
||||
.wx-go {
|
||||
min-height: 44px;
|
||||
}
|
||||
}
|
||||
:where(:root .wx) {
|
||||
--wx-bg: linear-gradient(#9fd3ff, #cfe9ff 55%, #f1f8ff);
|
||||
--wx-fg: #28304a;
|
||||
--wx-strip: rgba(255, 255, 255, .42);
|
||||
--wx-o1: .85;
|
||||
--wx-o2: .75;
|
||||
--wx-o3: .75;
|
||||
--wx-warn: #a8401a;
|
||||
}
|
||||
:root .wx {
|
||||
isolation: isolate;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 12px 16px;
|
||||
border: 0;
|
||||
border-radius: 28px;
|
||||
background: var(--wx-bg);
|
||||
color: var(--wx-fg);
|
||||
}
|
||||
.wx[data-t=morning] {
|
||||
--wx-bg: linear-gradient(#ffd9b8, #ffe9d4 40%, #dff0ff);
|
||||
}
|
||||
.wx:is([data-t=morning], [data-t=day]):is([data-sky=cloudy], [data-sky=rain], [data-sky=snow], [data-sky=sleet]) {
|
||||
--wx-bg: linear-gradient(#a9bbd0, #cbd7e4 55%, #eef2f7);
|
||||
}
|
||||
.wx[data-t=sunset] {
|
||||
--wx-bg: linear-gradient(#4c42b0, #6a48b0 45%, #8e4482);
|
||||
--wx-fg: #fff;
|
||||
--wx-strip: rgba(255, 255, 255, .14);
|
||||
--wx-o2: .85;
|
||||
--wx-o3: 1;
|
||||
--wx-warn: #ffd2b8;
|
||||
}
|
||||
.wx[data-t=night] {
|
||||
--wx-bg: linear-gradient(#141b3d, #27306a 60%, #3d3f86);
|
||||
--wx-fg: #fff;
|
||||
--wx-strip: rgba(255, 255, 255, .14);
|
||||
--wx-o2: .85;
|
||||
--wx-o3: .85;
|
||||
--wx-warn: #ffb38a;
|
||||
}
|
||||
:root .wx-home {
|
||||
height: 100%;
|
||||
padding-bottom: 11px;
|
||||
}
|
||||
:root .wx .wx-h {
|
||||
flex: none;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
}
|
||||
:root .wx .wx-t {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 24px;
|
||||
margin: 0 3px;
|
||||
padding: 0 10px;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #28304a;
|
||||
box-shadow: 0 0 0 3px var(--wx-strip), 0 4px 12px rgba(40, 48, 74, .1);
|
||||
font: 700 13px/1 WxJua, var(--font);
|
||||
font-synthesis: none;
|
||||
letter-spacing: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
:root .wx .wx-dt {
|
||||
display: block;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
margin-left: 10px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font: 700 13px/1.5 var(--font);
|
||||
opacity: var(--wx-o1);
|
||||
}
|
||||
:root .wx .wx-go {
|
||||
visibility: hidden;
|
||||
}
|
||||
:root .wx.is-ready .wx-go {
|
||||
visibility: visible;
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
gap: 3px;
|
||||
height: 30px;
|
||||
min-height: 0;
|
||||
margin-left: auto;
|
||||
padding: 0 12px;
|
||||
border-radius: 999px;
|
||||
background: var(--wx-strip);
|
||||
color: inherit;
|
||||
font: 700 13px/1 var(--font);
|
||||
text-decoration: none;
|
||||
}
|
||||
:root .wx.is-ready .wx-ar {
|
||||
display: inline;
|
||||
margin-left: 2px;
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
}
|
||||
:root .wx.is-ready .wx-go {
|
||||
position: relative;
|
||||
z-index: 5;
|
||||
}
|
||||
:root .wx.is-ready .wx-go::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: -7px -4px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
:root .wx.is-ready .wx-go:hover {
|
||||
background: rgba(255, 255, 255, .62);
|
||||
color: #28304a;
|
||||
}
|
||||
:root .wx.is-ready .wx-go:focus-visible {
|
||||
outline: 3px solid var(--focus);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
/* 못 그렸을 때(is-failed)와 8초가 지나도 그리지 못했을 때(아래 '더한 것: 토끼 로딩 화면') 가운데 뜨는 날씨각 링크 */
|
||||
:root .wx:not(.is-ready) .wx-go {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
z-index: 2;
|
||||
min-height: 44px;
|
||||
padding: 0 18px;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #28304a;
|
||||
font: 700 14px/1.3 var(--font);
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
box-shadow: 0 4px 12px rgba(40, 48, 74, .12);
|
||||
}
|
||||
:root .wx.is-failed .wx-go {
|
||||
visibility: visible;
|
||||
}
|
||||
:root .wx:not(.is-ready) .wx-go:hover {
|
||||
color: var(--sea-deep);
|
||||
text-decoration: underline;
|
||||
}
|
||||
:root .wx .wx-b {
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
min-height: 0;
|
||||
}
|
||||
.wx-stars, .wx-fx {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
pointer-events: none;
|
||||
}
|
||||
.wx-stars {
|
||||
opacity: 0;
|
||||
}
|
||||
.wx[data-t=night] .wx-stars {
|
||||
opacity: 1;
|
||||
}
|
||||
.wx-stars i {
|
||||
position: absolute;
|
||||
width: 3px;
|
||||
height: 3px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 6px #fff;
|
||||
}
|
||||
.wx-shoot {
|
||||
display: none;
|
||||
position: absolute;
|
||||
width: var(--len, 90px);
|
||||
height: 1.5px;
|
||||
border-radius: 2px;
|
||||
opacity: 0;
|
||||
background: linear-gradient(90deg, rgba(255, 255, 255, 0), #fff);
|
||||
}
|
||||
.wx-drop, .wx-flake {
|
||||
position: absolute;
|
||||
top: var(--top);
|
||||
}
|
||||
.wx-drop {
|
||||
width: 2px;
|
||||
height: 18px;
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(rgba(0, 0, 0, 0), rgba(80, 130, 200, .7));
|
||||
}
|
||||
.wx:is([data-t=sunset], [data-t=night]) .wx-drop {
|
||||
background: linear-gradient(rgba(0, 0, 0, 0), rgba(220, 230, 255, .7));
|
||||
}
|
||||
.wx-flake {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 4px rgba(120, 150, 200, .5);
|
||||
--drift: 18px;
|
||||
}
|
||||
.wx-sky, .wx-say, .wx-strip {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 440px;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
.wx-sky {
|
||||
flex: none;
|
||||
height: 9.125em;
|
||||
font-size: 16px;
|
||||
}
|
||||
.wx-cl {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
}
|
||||
.wx-c1 {
|
||||
top: 2.25em;
|
||||
left: 5%;
|
||||
width: 5.25em;
|
||||
height: 2em;
|
||||
--d: .1s;
|
||||
--f: 6s;
|
||||
}
|
||||
.wx-c2 {
|
||||
top: 6em;
|
||||
left: 63%;
|
||||
width: 6em;
|
||||
height: 2.25em;
|
||||
--d: .25s;
|
||||
--f: 6.4s;
|
||||
}
|
||||
.wx-c3 {
|
||||
top: 1.875em;
|
||||
left: 72%;
|
||||
width: 4em;
|
||||
height: 1.75em;
|
||||
--d: .4s;
|
||||
--f: 5.4s;
|
||||
}
|
||||
.wx-cb, .wx-cb::before, .wx-cb::after {
|
||||
position: absolute;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
}
|
||||
.wx-cb {
|
||||
inset: 0;
|
||||
box-shadow: inset 0 -.75em 1.125em rgba(160, 190, 230, .45), 0 1em 1.75em rgba(40, 70, 120, .13);
|
||||
}
|
||||
.wx-cb::before, .wx-cb::after {
|
||||
content: "";
|
||||
aspect-ratio: 1;
|
||||
box-shadow: inset 0 -.625em 1em rgba(160, 190, 230, .35);
|
||||
}
|
||||
.wx-cb::before {
|
||||
width: 46%;
|
||||
top: -58%;
|
||||
left: 16%;
|
||||
}
|
||||
.wx-cb::after {
|
||||
width: 36%;
|
||||
top: -36%;
|
||||
left: 50%;
|
||||
}
|
||||
.wx[data-t=night] .wx-cb, .wx[data-t=night] .wx-cb::before, .wx[data-t=night] .wx-cb::after {
|
||||
background: #c9cdf0;
|
||||
}
|
||||
.wx-ob {
|
||||
position: absolute;
|
||||
top: .5em;
|
||||
left: 50%;
|
||||
width: 8em;
|
||||
height: 8em;
|
||||
margin-left: -4em;
|
||||
--d: 0s;
|
||||
--f: 5.6s;
|
||||
}
|
||||
.wx-orb {
|
||||
position: relative;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
text-align: center;
|
||||
color: #5c1f08;
|
||||
background: radial-gradient(circle at 34% 30%, #fff5cf, #ffc86e 30%, #ff8e4e 68%, #ee6436);
|
||||
box-shadow: inset -1.125em -1.5em 2.5em rgba(170, 50, 20, .34), inset 1em 1.125em 1.75em rgba(255, 255, 255, .55), 0 1.875em 3.5em rgba(240, 106, 58, .32);
|
||||
}
|
||||
.wx[data-t=sunset] .wx-orb {
|
||||
color: #4a2442;
|
||||
background: radial-gradient(circle at 34% 30%, #fff4e6, #ffd9b8 32%, #f7a991 68%, #e07a8f);
|
||||
box-shadow: inset -1.125em -1.5em 2.5em rgba(150, 50, 90, .3), inset 1em 1.125em 1.75em rgba(255, 255, 255, .55), 0 0 3.75em rgba(255, 150, 110, .5);
|
||||
}
|
||||
.wx[data-t=night] .wx-orb {
|
||||
color: #2b2a5c;
|
||||
background: radial-gradient(circle at 34% 30%, #fff, #e7e3ff 35%, #b9b0f2 72%, #8f86d9);
|
||||
box-shadow: inset -1.125em -1.5em 2.5em rgba(60, 50, 140, .3), inset 1em 1.125em 1.75em rgba(255, 255, 255, .6), 0 0 3.75em rgba(190, 180, 255, .45);
|
||||
}
|
||||
.wx:is([data-sky=cloudy], [data-sky=rain], [data-sky=snow], [data-sky=sleet]) .wx-orb {
|
||||
filter: saturate(.7) brightness(.96);
|
||||
}
|
||||
.wx .wx-orb.wx-moon {
|
||||
background: none;
|
||||
box-shadow: none;
|
||||
filter: none;
|
||||
}
|
||||
.wx-mo {
|
||||
position: absolute;
|
||||
top: -25%;
|
||||
left: -25%;
|
||||
width: 150%;
|
||||
height: 150%;
|
||||
max-width: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
.wx-sc {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
margin: 0;
|
||||
}
|
||||
.wx-sc small {
|
||||
display: block;
|
||||
font: 700 12px/1.5 WxJua, var(--font);
|
||||
font-synthesis: none;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.wx-sc b {
|
||||
display: block;
|
||||
font: 700 3.25em/.95 WxBagel, WxJua, var(--font);
|
||||
font-synthesis: none;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.wx-moon.is-lit .wx-sc {
|
||||
text-shadow: 0 0 6px #fff, 0 0 12px #fff;
|
||||
}
|
||||
.wx-moon.is-dim .wx-sc {
|
||||
color: #fff;
|
||||
text-shadow: 0 1px 8px rgba(10, 14, 40, .6);
|
||||
}
|
||||
.wx-say {
|
||||
flex: none;
|
||||
height: 103px;
|
||||
overflow: hidden;
|
||||
text-align: center;
|
||||
}
|
||||
.wx-bub {
|
||||
margin: 0;
|
||||
font: 700 24px/30px WxJua, var(--font);
|
||||
font-synthesis: none;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.wx-sum {
|
||||
margin: 2px 0 0;
|
||||
font: 700 15px/22.5px var(--font);
|
||||
opacity: var(--wx-o1);
|
||||
}
|
||||
.wx-st {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 0 6px;
|
||||
margin: 6px 0 0;
|
||||
font: 700 14px/21px WxJua, var(--font);
|
||||
font-synthesis: none;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.wx-si {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.wx-si b {
|
||||
font-weight: inherit;
|
||||
}
|
||||
.wx-sl {
|
||||
opacity: var(--wx-o2);
|
||||
}
|
||||
.wx-dot {
|
||||
opacity: .3;
|
||||
}
|
||||
.wx-si.is-warn {
|
||||
color: var(--wx-warn);
|
||||
}
|
||||
.wx-si.is-warn .wx-sl {
|
||||
opacity: 1;
|
||||
}
|
||||
.wx-strip {
|
||||
flex: none;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
margin-top: 10px;
|
||||
padding: 3px;
|
||||
list-style: none;
|
||||
border-radius: 18px;
|
||||
background: var(--wx-strip);
|
||||
}
|
||||
.wx-strip li {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
padding: 6px 0;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.wx-cn {
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
font: 700 13px/19.5px var(--font);
|
||||
opacity: var(--wx-o3);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.wx-ic {
|
||||
display: block;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
margin: 2px 0;
|
||||
object-fit: contain;
|
||||
}
|
||||
.wx-tc {
|
||||
font: 700 15px/22.5px WxJua, var(--font);
|
||||
font-synthesis: none;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.wx-strip li.is-now {
|
||||
background: #fff;
|
||||
color: #28304a;
|
||||
box-shadow: 0 4px 12px rgba(40, 48, 74, .1);
|
||||
}
|
||||
.wx-strip li.is-now .wx-cn {
|
||||
color: #c2471b;
|
||||
opacity: 1;
|
||||
}
|
||||
:root .wx-side {
|
||||
height: 100%;
|
||||
padding: 10px 12px 9px;
|
||||
border-radius: 28px;
|
||||
}
|
||||
:root .wx-side .wx-h {
|
||||
height: 24px;
|
||||
}
|
||||
:root .wx-side .wx-t {
|
||||
height: 20px;
|
||||
margin: 0 2px;
|
||||
padding: 0 8px;
|
||||
box-shadow: 0 0 0 2px var(--wx-strip);
|
||||
font-size: 11.5px;
|
||||
}
|
||||
:root .wx-side .wx-dt {
|
||||
display: none;
|
||||
}
|
||||
/* 상세형(home) 날짜가 통째로 들어가지 않으면 card.js 가 상자에 is-nodt 를 붙인다: 잘린 채('1…') 두지 않고 자리째 숨긴다 */
|
||||
:root .wx.is-nodt .wx-dt {
|
||||
display: none;
|
||||
}
|
||||
:root .wx-side.is-ready .wx-go {
|
||||
height: 24px;
|
||||
padding: 0 9px;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
:root .wx-side.is-ready .wx-ar {
|
||||
font-size: 13px;
|
||||
}
|
||||
.wx-side .wx-sky {
|
||||
font-size: 11px;
|
||||
}
|
||||
.wx-side .wx-sc small {
|
||||
font-size: 9.5px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.wx-side .wx-say {
|
||||
height: 26px;
|
||||
}
|
||||
.wx-side .wx-bub {
|
||||
overflow: hidden;
|
||||
font-size: 17px;
|
||||
line-height: 26px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.wx-side .wx-strip {
|
||||
gap: 3px;
|
||||
margin-top: 6px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.wx-side .wx-strip li {
|
||||
padding: 4px 0;
|
||||
border-radius: 11px;
|
||||
}
|
||||
.wx-side .wx-cn {
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
.wx-side .wx-ic {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin: 1px 0;
|
||||
}
|
||||
.wx-side .wx-tc {
|
||||
font-size: 13px;
|
||||
line-height: 19px;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 배경: 밝은 바탕용(light)·어두운 바탕용(dark)
|
||||
같은 갈래의 sky 규칙(.wx[data-t=…], .wx:is(…):is(…))보다 클래스가 많아 순서와 상관없이 이긴다 */
|
||||
:root .wx.wx-bg-light {
|
||||
--wx-bg: linear-gradient(#e3f1ff, #f0f8ff 55%, #fbfdff);
|
||||
--wx-fg: #28304a;
|
||||
--wx-strip: rgba(255, 255, 255, .7);
|
||||
--wx-o1: .85;
|
||||
--wx-o2: .75;
|
||||
--wx-o3: .75;
|
||||
--wx-warn: #a8401a;
|
||||
box-shadow: inset 0 0 0 1px rgba(40, 48, 74, .08);
|
||||
}
|
||||
:root .wx.wx-bg-light[data-t=morning] {
|
||||
--wx-bg: linear-gradient(#ffeedd, #fff6ee 45%, #f3f9ff);
|
||||
}
|
||||
:root .wx.wx-bg-light:is([data-t=morning], [data-t=day]):is([data-sky=cloudy], [data-sky=rain], [data-sky=snow], [data-sky=sleet]) {
|
||||
--wx-bg: linear-gradient(#e6ebf1, #f1f4f8 55%, #fafbfc);
|
||||
}
|
||||
:root .wx.wx-bg-light[data-t=sunset] {
|
||||
--wx-bg: linear-gradient(#ece8ff, #f4ecfb 45%, #fdeef3);
|
||||
}
|
||||
:root .wx.wx-bg-light[data-t=night] {
|
||||
--wx-bg: linear-gradient(#e4e8fa, #ecedfa 60%, #f3f0fb);
|
||||
}
|
||||
:root .wx.wx-bg-light .wx-stars {
|
||||
display: none;
|
||||
}
|
||||
:root .wx.wx-bg-light .wx-cb, :root .wx.wx-bg-light .wx-cb::before, :root .wx.wx-bg-light .wx-cb::after {
|
||||
background: #fff;
|
||||
}
|
||||
:root .wx.wx-bg-light .wx-drop {
|
||||
background: linear-gradient(rgba(0, 0, 0, 0), rgba(80, 130, 200, .7));
|
||||
}
|
||||
:root .wx.wx-bg-light .wx-flake {
|
||||
background: #fff;
|
||||
box-shadow: 0 0 4px rgba(120, 150, 200, .7);
|
||||
}
|
||||
:root .wx.wx-bg-dark {
|
||||
--wx-bg: linear-gradient(#1c3252, #20304c 55%, #1c2540);
|
||||
--wx-fg: #fff;
|
||||
--wx-strip: rgba(255, 255, 255, .12);
|
||||
--wx-o1: .85;
|
||||
--wx-o2: .85;
|
||||
--wx-o3: .85;
|
||||
--wx-warn: #ffb38a;
|
||||
}
|
||||
:root .wx.wx-bg-dark[data-t=morning] {
|
||||
--wx-bg: linear-gradient(#3b2e3c, #34303f 45%, #252c42);
|
||||
}
|
||||
:root .wx.wx-bg-dark:is([data-t=morning], [data-t=day]):is([data-sky=cloudy], [data-sky=rain], [data-sky=snow], [data-sky=sleet]) {
|
||||
--wx-bg: linear-gradient(#2a313d, #262c38 55%, #20242e);
|
||||
}
|
||||
:root .wx.wx-bg-dark[data-t=sunset] {
|
||||
--wx-bg: linear-gradient(#2b2660, #39295d 45%, #482747);
|
||||
}
|
||||
:root .wx.wx-bg-dark[data-t=night] {
|
||||
--wx-bg: linear-gradient(#10152f, #1a2048 60%, #262852);
|
||||
}
|
||||
:root .wx.wx-bg-dark .wx-cb, :root .wx.wx-bg-dark .wx-cb::before, :root .wx.wx-bg-dark .wx-cb::after {
|
||||
background: #aab3d6;
|
||||
}
|
||||
:root .wx.wx-bg-dark .wx-drop {
|
||||
background: linear-gradient(rgba(0, 0, 0, 0), rgba(220, 230, 255, .7));
|
||||
}
|
||||
|
||||
/* 더한 것: 스크립트가 돌지 않을 때 날씨각 링크 (render_card 의 <noscript>, 모양은 is-failed 의 링크와 같다) */
|
||||
.wx-ns {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
z-index: 6;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 44px;
|
||||
padding: 0 18px;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #28304a;
|
||||
font: 700 14px/1.3 var(--font);
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
box-shadow: 0 4px 12px rgba(40, 48, 74, .12);
|
||||
}
|
||||
.wx-ns:hover {
|
||||
color: var(--sea-deep);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* 더한 것: 토끼 로딩 화면 (render_card 의 .wx-load. 날씨각 앱 첫 화면 #boot 와 같은 토끼·문구, 움직임은 앱의 b-hop).
|
||||
카드 가운데에 두고, 그리면(is-ready)·못 그리면(is-failed) 사라진다. 글자색은 배경을 따른다(dark 는 흰 글자).
|
||||
글꼴은 카드 본문과 같은 시스템 글꼴 굵은 글씨다 (이 화면은 Jua 를 싣지 않고, 둥근 글꼴은 card.js 가 카드 글자에만 받는다) */
|
||||
.wx-load {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
color: var(--wx-fg);
|
||||
font: 700 19px/1.3 var(--font);
|
||||
letter-spacing: 0;
|
||||
text-align: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
.wx-load img {
|
||||
display: block;
|
||||
width: 88px;
|
||||
height: 88px;
|
||||
transform-origin: 50% 100%;
|
||||
}
|
||||
.wx-side .wx-load {
|
||||
gap: 8px;
|
||||
font-size: 15px;
|
||||
}
|
||||
.wx-side .wx-load img {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
}
|
||||
.wx.is-ready .wx-load, .wx.is-failed .wx-load {
|
||||
display: none;
|
||||
}
|
||||
/* card.js 가 오지 않으면(막힘·404) 8초 뒤 스크립트 없이 토끼를 감추고 날씨각 링크를 보인다. 움직임이 아니라 바뀌기만 하므로
|
||||
움직임 줄이기 설정과 상관없이 둔다. is-ready·is-failed 가 붙으면 이 규칙이 안 맞아 그린 카드(또는 실패 링크)가 이긴다 */
|
||||
:root .wx:not(.is-ready):not(.is-failed) .wx-load {
|
||||
animation: wx-gone 0s linear 8s forwards;
|
||||
}
|
||||
:root .wx:not(.is-ready):not(.is-failed) .wx-go {
|
||||
animation: wx-late 0s linear 8s forwards;
|
||||
}
|
||||
@keyframes wx-gone {
|
||||
to { visibility: hidden; }
|
||||
}
|
||||
@keyframes wx-late {
|
||||
to { visibility: visible; }
|
||||
}
|
||||
|
||||
/* 더한 것: 상세형(home)의 글 줄 수 (한마디 한 줄 30px + 요약 한 줄 2+22.5px + 상태 두 줄 6+42px = 102.5px, .wx-say 103px 안) */
|
||||
.wx-home .wx-bub, .wx-home .wx-sum {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 1;
|
||||
line-clamp: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
.wx-home .wx-st {
|
||||
max-height: 42px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* 움직임 */
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.wx.is-ready .wx-b {
|
||||
animation: wx-in .45s var(--ease-out) both;
|
||||
}
|
||||
.wx-home :is(.wx-cl, .wx-ob) {
|
||||
animation: wx-drop 1.05s cubic-bezier(.22, .9, .3, 1) var(--d, 0s) backwards;
|
||||
}
|
||||
.wx :is(.wx-cb, .wx-orb) {
|
||||
animation: wx-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
|
||||
}
|
||||
.wx[data-t=night] .wx-shoot {
|
||||
display: block;
|
||||
animation: wx-shoot var(--dur, 8s) ease-in var(--dl, 0s) infinite;
|
||||
}
|
||||
.wx[data-t=night] .wx-tw {
|
||||
animation: wx-twinkle 5s ease-in-out var(--dl, 0s) infinite;
|
||||
}
|
||||
.wx-drop, .wx-flake {
|
||||
top: -24px;
|
||||
animation: wx-fall var(--dur) linear var(--dl) infinite;
|
||||
}
|
||||
.wx.is-off * {
|
||||
animation-play-state: paused !important;
|
||||
}
|
||||
.wx-load img {
|
||||
animation: wx-hop .9s cubic-bezier(.3, 0, .4, 1) infinite;
|
||||
}
|
||||
}
|
||||
@keyframes wx-hop {
|
||||
0%, to { transform: translateY(0) scale(1.06, .94); }
|
||||
45% { transform: translateY(-22px) scale(.97, 1.03); }
|
||||
}
|
||||
@keyframes wx-drop {
|
||||
0% { opacity: 0; transform: translateY(-60vh) rotate(-10deg); }
|
||||
55% { opacity: 1; }
|
||||
72% { transform: translateY(0) rotate(2deg) scale(1.04, .96); }
|
||||
86% { transform: translateY(-10px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
@keyframes wx-fall {
|
||||
to { transform: translate(var(--drift, -8px), 440px); }
|
||||
}
|
||||
@keyframes wx-float {
|
||||
0%, to { transform: translateY(0); }
|
||||
50% { transform: translateY(-.5625em) rotate(1.2deg); }
|
||||
}
|
||||
@keyframes wx-in {
|
||||
from { opacity: 0; }
|
||||
}
|
||||
@keyframes wx-shoot {
|
||||
0%, 86% { opacity: 0; transform: rotate(-24deg) translate(0); }
|
||||
89% { opacity: 1; }
|
||||
to { opacity: 0; transform: rotate(-24deg) translate(-240px); }
|
||||
}
|
||||
@keyframes wx-twinkle {
|
||||
0%, to { opacity: .25; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
/* 날씨각 카드 — 다른 사이트가 iframe 으로 붙이는 /embed/card 의 카드를 그린다 (모양은 card.css).
|
||||
군산각(https://gunsan.webforai.kr/assets/weather.js, 2026-11-25 받은 것)의 카드 스크립트를 옮겨 왔다. 군산각의 이
|
||||
카드는 날씨각 첫 화면 카드를 그대로 그린 위젯이라 점수·달 모양·하늘·4칸 줄이 날씨각과 같다. 원본과 다른 곳:
|
||||
1. 날씨 값을 fetch 두 번(data-wx, data-wx-day)으로 받지 않고, 백엔드가 이 페이지에 넣어 둔 #wx-data JSON
|
||||
({name, link, hero, today})을 읽어 usable() 에 {hero}, today 로 넘긴다. 8초 제한·ask()·화면에 가까워지면 묻기는
|
||||
뺐고, 바로 그린다. fetch 가 없는 브라우저는 카드 전체가 아니라 글꼴만 포기한다.
|
||||
2. 문구(지금 날씨 점수, 아침·낮·저녁·밤·지금, 자세히 보기, 하늘 이름)는 data-wx-w 대신 이 파일의 WORDS 에 둔다.
|
||||
외국어 갈래(wx-intl: 숫자만 보이는 줄, 접힌 줄)는 빼고 한국어 갈래만 남겼다. 날짜는 한국어 긴 꼴로만 쓴다.
|
||||
3. 아이콘 경로 /assets/wx/ → /icons/ (날씨각 아이콘). 일출·일몰([data-sd-days]) 부분을 뺐다.
|
||||
4. 원본의 빈 catch 두 곳(FontFace 만들기, document.fonts.add)을 뺐다. 글꼴 하나가 잘못되면 그 글꼴만 포기하고
|
||||
(faces 의 catch), 글꼴을 붙이다 오류가 나도 카드는 그린다(finally).
|
||||
5. 상세형(home) 날짜(.wx-dt)는 통째로 들어갈 때만 보인다. 원본은 좁으면 '1…' 처럼 말줄임으로 잘렸다. 카드를 그린 직후와
|
||||
iframe 폭이 바뀔 때(resize) 글자 폭과 칸 폭을 비교해, 안 들어가면 상자에 is-nodt 를 붙여 숨긴다(card.css).
|
||||
6. 그리기 전에는 원본의 빈 자리 표시 대신 서버 HTML 에 처음부터 든 토끼 로딩 화면(.wx-load)이 보이고, is-ready·
|
||||
is-failed 가 붙으면 card.css 가 감춘다. 못 그렸을 때 링크 글자는 서버가 넣은 '날씨각에서 날씨 보기 ›'(원본은 '○○ 날씨
|
||||
보기'와 새 창 그림)이고, 실패할 때 이 파일은 그 글자를 바꾸지 않는다. 이 파일이 아예 안 오면 card.css 가 8초 뒤 같은
|
||||
링크를 보인다.
|
||||
그대로 둔 것: 오늘(한국 날짜) 값이 아니면 그리지 않음, 날씨각 둥근 글꼴(Jua, Bagel Fat One)을 Google Fonts 에서
|
||||
카드 글자만 받기(2.5초 넘으면 기본 글꼴), 화면 밖이면 움직임 멈춤(is-off), 그리다 실패하면 is-failed.
|
||||
밖으로 나가는 요청은 이 글꼴뿐이다(쿠키·localStorage·통계 없음). 글은 textContent 로만 넣는다.
|
||||
움직임 줄이기 설정이면 떨어지기·떠 있기·별똥별·반짝임·비 내리기·토끼 뛰기가 없다(card.css). */
|
||||
(function () {
|
||||
"use strict";
|
||||
var doc = document, win = window;
|
||||
var SVG = "http://www.w3.org/2000/svg";
|
||||
function $all(sel, el) { return Array.prototype.slice.call((el || doc).querySelectorAll(sel)); }
|
||||
// the visitor's date and time in Korea
|
||||
function seoul() {
|
||||
var o = {};
|
||||
try {
|
||||
new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Seoul", year: "numeric", month: "2-digit", day: "2-digit",
|
||||
hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date()).forEach(function (p) { o[p.type] = p.value; });
|
||||
// oxlint-disable-next-line no-unused-vars -- 바인딩 없는 catch 는 옛 브라우저에서 파일 전체가 문법 오류가 된다
|
||||
} catch (e) { return null; }
|
||||
if (!(o.year && o.month && o.day)) return null;
|
||||
return { iso: o.year + "-" + o.month + "-" + o.day, mo: +o.month, h: (+o.hour || 0) % 24, mi: +o.minute || 0 };
|
||||
}
|
||||
var T = seoul(), day = T ? T.iso : "";
|
||||
|
||||
// ------------------------------------------------------------ weather
|
||||
var boxes = $all(".wx");
|
||||
if (!boxes.length) return;
|
||||
|
||||
// the card's words (군산각's data-wx-w on its Korean pages)
|
||||
var WORDS = {
|
||||
more: "자세히 보기",
|
||||
score: "지금 날씨 점수",
|
||||
slots: { morning: "아침", day: "낮", sunset: "저녁", night: "밤", now: "지금" },
|
||||
sky: { sun: "맑음", sun_cloud: "구름 조금", cloud: "흐림", rain: "비", snow: "눈", moon: "맑음" }
|
||||
};
|
||||
// 날씨각's own tables (its app: the hero card)
|
||||
var COLS = ["morning", "day", "sunset", "night"];
|
||||
var HOUR = { morning: 7, day: 13, sunset: 18, night: 22 };
|
||||
var ICON = { clear: "sun", partly: "sun_cloud", cloudy: "cloud", rain: "rain", snow: "snow", sleet: "snow" };
|
||||
var CLOUDS = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 };
|
||||
var WANING = ["기우는 달", "하현달", "그믐달"];
|
||||
var SUNSET = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]; // its sky by the clock
|
||||
var ICONS = "/icons/";
|
||||
function num(v) { return typeof v === "number" && isFinite(v); }
|
||||
function deg(v) { return num(v) ? Math.round(v) + "°" : "–"; }
|
||||
function el(tag, cls, text) {
|
||||
var e = doc.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text != null) e.textContent = text;
|
||||
return e;
|
||||
}
|
||||
function clockSky() {
|
||||
if (!T) return "day";
|
||||
var h = T.h + T.mi / 60, s = SUNSET[T.mo - 1] || 18.5;
|
||||
return h >= 5 && h < 11 ? "morning" : h >= 11 && h < s + 1 ? (h < s - 2 ? "day" : "sunset") : "night";
|
||||
}
|
||||
// a slot's sky as 날씨각 reads it (rain_type: 2 rain · 3 sleet · 4 snow · 5 shower; sky: 2 partly · 3 cloudy)
|
||||
function kind(s) {
|
||||
if (!s) return "clear";
|
||||
var r = s.rain_type, k = s.sky;
|
||||
if (r === 2 || r === 5) return "rain";
|
||||
if (r === 4) return "snow";
|
||||
if (r === 3) return "sleet";
|
||||
if (k === 3) return "cloudy";
|
||||
if (k === 2) return "partly";
|
||||
if (r == null && k == null) return { cloud: "cloudy", rain: "rain", snow: "snow" }[s.icon] || "clear";
|
||||
return "clear";
|
||||
}
|
||||
// the slot for a cell: the last at or before its hour (one with a figure after it when that one has none)
|
||||
function pick(slots, hour) {
|
||||
var n = null;
|
||||
slots.forEach(function (s) { if (s.hh <= hour) n = s; });
|
||||
n = n || slots[0];
|
||||
if (!num(n.temp_c)) n = slots.filter(function (s) { return s.hh > hour && num(s.temp_c); })[0] || n;
|
||||
return n;
|
||||
}
|
||||
function nearest(slots) {
|
||||
var t = Date.now(), have = slots.filter(function (s) { return num(s.temp_c); });
|
||||
return have.reduce(function (a, s) { return Math.abs(s.ms - t) < Math.abs(a.ms - t) ? s : a; }, have[0]);
|
||||
}
|
||||
function usable(feed, today) {
|
||||
var h = feed && feed.hero;
|
||||
if (!h || typeof h !== "object" || !num(h.weather_score)) return null;
|
||||
if (!today || typeof today !== "object") return null;
|
||||
if (day && (String(h.now_at || "").slice(0, 10) !== day || today.day !== day)) return null;
|
||||
var slots = (today.slots || []).filter(function (s) { return s && !isNaN(Date.parse(s.at)); }).map(function (s) {
|
||||
var ms = Date.parse(s.at), k = new Date(ms + 324e5); // its hour in Korea
|
||||
return { ms: ms, hh: k.getUTCHours() + k.getUTCMinutes() / 60, temp_c: s.temp_c, sky: s.sky, rain_type: s.rain_type, icon: s.icon };
|
||||
});
|
||||
if (!slots.some(function (s) { return num(s.temp_c); })) return null;
|
||||
return { hero: h, slots: slots };
|
||||
}
|
||||
|
||||
// 날씨각's moon (its app's own drawing: the disc, its seas and craters, the shade of its phase)
|
||||
var SEAS = [[-.32, -.36, .3, .26], [.12, -.36, .17, .15], [.3, -.06, .2, .17], [-.56, .06, .26, .42], [.66, -.26, .1, .12],
|
||||
[.52, .22, .13, .15], [-.14, .44, .18, .13], [-.46, .5, .1, .09]];
|
||||
var CRATERS = [[.1, .72, .07], [.42, .52, .05], [-.66, -.5, .05], [.62, .52, .04], [-.2, .08, .04]];
|
||||
var TONES = { night: { body: ["#fffcf2", "#f6ebcb", "#e0cc98"], shade: "#1a2050" },
|
||||
dusk: { body: ["#fff8ee", "#ffe2cc", "#f2b9a2"], shade: "#4a2a63" } };
|
||||
var uid = 0;
|
||||
function node(tag, at, kids) {
|
||||
var e = doc.createElementNS(SVG, tag);
|
||||
Object.keys(at || {}).forEach(function (k) { e.setAttribute(k, at[k]); });
|
||||
(kids || []).forEach(function (c) { if (c) e.appendChild(c); });
|
||||
return e;
|
||||
}
|
||||
function shadePath(pct, r) {
|
||||
var f = pct / 100;
|
||||
return "M0," + (-r) + " A" + r + "," + r + " 0 0 0 0," + r + " A" + (r * Math.abs(1 - 2 * f)) + "," + r + " 0 0 " + (f < .5 ? 0 : 1) + " 0," + (-r);
|
||||
}
|
||||
function moon(pct, waxing, tone) {
|
||||
var id = "wxm" + (++uid), a = TONES[tone], o = pct / 100, full = pct >= 99, nw = pct <= 1;
|
||||
var stop = function (off, c, op) { return node("stop", op == null ? { offset: off, "stop-color": c } : { offset: off, "stop-color": c, "stop-opacity": op }); };
|
||||
var defs = node("defs", {}, [
|
||||
node("radialGradient", { id: id + "g" }, [stop("0.6", "#fff4cf", "0.55"), stop("0.8", "#ffe9a8", "0.16"), stop("1", "#ffe9a8", "0")]),
|
||||
node("radialGradient", { id: id + "b", cx: "0.4", cy: "0.36", r: "0.72" }, [stop("0", a.body[0]), stop("0.6", a.body[1]), stop("1", a.body[2])]),
|
||||
node("radialGradient", { id: id + "l" }, [stop("0.72", "#8a6f3c", "0"), stop("1", "#8a6f3c", "0.28")]),
|
||||
node("clipPath", { id: id + "c" }, [node("circle", { r: "1" })]),
|
||||
node("filter", { id: id + "f", x: "-0.2", y: "-0.2", width: "1.4", height: "1.4" }, [node("feGaussianBlur", { stdDeviation: "0.035" })])
|
||||
]);
|
||||
var seas = node("g", { filter: "url(#" + id + "f)", fill: "#c4b287", opacity: "0.55" },
|
||||
SEAS.map(function (e) { return node("ellipse", { cx: e[0], cy: e[1], rx: e[2], ry: e[3] }); }));
|
||||
var disc = node("g", { "clip-path": "url(#" + id + "c)" }, [node("circle", { r: "1", fill: "url(#" + id + "b)" }), seas]
|
||||
.concat(CRATERS.map(function (e) { return node("circle", { cx: e[0], cy: e[1], r: e[2], fill: "#efe2bd", stroke: "#cdbb8c", "stroke-width": "0.018", opacity: "0.8" }); }))
|
||||
.concat([node("circle", { r: "1", fill: "url(#" + id + "l)" }),
|
||||
full ? null : node("path", waxing ? { d: shadePath(pct, 1.04), fill: a.shade, opacity: "0.94", filter: "url(#" + id + "f)" }
|
||||
: { d: shadePath(pct, 1.04), fill: a.shade, opacity: "0.94", filter: "url(#" + id + "f)", transform: "scale(-1,1)" })]));
|
||||
return node("svg", { viewBox: "-1.5 -1.5 3 3", class: "wx-mo", "aria-hidden": "true", focusable: "false" }, [defs,
|
||||
nw ? null : node("circle", { r: "1.5", fill: "url(#" + id + "g)", opacity: String(full ? 1 : .12 + .8 * o) }), disc,
|
||||
nw ? node("circle", { r: "1", fill: "none", stroke: "#fff", "stroke-opacity": "0.18", "stroke-width": "0.025" }) : null]);
|
||||
}
|
||||
// the night sky: 날씨각's 26 stars (kept between the head and the words: a star by a letter reads as part of it,
|
||||
// one behind the see-through link as a dot after it) and 3 shooting stars; rain and snow
|
||||
function sky(kindNow) {
|
||||
var s = el("div", "wx-stars");
|
||||
s.setAttribute("aria-hidden", "true");
|
||||
for (var i = 0; i < 26; i++) {
|
||||
var st = el("i", i % 3 ? "" : "wx-tw");
|
||||
st.style.left = (i * 37 % 100) + "%";
|
||||
st.style.top = (12 + (i * 53 % 60) * .55).toFixed(1) + "%";
|
||||
st.style.opacity = String(.4 + i * 7 % 6 / 10);
|
||||
st.style.setProperty("--dl", (i * 0.7 % 5).toFixed(1) + "s");
|
||||
s.appendChild(st);
|
||||
}
|
||||
[["6%", "80%", "90px", "7s", "1.5s"], ["20%", "52%", "70px", "9s", "4s"], ["34%", "94%", "80px", "11s", "6.5s"]].forEach(function (x) {
|
||||
var sh = el("span", "wx-shoot");
|
||||
sh.style.top = x[0];
|
||||
sh.style.left = x[1];
|
||||
sh.style.setProperty("--len", x[2]);
|
||||
sh.style.setProperty("--dur", x[3]);
|
||||
sh.style.setProperty("--dl", x[4]);
|
||||
s.appendChild(sh);
|
||||
});
|
||||
var out = [s];
|
||||
var rain = kindNow === "rain" || kindNow === "sleet", snow = kindNow === "snow" || kindNow === "sleet";
|
||||
if (rain || snow) {
|
||||
var f = el("div", "wx-fx");
|
||||
f.setAttribute("aria-hidden", "true");
|
||||
var add = function (n, cls, step, a, b, c, d) {
|
||||
for (var i = 0; i < n; i++) {
|
||||
var x = el("i", cls);
|
||||
x.style.left = (i * step % 100) + "%";
|
||||
x.style.setProperty("--top", (i * a % 90) + "%");
|
||||
x.style.setProperty("--dl", (i * b % 100 / c) + "s");
|
||||
x.style.setProperty("--dur", d(i) + "s");
|
||||
f.appendChild(x);
|
||||
}
|
||||
};
|
||||
if (rain) add(22, "wx-drop", 41, 29, 37, 100, function (i) { return .55 + i * 13 % 5 / 10; });
|
||||
if (snow) add(16, "wx-flake", 47, 31, 53, 25, function (i) { return 3.2 + i * 7 % 5 / 2; });
|
||||
out.push(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// the date as 날씨각 writes it ('10월 31일 토요일')
|
||||
function dateWords() {
|
||||
try {
|
||||
return new Intl.DateTimeFormat("ko", { timeZone: "Asia/Seoul", month: "long", day: "numeric", weekday: "long" }).format(new Date());
|
||||
// oxlint-disable-next-line no-unused-vars -- 옛 브라우저용 catch 바인딩 (seoul() 참고)
|
||||
} catch (e) { return ""; }
|
||||
}
|
||||
// the date shows only whole: hidden (is-nodt, card.css) when its letters are wider than its room, never cut ('1…')
|
||||
function fitDate(box) {
|
||||
var dt = box.querySelector("[data-wx-dt]");
|
||||
if (!dt || !dt.textContent) return;
|
||||
box.classList.remove("is-nodt");
|
||||
var r = doc.createRange();
|
||||
r.selectNodeContents(dt);
|
||||
box.classList.toggle("is-nodt", r.getBoundingClientRect().width > dt.getBoundingClientRect().width + .01);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 날씨각's round fonts, only the letters the card shows
|
||||
var FONTS = "https://fonts.googleapis.com/css2?family=";
|
||||
function faces(family, as, text) {
|
||||
// the stylesheet's faces (one or more, each with its unicode-range), loaded before they join the page; none when
|
||||
// the stylesheet or a face does not come
|
||||
var url = FONTS + family + "&text=" + encodeURIComponent(text) + "&display=swap";
|
||||
return win.fetch(url, { mode: "cors", credentials: "omit" }).then(function (r) { return r.ok ? r.text() : ""; }).then(function (css) {
|
||||
var out = [];
|
||||
(css.match(/@font-face\s*{[^}]*}/g) || []).forEach(function (blk) {
|
||||
var src = /src:\s*url\((https:\/\/fonts\.gstatic\.com\/[^)\s]+)\)\s*format\(['"]?woff2['"]?\)/.exec(blk);
|
||||
var ur = /unicode-range:\s*([^;]+);/.exec(blk);
|
||||
if (!src) return;
|
||||
out.push(new win.FontFace(as, "url(" + src[1] + ") format('woff2')", ur ? { unicodeRange: ur[1].trim() } : {}));
|
||||
});
|
||||
return Promise.all(out.map(function (f) { return f.load(); }));
|
||||
}).catch(function () { return []; });
|
||||
}
|
||||
function fonts(round, digits, done) {
|
||||
var over = false;
|
||||
var end = function (list) {
|
||||
if (over) return;
|
||||
over = true;
|
||||
clearTimeout(t);
|
||||
// they join the page now, before the card is drawn in them — never afterwards (nothing changes its letters)
|
||||
try {
|
||||
(list || []).forEach(function (fs) { (fs || []).forEach(function (f) { doc.fonts.add(f); }); });
|
||||
} finally {
|
||||
done();
|
||||
}
|
||||
};
|
||||
var t = setTimeout(function () { end(null); }, 2500);
|
||||
if (!win.FontFace || !doc.fonts || !win.Promise || !win.fetch) return end(null);
|
||||
Promise.all([faces("Jua", "WxJua", round), faces("Bagel+Fat+One", "WxBagel", digits)]).then(end);
|
||||
}
|
||||
function letters(s) {
|
||||
var seen = {}, out = "";
|
||||
s.replace(/\s+/g, "").split("").forEach(function (c) { if (!seen[c]) { seen[c] = 1; out += c; } });
|
||||
return out;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ the card
|
||||
function draw(box, D) {
|
||||
var w = WORDS, side = box.classList.contains("wx-side"), h = D.hero, slots = D.slots;
|
||||
var S = w.slots, SKY = w.sky;
|
||||
var mode = HOUR[h.sky_mode] ? h.sky_mode : clockSky();
|
||||
var now = nearest(slots), skyNow = kind(now);
|
||||
var body = box.querySelector("[data-wx-b]");
|
||||
if (!body) return;
|
||||
box.setAttribute("data-t", mode);
|
||||
box.setAttribute("data-sky", skyNow);
|
||||
var dt = box.querySelector("[data-wx-dt]");
|
||||
if (dt && !side) dt.textContent = dateWords();
|
||||
sky(skyNow).forEach(function (x) { body.appendChild(x); });
|
||||
// the sun, or the moon, with the score; 날씨각's clouds for the sky now
|
||||
var stage = el("div", "wx-sky");
|
||||
for (var i = 0; i < CLOUDS[skyNow]; i++) {
|
||||
var c = el("span", "wx-cl wx-c" + (i + 1));
|
||||
c.setAttribute("aria-hidden", "true");
|
||||
c.appendChild(el("span", "wx-cb"));
|
||||
stage.appendChild(c);
|
||||
}
|
||||
var mn = (mode === "sunset" || mode === "night") && h.moon_name && num(h.moon_pct)
|
||||
? { pct: Math.max(0, Math.min(100, h.moon_pct)), waning: WANING.indexOf(h.moon_name) > -1 } : null;
|
||||
var orb = el("div", "wx-orb" + (mn ? " wx-moon " + (mn.pct >= 50 ? "is-lit" : "is-dim") : ""));
|
||||
if (mn) orb.appendChild(moon(mn.pct, !mn.waning, mode === "sunset" ? "dusk" : "night"));
|
||||
var ob = el("div", "wx-ob");
|
||||
ob.appendChild(orb);
|
||||
stage.appendChild(ob);
|
||||
body.appendChild(stage);
|
||||
var score = el("p", "wx-sc");
|
||||
score.appendChild(el("small", "", w.score));
|
||||
score.appendChild(el("b", "", String(Math.round(h.weather_score))));
|
||||
orb.appendChild(score);
|
||||
// the words: 날씨각's own
|
||||
var say = el("div", "wx-say");
|
||||
if (typeof h.bubble === "string" && h.bubble.trim()) say.appendChild(el("p", "wx-bub", h.bubble.trim()));
|
||||
var sum = h.top1 && typeof h.top1.summary === "string" ? h.top1.summary.trim() : "";
|
||||
if (!side && sum) say.appendChild(el("p", "wx-sum", sum));
|
||||
var st = (Array.isArray(h.status) ? h.status : []).filter(function (x) { return x && typeof x.label === "string" && typeof x.value === "string"; });
|
||||
if (!side && st.length) {
|
||||
var p = el("p", "wx-st");
|
||||
st.forEach(function (x, i) {
|
||||
if (i) { var dot = el("span", "wx-dot", "·"); dot.setAttribute("aria-hidden", "true"); p.appendChild(dot); }
|
||||
var one = el("span", "wx-si" + (x.tone === "warn" ? " is-warn" : ""));
|
||||
one.appendChild(el("span", "wx-sl", x.label));
|
||||
one.appendChild(doc.createTextNode(" "));
|
||||
one.appendChild(el("b", "", x.value));
|
||||
p.appendChild(one);
|
||||
});
|
||||
say.appendChild(p);
|
||||
}
|
||||
if (say.childNodes.length) body.appendChild(say);
|
||||
// the four cells: 아침 · 낮 · 저녁 · 밤, the one it is now '지금'
|
||||
var ol = el("ol", "wx-strip");
|
||||
COLS.forEach(function (k) {
|
||||
var isNow = k === mode, s = isNow ? now : pick(slots, HOUR[k]), sk = kind(s);
|
||||
var ic = k === "night" && sk === "clear" ? "moon" : ICON[sk];
|
||||
var li = el("li", isNow ? "is-now" : "");
|
||||
li.appendChild(el("span", "wx-cn", isNow ? S.now : S[k]));
|
||||
var img = el("img", "wx-ic");
|
||||
img.src = ICONS + ic + ".webp";
|
||||
img.alt = SKY[ic] || "";
|
||||
img.width = img.height = side ? 18 : 22;
|
||||
img.decoding = "async";
|
||||
li.appendChild(img);
|
||||
li.appendChild(el("b", "wx-tc", deg(isNow && num(h.temp_c) ? h.temp_c : s && s.temp_c)));
|
||||
ol.appendChild(li);
|
||||
});
|
||||
body.appendChild(ol);
|
||||
// the link: only the 자세히 보기 button goes to 날씨각 (the rest of the card is not a link)
|
||||
var go = box.querySelector("[data-wx-gl]");
|
||||
if (go) {
|
||||
var t = box.querySelector(".wx-t");
|
||||
go.textContent = "";
|
||||
go.appendChild(el("span", "vh", (t ? t.textContent : "") + " "));
|
||||
go.appendChild(doc.createTextNode(w.more));
|
||||
var arr = el("span", "wx-ar", "›");
|
||||
arr.setAttribute("aria-hidden", "true");
|
||||
go.appendChild(arr);
|
||||
}
|
||||
box.classList.add("is-ready");
|
||||
if (!side) fitDate(box);
|
||||
}
|
||||
// the letters the card will show in 날씨각's round font (Jua) and in its score font (Bagel Fat One)
|
||||
function roundText(D) {
|
||||
var h = D.hero, S = WORDS.slots, s = "";
|
||||
boxes.forEach(function (b) {
|
||||
s += (b.querySelector(".wx-t") || {}).textContent || "";
|
||||
s += WORDS.score + S.morning + S.day + S.sunset + S.night + S.now;
|
||||
s += typeof h.bubble === "string" ? h.bubble : "";
|
||||
(Array.isArray(h.status) ? h.status : []).forEach(function (x) { s += (x && x.label || "") + (x && x.value || ""); });
|
||||
});
|
||||
return letters(s + "0123456789-–°·");
|
||||
}
|
||||
|
||||
// the values the server put in the page (#wx-data); null when missing or broken
|
||||
function given() {
|
||||
var x = doc.getElementById("wx-data");
|
||||
if (!x) return null;
|
||||
// oxlint-disable-next-line no-unused-vars -- 옛 브라우저용 catch 바인딩 (seoul() 참고)
|
||||
try { return JSON.parse(x.textContent); } catch (e) { return null; }
|
||||
}
|
||||
function fail() { boxes.forEach(function (b) { b.classList.add("is-failed"); }); }
|
||||
function start() {
|
||||
var g = given(), D = g && typeof g === "object" ? usable({ hero: g.hero }, g.today) : null;
|
||||
if (!D) return fail();
|
||||
fonts(roundText(D), "0123456789", function () {
|
||||
boxes.forEach(function (b) {
|
||||
// oxlint-disable-next-line no-unused-vars -- 옛 브라우저용 catch 바인딩 (seoul() 참고)
|
||||
try { draw(b, D); } catch (e) {
|
||||
var x = b.querySelector("[data-wx-b]");
|
||||
if (x) x.textContent = "";
|
||||
b.classList.remove("is-ready");
|
||||
b.classList.add("is-failed");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
start();
|
||||
// the iframe's width changed (the host page resized): look again whether the date fits
|
||||
win.addEventListener("resize", function () {
|
||||
boxes.forEach(function (b) { if (b.classList.contains("is-ready") && !b.classList.contains("wx-side")) fitDate(b); });
|
||||
});
|
||||
// a card off the screen (the host page scrolled it away) rests: its motion paused
|
||||
if (win.IntersectionObserver) {
|
||||
var rest = new win.IntersectionObserver(function (seen) {
|
||||
seen.forEach(function (e) { e.target.classList.toggle("is-off", !e.isIntersecting); });
|
||||
});
|
||||
boxes.forEach(function (b) { rest.observe(b); });
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>날씨각</title>
|
||||
<meta name="color-scheme" content="light">
|
||||
<!-- 백엔드가 안 될 때 nginx 가 /embed/card 대신 주는 화면 (nginx.conf 의 @embed_quiet). 백엔드의 조용한 화면(embed_service.render_quiet)과 같은 모양, 배경은 sky -->
|
||||
<style>html,body{margin:0;height:100%}body{display:flex;align-items:center;justify-content:center;box-sizing:border-box;padding:16px}a{display:inline-flex;align-items:center;min-height:44px;padding:0 18px;border-radius:999px;background:#fff;color:#28304a;font:700 14px/1.3 -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", sans-serif;text-decoration:none;white-space:nowrap;box-shadow:0 4px 12px rgba(40,48,74,.12)}a:hover{color:#1d4f96;text-decoration:underline}.wx-q-sky::before{content:"";position:fixed;inset:0;z-index:-1;border-radius:28px;background:linear-gradient(#9fd3ff,#cfe9ff 55%,#f1f8ff)}</style>
|
||||
</head>
|
||||
<body class="wx-q-sky">
|
||||
<a href="https://weather.o2o.kr/?utm_source=widget&utm_medium=embed&utm_campaign=unknown" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,54 @@
|
||||
/* 날씨각 위젯 스크립트 — 다른 사이트가 날씨각 링크와 함께 붙이는 작은 로더 (붙이는 코드는 src/lib/embedWidget.ts 의 embedScript).
|
||||
<a class="nalssigak-weather" data-region="지역 코드 10자리" data-type="side|home" data-bg="sky|light|dark"> 링크 자리에
|
||||
카드 iframe(/embed/card)을 끼워 넣는다. iframe 의 주소·크기·style 은 embedCode 가 만드는 iframe 과 같다
|
||||
(tests/embedLoader.test.mjs 가 둘이 같은지 본다). 값이 틀린 링크는 그대로 두고, 이 파일이 막히거나 안 오면 링크가 남는다.
|
||||
- 주소에 버전이 없어 붙인 사이트가 늘 최신 파일을 받는다(nginx /embed/ 1시간 캐시). 고칠 때 붙인 코드가 바뀌지 않게 한다.
|
||||
- 날씨각 주소(origin)는 이 스크립트의 주소에서 얻는다 (로컬 도커에서도 그 서버의 카드를 붙인다).
|
||||
- 남의 페이지에서 도니까 iframe 끼워 넣기 외에는 하지 않는다: 전역 이름·쿠키·저장소·추가 요청·콘솔 출력 없음.
|
||||
- 옛 브라우저에서도 돌게 ES5 로만 쓴다. 화면에 가까워질 때 불러오기는 iframe 의 loading="lazy" 에 맡긴다. */
|
||||
(function () {
|
||||
"use strict";
|
||||
var doc = document;
|
||||
// 모양별 [기본 높이, 최대 높이, 최소 폭, 최대 폭] (px), 폭:높이 비율 — embedWidget.ts 의 EMBED_HEIGHT·EMBED_MAX_HEIGHT·EMBED_MIN_WIDTH·EMBED_MAX_WIDTH, EMBED_RATIO
|
||||
var SIZE = { side: [245, 320, 220, 440, "11/8"], home: [400, 520, 280, 720, "18/13"] };
|
||||
var BGS = { sky: 1, light: 1, dark: 1 };
|
||||
var own = Object.prototype.hasOwnProperty;
|
||||
|
||||
// currentScript 는 처음 실행될 때만 있다. 없는 브라우저면 이 파일을 부른 script 태그를 찾는다
|
||||
var me = doc.currentScript;
|
||||
if (!me) {
|
||||
var found = doc.querySelectorAll('script[src*="/embed/widget.js"]');
|
||||
me = found[found.length - 1];
|
||||
}
|
||||
var origin = me && /^https?:\/\/[^/?#]+/i.exec(me.src || "");
|
||||
if (!origin) return;
|
||||
origin = origin[0];
|
||||
|
||||
function put(a) {
|
||||
var region = a.getAttribute("data-region");
|
||||
var kind = a.getAttribute("data-type") || "side";
|
||||
var bg = a.getAttribute("data-bg") || "sky";
|
||||
if (!/^[0-9]{10}$/.test(region || "") || !own.call(SIZE, kind) || !own.call(BGS, bg) || !a.parentNode) return;
|
||||
var s = SIZE[kind];
|
||||
var title = (a.textContent || "").replace(/\s+/g, " ").replace(/^ | $/g, "") || "날씨각";
|
||||
var f = doc.createElement("iframe");
|
||||
f.setAttribute("src", origin + "/embed/card?region=" + encodeURIComponent(region) + "&type=" + kind + "&bg=" + bg);
|
||||
f.setAttribute("title", title);
|
||||
f.setAttribute("width", "100%");
|
||||
f.setAttribute("height", String(s[0]));
|
||||
f.setAttribute("style", "border:0;width:100%;height:auto;aspect-ratio:" + s[4] + ";min-width:" + s[2] + "px;max-width:" + s[3] + "px;min-height:" + s[0] + "px;max-height:" + s[1] + "px;border-radius:28px");
|
||||
f.setAttribute("loading", "lazy");
|
||||
f.setAttribute("referrerpolicy", "origin");
|
||||
a.parentNode.replaceChild(f, a);
|
||||
}
|
||||
|
||||
// 끼워 넣은 링크는 문서에서 빠지므로 여러 번 돌아도(스크립트를 두 번 붙임) 카드는 하나다
|
||||
function place() {
|
||||
var links = doc.querySelectorAll("a.nalssigak-weather[data-region]");
|
||||
for (var i = 0; i < links.length; i++) put(links[i]);
|
||||
}
|
||||
|
||||
place();
|
||||
// 문서가 다 읽히기 전에 돌았으면 스크립트보다 아래에 있는 링크를 위해 다 읽힌 뒤 한 번 더
|
||||
if (doc.readyState === "loading") doc.addEventListener("DOMContentLoaded", place);
|
||||
})();
|
||||
@@ -13,6 +13,7 @@ import { TalkPage } from './b/TalkPage'
|
||||
import { TodayPage } from './b/TodayPage'
|
||||
import { TypePage } from './b/TypePage'
|
||||
import { WeekPage } from './b/WeekPage'
|
||||
import { WidgetPage } from './b/WidgetPage'
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
@@ -34,6 +35,7 @@ export default function App() {
|
||||
<Route path="talk" element={<TalkPage />} />
|
||||
<Route path="shorts/:id?" element={<ShortsPage />} />
|
||||
<Route path="game" element={<CloudMergePage />} />
|
||||
<Route path="widget" element={<WidgetPage />} />
|
||||
<Route path="*" element={<TodayPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
+69
-23
@@ -1,5 +1,6 @@
|
||||
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 { useLocation, useNavigate } from 'react-router'
|
||||
import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import {
|
||||
@@ -46,7 +47,7 @@ import { WeatherWhySheet } from './weatherWhy'
|
||||
import { useSky } from './skyContext'
|
||||
import { LEVELS } from './cloudMerge'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
import { SheetContext, sheetEntryOnTop, useSheet, type CommentTarget, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { SheetContext, sheetEntryOnTop, useSheet, type CommentTarget, type RegionPick, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { MyTalks } from './talk'
|
||||
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
|
||||
@@ -141,7 +142,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
}, [isOpen])
|
||||
|
||||
const then = shown?.type === 'login' ? shown.then : undefined
|
||||
const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : TITLES[shown.type]
|
||||
const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : shown.type === 'region' && shown.pick ? '미리 볼 지역 고르기' : TITLES[shown.type]
|
||||
|
||||
return (
|
||||
<dialog
|
||||
@@ -175,7 +176,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{shown.type === 'comments' && <CommentsSheet to={shown} draft={shown.draft} />}
|
||||
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={shown.why} />}
|
||||
{shown.type === 'me' && <MeSheet onDone={onClose} />}
|
||||
{shown.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
{shown.type === 'region' && <RegionSheet onDone={onClose} pick={shown.pick} />}
|
||||
{shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
|
||||
{shown.type === 'myGak' && <MyGakSheet gak={shown.gak} shot={shown.shot} onDone={onClose} />}
|
||||
{shown.type === 'install' && <InstallSheet />}
|
||||
@@ -560,9 +561,28 @@ const CONTACTS = [
|
||||
{ method: 'phone', label: '전화 문의', value: '010-2755-6463', href: 'tel:010-2755-6463', icon: 'M6.6 3h3l1.5 4.2-2 1.5a12 12 0 0 0 6.2 6.2l1.5-2L21 14.4v3A2.6 2.6 0 0 1 18.4 20 15.4 15.4 0 0 1 4 5.6 2.6 2.6 0 0 1 6.6 3Z' },
|
||||
{ method: 'email', label: '이메일 문의', value: 'sales@o2o.kr', href: 'mailto:sales@o2o.kr', icon: 'M3.5 6.5h17v11h-17zM4 7l8 6.5L20 7' },
|
||||
] as const
|
||||
// 창 안의 해: 다른 사이트에 붙이는 날씨 카드
|
||||
const WIDGET_ICON = 'M5 4.5h14A1.5 1.5 0 0 1 20.5 6v12a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 18V6A1.5 1.5 0 0 1 5 4.5ZM3.5 8.5h17M14.5 14a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0Z'
|
||||
|
||||
/** 오른쪽 아래 문의 버튼으로 여는 창: 운영사 소개와 전화·이메일 */
|
||||
/** 오른쪽 아래 문의 버튼으로 여는 창: 운영사 소개와 전화·이메일, 날씨 위젯 사용 방법으로 가는 줄(토스 빌드에는 없음) */
|
||||
function ContactSheet({ onDone }: { onDone: () => void }) {
|
||||
const navigate = useNavigate()
|
||||
const { pathname } = useLocation()
|
||||
// 창이 쌓아 둔 방문 기록을 닫으며 되돌리므로(history.back), 되돌린 뒤(popstate)에 옮겨야 새 주소가 안 지워지고 뒤로 가기가 이 화면으로 온다
|
||||
const toWidget = () => {
|
||||
if (pathname === '/widget') {
|
||||
onDone()
|
||||
return
|
||||
}
|
||||
const go = () => navigate('/widget', { state: { from: 'contact' } })
|
||||
if (sheetEntryOnTop()) {
|
||||
window.addEventListener('popstate', go, { once: true })
|
||||
onDone()
|
||||
} else {
|
||||
onDone()
|
||||
go()
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Body className="flex flex-col items-center text-center">
|
||||
<img src="/b/aio2o.png" alt="AIO2O" width={162} height={27} className="mt-1 block h-[27px] w-auto" />
|
||||
@@ -570,7 +590,7 @@ function ContactSheet({ onDone }: { onDone: () => void }) {
|
||||
<p className="mt-1.5 mb-0 text-[13.5px] leading-[1.6] font-semibold text-(--ink2)">
|
||||
날씨에 맞춘 광고, 지역 축제·행사 소개,
|
||||
<br />
|
||||
콘텐츠 협업 같은 제휴 문의를 받아요.
|
||||
날씨 위젯, 콘텐츠 협업 같은 제휴 문의를 받아요.
|
||||
<br />
|
||||
전화나 이메일로 편하게 알려 주세요.
|
||||
</p>
|
||||
@@ -591,6 +611,20 @@ function ContactSheet({ onDone }: { onDone: () => void }) {
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
{/* 위젯은 다른 사이트에 붙이는 웹 기능이라 토스 미니앱에서는 보이지 않는다 */}
|
||||
{!IS_TOSS && (
|
||||
<button type="button" onClick={toWidget} className="flex w-full cursor-pointer items-center gap-3 rounded-[16px] bg-[#f3f6fb] p-3 text-left text-(--ink)">
|
||||
<span className="b-keep-bg grid size-11 shrink-0 place-items-center rounded-full bg-white text-(--orange)">
|
||||
<svg viewBox="0 0 24 24" className="size-[22px]" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d={WIDGET_ICON} />
|
||||
</svg>
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[17px] font-extrabold">날씨 위젯 달기</span>
|
||||
<span className="text-xl text-(--orange)" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-3.5 mb-0 text-[12px] font-semibold text-(--ink3)">날씨각은 주식회사 에이아이오투오가 만들어요</p>
|
||||
<button type="button" onClick={onDone} className="mt-3 w-full cursor-pointer rounded-[14px] bg-(--orange) p-3 text-[15px] font-extrabold text-white">
|
||||
@@ -1440,8 +1474,10 @@ const pageHref = (code: string) => {
|
||||
return p ? `/today/${p.path}` : '/'
|
||||
}
|
||||
|
||||
function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
/** pick 이 있으면 '고르기만' 모드: 앱 지역을 바꾸지 않고(region_change 도 안 보냄) 고른 지역을 onPick 으로 넘긴다. 위치로 찾기·로그인 줄은 없다 */
|
||||
function RegionSheet({ onDone, pick }: { onDone: () => void; pick?: RegionPick }) {
|
||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||
const current = pick ? pick.current : region.code
|
||||
const { me, logout } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const alive = useRef(true)
|
||||
@@ -1459,12 +1495,16 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
|
||||
return (
|
||||
<Body>
|
||||
<button type="button" onClick={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
지금 위치로 찾기
|
||||
</button>
|
||||
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
||||
{LOCATE_TEXT[locateStatus]}
|
||||
</p>
|
||||
{!pick && (
|
||||
<>
|
||||
<button type="button" onClick={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
지금 위치로 찾기
|
||||
</button>
|
||||
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
||||
{LOCATE_TEXT[locateStatus]}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="구 이름으로 찾기 (예: 마포)" aria-label="구 이름으로 찾기" className="mt-1 w-full rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
{listLoad === 'loading' && <RegionsSkel />}
|
||||
{listLoad !== 'loading' && !regions.length && (listLoad === 'ready' ? <StateBox load={listLoad} empty="찾는 구가 없어요." className="mt-3" /> : <StateBox load={listLoad} onRetry={() => list.refetch()} hold={<RegionsSkel />} className="inset-x-0 top-2 bottom-0" />)}
|
||||
@@ -1473,27 +1513,33 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
<li key={r.code}>
|
||||
<a
|
||||
href={pageHref(r.code)}
|
||||
aria-current={r.code === region.code ? 'true' : undefined}
|
||||
aria-current={r.code === current ? 'true' : undefined}
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'list' })
|
||||
if (pick) {
|
||||
pick.onPick(r)
|
||||
} else {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'list' })
|
||||
}
|
||||
onDone()
|
||||
}}
|
||||
className={cx('flex w-full cursor-pointer items-center justify-between border-b-[1.5px] border-(--line) px-1 py-3 text-left font-jua text-[17px]', r.code === region.code && 'text-(--orange)')}
|
||||
className={cx('flex w-full cursor-pointer items-center justify-between border-b-[1.5px] border-(--line) px-1 py-3 text-left font-jua text-[17px]', r.code === current && 'text-(--orange)')}
|
||||
>
|
||||
{r.name}
|
||||
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
|
||||
{r.code === current && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
||||
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}
|
||||
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
|
||||
{me ? '로그아웃' : '로그인'}
|
||||
</button>
|
||||
</p>
|
||||
{!pick && (
|
||||
<p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
||||
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}
|
||||
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
|
||||
{me ? '로그아웃' : '로그인'}
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router'
|
||||
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import { track } from '../lib/analytics'
|
||||
import { EMBED_BG_LABEL, EMBED_HEIGHT, EMBED_KIND_LABEL, EMBED_MAX_HEIGHT, EMBED_MAX_WIDTH, EMBED_MIN_WIDTH, EMBED_RATIO, embedCode, embedScript, embedSrc, type EmbedBg, type EmbedKind } from '../lib/embedWidget'
|
||||
import { IS_TOSS } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ownPage, useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { TAP44 } from './ui'
|
||||
|
||||
type Method = 'script' | 'iframe'
|
||||
const KINDS: EmbedKind[] = ['side', 'home']
|
||||
const BGS: EmbedBg[] = ['sky', 'light', 'dark']
|
||||
const METHODS: Method[] = ['script', 'iframe']
|
||||
const METHOD_LABEL: Record<Method, string> = { script: '스크립트(권장)', iframe: 'iframe 코드' }
|
||||
/** 배경 칩 글자는 짧게. 읽어 주는 이름은 EMBED_BG_LABEL 의 전체 이름 */
|
||||
const BG_CHIP: Record<EmbedBg, string> = { sky: '기본형', light: '밝은', dark: '어두운' }
|
||||
const STAGE_NOTE: Record<EmbedBg, string> = { sky: '', light: ' · 밝은 바탕', dark: ' · 어두운 바탕' }
|
||||
const CHIP = 'min-w-0 flex-1 cursor-pointer rounded-[14px] border-[1.5px] px-1.5 py-2.5 text-center text-[13.5px] font-extrabold'
|
||||
const CHIP_ON = 'border-(--ink) bg-(--ink) text-white'
|
||||
const CHIP_OFF = 'border-(--line) bg-white text-(--ink)'
|
||||
// 붙이는 방법 탭: 고르는 값(칩)과 달리 코드 상자 머리에 붙은 밑줄 탭
|
||||
const TAB = "relative min-h-11 cursor-pointer px-3 text-[13.5px] after:absolute after:inset-x-3 after:bottom-0 after:h-[2.5px] after:rounded-full after:content-['']"
|
||||
const TAB_ON = 'font-extrabold text-white after:bg-(--orange)'
|
||||
const TAB_OFF = 'font-bold text-[#8f98c0] after:bg-transparent'
|
||||
|
||||
/** 다른 사이트에 날씨 카드(위젯)를 붙이는 방법 (/widget). 미리보기를 맨 위에 두고, 고르면 미리보기와 코드가 같이 바뀐다 */
|
||||
export function WidgetPage() {
|
||||
const navigate = useNavigate()
|
||||
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
|
||||
const { state } = useLocation()
|
||||
// 문의 창의 '날씨 위젯 달기'로 왔는지. 들어올 때 한 번만 본다
|
||||
const [from] = useState<'contact' | 'direct'>(() => ((state as { from?: string } | null)?.from === 'contact' ? 'contact' : 'direct'))
|
||||
// 지역은 이 페이지만의 값: 여기서 고르기 전까지는 앱 지역(처음 온 사람의 자동 위치 맞춤 포함)을 따라가고,
|
||||
// 고르기만 하는 지역 창으로 한 번 고른 뒤에는 앱 지역이 바뀌어도 따라가지 않는다. 앱 지역은 바꾸지 않는다
|
||||
const { region: appRegion } = useRegion()
|
||||
const [picked, setPicked] = useState<RegionData | null>(null)
|
||||
const region = picked ?? appRegion
|
||||
const { open } = useSheet()
|
||||
const [kind, setKind] = useState<EmbedKind>('side')
|
||||
const [bg, setBg] = useState<EmbedBg>('sky')
|
||||
const [method, setMethod] = useState<Method>('script')
|
||||
const [copy, setCopy] = useState<'idle' | 'done' | 'failed'>('idle')
|
||||
// 복사에 성공한 횟수: '복사했어요'에서 다시 눌러도 2초를 새로 세고 화면 낭독기가 다시 알리게
|
||||
const [copies, setCopies] = useState(0)
|
||||
const codeRef = useRef<HTMLPreElement>(null)
|
||||
// 복사한 코드와 화면의 코드가 같게 둘 다 여기서 나온다
|
||||
const codeFor = { origin: SITE_URL, region: region.code, regionName: region.short_name, kind, bg }
|
||||
const code = method === 'script' ? embedScript({ ...codeFor, regionPath: ownPage(region.code)?.path ?? null }) : embedCode(codeFor)
|
||||
// 미리보기는 지금 연 사이트의 카드 (도커·개발 서버에서도 보이게)
|
||||
const src = embedSrc(window.location.origin, region.code, kind, bg)
|
||||
|
||||
useEffect(() => track('widget_guide_view', { from }), [from])
|
||||
|
||||
useEffect(() => {
|
||||
if (copy !== 'done') return
|
||||
const id = setTimeout(() => setCopy('idle'), 2000)
|
||||
return () => clearTimeout(id)
|
||||
}, [copy, copies])
|
||||
|
||||
// 코드가 바뀌면 지난 복사 결과('복사했어요'·직접 복사 안내)를 지운다. 앱 지역을 따라 지역이 바뀔 때도
|
||||
const [shownRegion, setShownRegion] = useState(region.code)
|
||||
if (region.code !== shownRegion) {
|
||||
setShownRegion(region.code)
|
||||
setCopy('idle')
|
||||
}
|
||||
// 같은 지역을 골라도 이제부터는 앱 지역을 따라가지 않는다
|
||||
const pickRegion = (r: RegionData) => {
|
||||
setPicked(r)
|
||||
if (r.code === region.code) return
|
||||
track('widget_option_select', { option: 'region', value: r.code })
|
||||
}
|
||||
const pickKind = (k: EmbedKind) => {
|
||||
if (k === kind) return
|
||||
setKind(k)
|
||||
setCopy('idle')
|
||||
track('widget_option_select', { option: 'kind', value: k })
|
||||
}
|
||||
const pickBg = (b: EmbedBg) => {
|
||||
if (b === bg) return
|
||||
setBg(b)
|
||||
setCopy('idle')
|
||||
track('widget_option_select', { option: 'bg', value: b })
|
||||
}
|
||||
const pickMethod = (m: Method) => {
|
||||
if (m === method) return
|
||||
setMethod(m)
|
||||
setCopy('idle')
|
||||
}
|
||||
|
||||
/** 클립보드를 못 쓰면 코드 글자를 전부 선택해 두고 직접 복사하게 한다 */
|
||||
const selectCode = () => {
|
||||
const box = codeRef.current
|
||||
const sel = window.getSelection()
|
||||
if (!box || !sel) return
|
||||
const range = document.createRange()
|
||||
range.selectNodeContents(box)
|
||||
sel.removeAllRanges()
|
||||
sel.addRange(range)
|
||||
}
|
||||
const copyCode = async () => {
|
||||
try {
|
||||
if (!navigator.clipboard) throw new Error('클립보드를 쓸 수 없는 브라우저')
|
||||
await navigator.clipboard.writeText(code)
|
||||
} catch (e) {
|
||||
console.warn('[widget] 코드를 복사하지 못함', e)
|
||||
selectCode()
|
||||
setCopy('failed')
|
||||
return
|
||||
}
|
||||
setCopy('done')
|
||||
setCopies((n) => n + 1)
|
||||
track('widget_code_copy', { kind, bg, region: region.code, method })
|
||||
}
|
||||
|
||||
const notes = [
|
||||
`놓은 자리 폭에 맞춰 자동으로 늘고 줄어요. (${EMBED_MIN_WIDTH[kind]}~${EMBED_MAX_WIDTH[kind]}px)`,
|
||||
`높이는 폭에 맞춰 ${EMBED_HEIGHT[kind]}~${EMBED_MAX_HEIGHT[kind]}px 사이에서 자동으로 바뀌어요.`,
|
||||
...(method === 'iframe' ? ['코드의 style은 지우지 말아 주세요.'] : []),
|
||||
'무료이고 신청 없이 쓸 수 있어요. 날씨각 링크는 그대로 두어 주세요.',
|
||||
'예고 없이 바뀌거나 중단될 수 있어요.',
|
||||
'카드가 안 보이면 사이트 보안 설정에서 weather.o2o.kr 을 허용해 주세요.',
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="pb-8">
|
||||
<div className="flex items-center gap-1 px-3 pt-1">
|
||||
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
|
||||
‹
|
||||
</button>
|
||||
<h2 className="m-0 px-1 font-batang text-[20px] font-bold">날씨 위젯</h2>
|
||||
</div>
|
||||
|
||||
<div className="px-[18px]">
|
||||
<p className="mt-1.5 mb-0 font-bold text-(--ink2)">내 사이트에 오늘 날씨 카드를 달아 보세요.</p>
|
||||
|
||||
{IS_TOSS ? (
|
||||
// 토스 미니앱에서 주소로 열었을 때: 미리보기 대신 웹 주소 안내 (고르기·코드는 SITE_URL 기준이라 그대로 둔다)
|
||||
<p className="mt-3 mb-0 rounded-[18px] border border-dashed border-[#c5d2e4] bg-white p-3.5 text-[13.5px] leading-[1.6] font-bold text-(--ink2)">
|
||||
날씨 위젯은 웹에서 만들 수 있어요.{' '}
|
||||
<a href={`${SITE_URL}/widget`} target="_blank" rel="noopener" className="text-(--ink) underline">
|
||||
weather.o2o.kr/widget
|
||||
</a>{' '}
|
||||
에서 열어 주세요.
|
||||
</p>
|
||||
) : (
|
||||
// b-day: 밤 화면에서도 미리보기 바탕은 고른 배경 그대로 (흰색·어두운 색)
|
||||
<div className={cx('b-day mt-3 rounded-[18px] p-3.5', bg === 'dark' ? 'bg-[#111318]' : 'border border-dashed border-[#c5d2e4] bg-white')}>
|
||||
<p className={cx('m-0 mb-2 text-[12.5px] font-bold', bg === 'dark' ? 'text-[#aab0c4]' : 'text-(--ink3)')}>이렇게 보여요{STAGE_NOTE[bg]}</p>
|
||||
<iframe key={src} src={src} title="미리보기" className="mx-auto block w-full border-0" style={{ maxWidth: EMBED_MAX_WIDTH[kind], aspectRatio: EMBED_RATIO[kind], minHeight: EMBED_HEIGHT[kind], maxHeight: EMBED_MAX_HEIGHT[kind], borderRadius: 28 }} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-3 flex flex-col gap-2.5">
|
||||
<Row label="지역">
|
||||
<button type="button" onClick={() => open({ type: 'region', pick: { current: region.code, onPick: pickRegion } })} aria-label={`지역 바꾸기, 지금 ${region.name}`} className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-[14px] border-[1.5px] border-(--line) bg-white px-3.5 py-2.5 text-left font-extrabold text-(--ink)">
|
||||
<span className="min-w-0 truncate">{region.name}</span>
|
||||
<span className="shrink-0 text-[13px] text-(--ink2)">바꾸기 ›</span>
|
||||
</button>
|
||||
</Row>
|
||||
<Row label="모양">
|
||||
<div role="group" aria-label="모양" className="flex gap-2">
|
||||
{KINDS.map((k) => (
|
||||
<button key={k} type="button" aria-pressed={k === kind} onClick={() => pickKind(k)} className={cx(CHIP, k === kind ? CHIP_ON : CHIP_OFF)}>
|
||||
{EMBED_KIND_LABEL[k]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Row>
|
||||
<Row label="배경">
|
||||
<div role="group" aria-label="배경" className="flex gap-2">
|
||||
{BGS.map((b) => (
|
||||
<button key={b} type="button" aria-pressed={b === bg} aria-label={EMBED_BG_LABEL[b]} onClick={() => pickBg(b)} className={cx(CHIP, b === bg ? CHIP_ON : CHIP_OFF)}>
|
||||
{BG_CHIP[b]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Row>
|
||||
</div>
|
||||
|
||||
{/* 탭 → 코드 → 복사 버튼: 탭은 코드 상자 머리에 붙여 한 덩어리로 보이게 */}
|
||||
<div className="mt-4 overflow-hidden rounded-[14px] bg-[#1d2440]">
|
||||
<div role="tablist" aria-label="붙이는 방법" className="flex border-b border-white/10 px-1">
|
||||
{METHODS.map((m) => (
|
||||
<button key={m} type="button" role="tab" aria-selected={m === method} onClick={() => pickMethod(m)} className={cx(TAB, m === method ? TAB_ON : TAB_OFF)}>
|
||||
{METHOD_LABEL[m]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{method === 'iframe' && <p className="m-0 px-3 pt-2.5 text-[12.5px] font-bold text-[#aab3d9]">스크립트를 넣을 수 없는 곳이라면 이 코드를 쓰세요.</p>}
|
||||
{/* 앱은 글자 선택을 막아 두어(body user-select: none) 이 상자만 선택·길게 눌러 복사할 수 있게 연다 */}
|
||||
<pre ref={codeRef} className="m-0 p-3 font-mono text-[12px] leading-[1.55] break-all whitespace-pre-wrap text-[#e8ecff] select-text [-webkit-touch-callout:default]">
|
||||
{code}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<button type="button" onClick={copyCode} className="mt-2.5 block w-full cursor-pointer rounded-[14px] bg-(--orange) py-3.5 text-center text-[15.5px] font-extrabold text-white">
|
||||
{copy === 'done' ? '복사했어요' : '코드 복사'}
|
||||
</button>
|
||||
<div aria-live="polite">
|
||||
{copy === 'done' && (
|
||||
<span key={copies} className="sr-only">
|
||||
복사했어요
|
||||
</span>
|
||||
)}
|
||||
{copy === 'failed' && <p className="mt-2 mb-0 text-center text-[13px] font-bold text-(--ink2)">코드를 길게 눌러 복사해 주세요</p>}
|
||||
</div>
|
||||
|
||||
<ul className="mt-3 mb-0 flex list-none flex-col gap-1 p-0 text-[12.5px] font-semibold text-(--ink3)">
|
||||
{notes.map((n) => (
|
||||
<li key={n} className="before:content-['·_']">
|
||||
{n}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 고르는 줄: 왼쪽에 이름, 오른쪽에 고르는 것 */
|
||||
function Row({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2.5">
|
||||
<span className="w-9 shrink-0 text-[13px] font-bold text-(--ink2)">{label}</span>
|
||||
<div className="min-w-0 flex-1">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import type { MyGak } from './myGakState'
|
||||
import type { WeatherWhyPayload } from './weatherWhy'
|
||||
import { createContext, use } from 'react'
|
||||
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides). url: 같이 보낼 링크 (없으면 사이트 주소) */
|
||||
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[]; url?: string }
|
||||
|
||||
/** 지역 창 '고르기만' 모드: current 는 '지금 보는 곳'으로 표시할 지역 코드 */
|
||||
export type RegionPick = { current: string; onPick: (r: RegionData) => void }
|
||||
|
||||
/** 댓글이 달린 곳: 운영 포스트 또는 사람 글 */
|
||||
export type CommentTarget = { postId: number } | { talkId: number }
|
||||
type CommentsState = { type: 'comments'; draft?: string } & CommentTarget
|
||||
@@ -16,7 +20,8 @@ export type SheetState =
|
||||
| { type: 'seasonWeek' }
|
||||
| { type: 'login'; then?: CommentsState; why?: 'level' }
|
||||
| { type: 'me' }
|
||||
| { type: 'region' }
|
||||
/** pick: 앱 지역은 그대로 두고 고른 지역만 돌려받는 '고르기만' 모드 (위젯 페이지 미리보기). 창 상태는 방문 기록에 저장하지 않아 함수를 넣어도 된다 */
|
||||
| { type: 'region'; pick?: RegionPick }
|
||||
| { type: 'mix'; shared?: MyGak }
|
||||
| { type: 'myGak'; gak: MyGak; shot?: HTMLElement | null }
|
||||
| { type: 'install' }
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/** 다른 사이트가 iframe 으로 붙이는 날씨 카드의 주소와 붙이는 코드(스크립트·iframe)를 만든다. 브라우저 API 를 쓰지 않아 테스트(node --test)에서도 돈다 */
|
||||
export type EmbedKind = 'side' | 'home'
|
||||
export type EmbedBg = 'sky' | 'light' | 'dark'
|
||||
|
||||
// 화면에 보이는 이름. 주소의 값(side·home, sky·light·dark)은 이미 붙인 코드가 깨지지 않게 그대로 둔다
|
||||
export const EMBED_KIND_LABEL: Record<EmbedKind, string> = { side: '기본형', home: '상세형' }
|
||||
export const EMBED_BG_LABEL: Record<EmbedBg, string> = { sky: '기본형 배경', light: '밝은 바탕용', dark: '어두운 바탕용' }
|
||||
|
||||
// 기본 높이(px): 카드가 넘치거나 스크롤이 생기지 않고 전부 보이는 최소 높이
|
||||
export const EMBED_HEIGHT: Record<EmbedKind, number> = { side: 245, home: 400 }
|
||||
// 최대 높이(px): 붙인 사이트가 높이를 늘려도 카드가 휑해 보이지 않는 데까지
|
||||
export const EMBED_MAX_HEIGHT: Record<EmbedKind, number> = { side: 320, home: 520 }
|
||||
// 최소 폭(px): 이름이 가장 긴 지역 '창원시 마산합포구'로도 제목·버튼이 다 보이는 폭
|
||||
export const EMBED_MIN_WIDTH: Record<EmbedKind, number> = { side: 220, home: 280 }
|
||||
// 최대 폭(px): 이보다 넓으면 카드가 늘어나 보기 나쁘다
|
||||
export const EMBED_MAX_WIDTH: Record<EmbedKind, number> = { side: 440, home: 720 }
|
||||
// 폭:높이 비율 = 최대 폭 ÷ 최대 높이: 높이가 폭에 맞춰 기본 높이~최대 높이 사이에서 바뀌고 최대 폭에서 최대 높이가 된다
|
||||
export const EMBED_RATIO: Record<EmbedKind, string> = { side: '11/8', home: '18/13' }
|
||||
|
||||
/** iframe 의 style. 크기 범위를 모두 코드에 넣어 붙인 사이트의 다른 스타일에 밀리지 않게 한다.
|
||||
* 높이는 aspect-ratio 로 폭을 따르고 min-height·max-height 안에 머문다. aspect-ratio 를 모르는 옛 브라우저는 min-height(기본 높이)로 보인다.
|
||||
* border-radius 는 붙인 사이트가 color-scheme: dark 일 때 카드의 둥근 모서리 밖이 희게 칠해지는 것을 잘라 낸다 (두 모양 모두 28px 모서리).
|
||||
* public/embed/widget.js 도 같은 값을 쓴다 (tests/embedLoader.test.mjs 가 둘이 같은지 본다) */
|
||||
function embedStyle(kind: EmbedKind): string {
|
||||
return `border:0;width:100%;height:auto;aspect-ratio:${EMBED_RATIO[kind]};min-width:${EMBED_MIN_WIDTH[kind]}px;max-width:${EMBED_MAX_WIDTH[kind]}px;min-height:${EMBED_HEIGHT[kind]}px;max-height:${EMBED_MAX_HEIGHT[kind]}px;border-radius:28px`
|
||||
}
|
||||
|
||||
/** HTML 속성 값 안에 넣어도 속성이 깨지지 않게 바꾼다 */
|
||||
function escapeAttr(text: string): string {
|
||||
return text.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
|
||||
}
|
||||
|
||||
/** 카드 화면 주소. region 은 지역 코드(숫자 10자리) */
|
||||
export function embedSrc(origin: string, region: string, kind: EmbedKind, bg: EmbedBg): string {
|
||||
return `${origin}/embed/card?region=${encodeURIComponent(region)}&type=${kind}&bg=${bg}`
|
||||
}
|
||||
|
||||
/** 다른 사이트에 붙여 넣을 iframe 코드 */
|
||||
export function embedCode(p: { origin: string; region: string; regionName: string; kind: EmbedKind; bg: EmbedBg }): string {
|
||||
const src = embedSrc(p.origin, p.region, p.kind, p.bg)
|
||||
const title = escapeAttr(`${p.regionName} 날씨 - 날씨각`)
|
||||
return `<iframe src="${src}" title="${title}" width="100%" height="${EMBED_HEIGHT[p.kind]}" style="${embedStyle(p.kind)}" loading="lazy" referrerpolicy="origin"></iframe>`
|
||||
}
|
||||
|
||||
/** 다른 사이트에 붙여 넣을 스크립트 코드: 날씨각 링크 + widget.js. widget.js 가 링크 자리에 embedCode 와 같은 iframe 을 넣고,
|
||||
* 스크립트가 막히거나 날씨각에 접속이 안 되면 링크가 그대로 남는다. regionPath 는 지역 페이지 주소 이름(없으면 링크는 날씨각 홈) */
|
||||
export function embedScript(p: { origin: string; region: string; regionName: string; regionPath: string | null; kind: EmbedKind; bg: EmbedBg }): string {
|
||||
const href = `${p.origin}${p.regionPath ? `/today/${p.regionPath}` : '/'}?utm_source=widget&utm_medium=embed&utm_campaign=fallback`
|
||||
const text = escapeAttr(`${p.regionName} 날씨 - 날씨각`)
|
||||
return (
|
||||
`<a class="nalssigak-weather" href="${href}"\n` +
|
||||
` data-region="${escapeAttr(p.region)}" data-type="${p.kind}" data-bg="${p.bg}">${text}</a>\n` +
|
||||
`<script src="${p.origin}/embed/widget.js" async></script>`
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// 다른 사이트에 붙이는 스크립트(public/embed/widget.js) 검증: 가짜 문서에서 돌려 링크 자리에 생긴 iframe 이
|
||||
// embedCode 가 만드는 iframe 과 같은지 본다 (크기 상수가 두 파일에서 어긋나지 않게 묶는다). 실행: frontend 폴더에서 npm test
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { test } from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
import { embedCode } from '../src/lib/embedWidget.ts'
|
||||
|
||||
const SOURCE = readFileSync(new URL('../public/embed/widget.js', import.meta.url), 'utf8')
|
||||
const SCRIPT_SRC = 'http://localhost:8080/embed/widget.js'
|
||||
const ORIGIN = 'http://localhost:8080'
|
||||
|
||||
/** 가짜 요소: 속성·글자·부모만 */
|
||||
function node(tag, attrs = {}, text = '') {
|
||||
return {
|
||||
tagName: tag.toUpperCase(),
|
||||
attrs: { ...attrs },
|
||||
textContent: text,
|
||||
parentNode: null,
|
||||
getAttribute(name) {
|
||||
return Object.hasOwn(this.attrs, name) ? this.attrs[name] : null
|
||||
},
|
||||
setAttribute(name, value) {
|
||||
this.attrs[name] = String(value)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** 날씨각 링크 */
|
||||
function link(attrs, text = '군산시 날씨 - 날씨각') {
|
||||
return node('a', { class: 'nalssigak-weather', href: 'https://weather.o2o.kr/today/jeonbuk/gunsan', ...attrs }, text)
|
||||
}
|
||||
|
||||
// widget.js 가 쓰는 선택자만 안다
|
||||
const SELECTORS = {
|
||||
'a.nalssigak-weather[data-region]': (n) => n.tagName === 'A' && (n.attrs.class ?? '').split(/\s+/).includes('nalssigak-weather') && Object.hasOwn(n.attrs, 'data-region'),
|
||||
'script[src*="/embed/widget.js"]': (n) => n.tagName === 'SCRIPT' && (n.attrs.src ?? '').includes('/embed/widget.js'),
|
||||
}
|
||||
|
||||
/** 가짜 문서: body 아래에 링크들과 스크립트 태그가 나란히 있다 */
|
||||
function fakeDoc(links, { scriptSrc = SCRIPT_SRC, current = true, readyState = 'complete' } = {}) {
|
||||
const listeners = {}
|
||||
const body = {
|
||||
children: [],
|
||||
replaceChild(next, old) {
|
||||
const i = this.children.indexOf(old)
|
||||
if (i < 0) throw new Error('없는 자식을 바꾸려 함')
|
||||
this.children[i] = next
|
||||
next.parentNode = this
|
||||
old.parentNode = null
|
||||
return old
|
||||
},
|
||||
}
|
||||
const script = node('script', { src: scriptSrc, async: '' })
|
||||
script.src = scriptSrc // 브라우저는 src 속성(프로퍼티)에 절대 주소를 준다
|
||||
for (const n of [...links, script]) {
|
||||
n.parentNode = body
|
||||
body.children.push(n)
|
||||
}
|
||||
const doc = {
|
||||
readyState,
|
||||
currentScript: current ? script : null,
|
||||
createElement: (tag) => node(tag),
|
||||
querySelectorAll(sel) {
|
||||
const match = SELECTORS[sel]
|
||||
if (!match) throw new Error(`모르는 선택자 ${sel}`)
|
||||
return body.children.filter(match)
|
||||
},
|
||||
addEventListener(type, fn) {
|
||||
;(listeners[type] ??= []).push(fn)
|
||||
},
|
||||
}
|
||||
return {
|
||||
doc,
|
||||
body,
|
||||
fire: (type) => (listeners[type] ?? []).forEach((fn) => fn()),
|
||||
frames: () => body.children.filter((n) => n.tagName === 'IFRAME'),
|
||||
}
|
||||
}
|
||||
|
||||
/** 브라우저처럼 문서만 주고 widget.js 를 돌린다 (console·window 없음: 쓰면 오류로 드러난다) */
|
||||
function run(doc) {
|
||||
vm.runInNewContext(SOURCE, { document: doc })
|
||||
}
|
||||
|
||||
/** embedCode 문자열의 iframe 속성 (HTML 이스케이프를 푼 값) */
|
||||
function attrsOf(html) {
|
||||
const out = {}
|
||||
for (const [, name, value] of html.matchAll(/([a-z]+)="([^"]*)"/g)) {
|
||||
out[name] = value.replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&')
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
test('올바른 링크 → 그 자리에 iframe 하나, 속성은 embedCode 와 같다', () => {
|
||||
for (const kind of ['side', 'home']) {
|
||||
for (const bg of ['sky', 'light', 'dark']) {
|
||||
const a = link({ 'data-region': '5213000000', 'data-type': kind, 'data-bg': bg })
|
||||
const page = fakeDoc([a])
|
||||
run(page.doc)
|
||||
assert.equal(page.frames().length, 1)
|
||||
assert.equal(page.body.children[0], page.frames()[0], '링크가 있던 자리')
|
||||
assert.equal(a.parentNode, null, '링크는 빠진다')
|
||||
assert.deepEqual(page.frames()[0].attrs, attrsOf(embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind, bg })))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('iframe 제목은 링크 글자 (특수문자도 그대로)', () => {
|
||||
const page = fakeDoc([link({ 'data-region': '5213000000' }, 'A&B<C>"D 날씨 - 날씨각')])
|
||||
run(page.doc)
|
||||
assert.deepEqual(page.frames()[0].attrs, attrsOf(embedCode({ origin: ORIGIN, region: '5213000000', regionName: 'A&B<C>"D', kind: 'side', bg: 'sky' })))
|
||||
})
|
||||
|
||||
test('data-type·data-bg 를 빼면 기본형(side)·기본형 배경(sky)', () => {
|
||||
const page = fakeDoc([link({ 'data-region': '5213000000' })])
|
||||
run(page.doc)
|
||||
assert.equal(page.frames()[0].attrs.src, `${ORIGIN}/embed/card?region=5213000000&type=side&bg=sky`)
|
||||
assert.equal(page.frames()[0].attrs.height, '245')
|
||||
assert.equal(page.frames()[0].attrs.style, 'border:0;width:100%;height:auto;aspect-ratio:11/8;min-width:220px;max-width:440px;min-height:245px;max-height:320px;border-radius:28px')
|
||||
})
|
||||
|
||||
test('틀린 지역·모양·배경의 링크는 그대로 둔다', () => {
|
||||
const bad = [
|
||||
link({ 'data-region': '521300000' }),
|
||||
link({ 'data-region': '52130000001' }),
|
||||
link({ 'data-region': '52130000ab' }),
|
||||
link({ 'data-region': '5213000000', 'data-type': 'wide' }),
|
||||
link({ 'data-region': '5213000000', 'data-bg': 'red' }),
|
||||
]
|
||||
const page = fakeDoc(bad)
|
||||
run(page.doc)
|
||||
assert.equal(page.frames().length, 0)
|
||||
assert.deepEqual(page.body.children.slice(0, bad.length), bad)
|
||||
})
|
||||
|
||||
test('두 번 실행해도 iframe 은 하나', () => {
|
||||
const page = fakeDoc([link({ 'data-region': '5213000000' })])
|
||||
run(page.doc)
|
||||
run(page.doc)
|
||||
assert.equal(page.frames().length, 1)
|
||||
})
|
||||
|
||||
test('링크가 여러 개면 각각 생긴다', () => {
|
||||
const page = fakeDoc([link({ 'data-region': '5213000000', 'data-type': 'home' }), link({ 'data-region': '1111000000', 'data-bg': 'dark' }, '종로구 날씨 - 날씨각')])
|
||||
run(page.doc)
|
||||
assert.deepEqual(
|
||||
page.frames().map((f) => f.attrs.src),
|
||||
[`${ORIGIN}/embed/card?region=5213000000&type=home&bg=sky`, `${ORIGIN}/embed/card?region=1111000000&type=side&bg=dark`],
|
||||
)
|
||||
assert.equal(page.frames()[1].attrs.title, '종로구 날씨 - 날씨각')
|
||||
})
|
||||
|
||||
test('날씨각 주소(origin)는 스크립트 주소에서 온다', () => {
|
||||
const page = fakeDoc([link({ 'data-region': '5213000000' })], { scriptSrc: 'https://weather.o2o.kr/embed/widget.js' })
|
||||
run(page.doc)
|
||||
assert.equal(page.frames()[0].attrs.src, 'https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky')
|
||||
})
|
||||
|
||||
test('currentScript 가 없으면 스크립트 태그를 찾아 주소를 얻는다', () => {
|
||||
const page = fakeDoc([link({ 'data-region': '5213000000' })], { current: false })
|
||||
run(page.doc)
|
||||
assert.equal(page.frames()[0].attrs.src, `${ORIGIN}/embed/card?region=5213000000&type=side&bg=sky`)
|
||||
})
|
||||
|
||||
test('문서가 다 읽히기 전에 실행되면 다 읽힌 뒤에도 한 번 더 찾는다', () => {
|
||||
const page = fakeDoc([], { readyState: 'loading' })
|
||||
run(page.doc)
|
||||
// 스크립트보다 아래에 있어 나중에 읽힌 링크
|
||||
const late = link({ 'data-region': '5213000000' })
|
||||
late.parentNode = page.body
|
||||
page.body.children.push(late)
|
||||
page.fire('DOMContentLoaded')
|
||||
assert.equal(page.frames().length, 1)
|
||||
})
|
||||
|
||||
test('옛 브라우저에서도 돌게 ES5 문법만 쓴다', () => {
|
||||
const code = SOURCE.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
|
||||
assert.doesNotMatch(code, /=>|`|\b(?:let|const|class)\s/)
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
// 다른 사이트에 붙이는 날씨 카드의 iframe 주소·붙이는 코드 검증. 실행: frontend 폴더에서 npm test
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { EMBED_HEIGHT, EMBED_MAX_HEIGHT, EMBED_MAX_WIDTH, EMBED_MIN_WIDTH, EMBED_RATIO, embedCode, embedScript, embedSrc } from '../src/lib/embedWidget.ts'
|
||||
|
||||
const ORIGIN = 'https://weather.o2o.kr'
|
||||
|
||||
test('iframe 주소', () => {
|
||||
assert.equal(embedSrc(ORIGIN, '5213000000', 'side', 'sky'), 'https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky')
|
||||
})
|
||||
|
||||
test('모양별 크기', () => {
|
||||
assert.deepEqual(EMBED_HEIGHT, { side: 245, home: 400 })
|
||||
assert.deepEqual(EMBED_MAX_HEIGHT, { side: 320, home: 520 })
|
||||
assert.deepEqual(EMBED_MIN_WIDTH, { side: 220, home: 280 })
|
||||
assert.deepEqual(EMBED_MAX_WIDTH, { side: 440, home: 720 })
|
||||
assert.deepEqual(EMBED_RATIO, { side: '11/8', home: '18/13' })
|
||||
})
|
||||
|
||||
test('폭:높이 비율은 최대 폭 ÷ 최대 높이 (최대 폭에서 최대 높이가 되게)', () => {
|
||||
for (const kind of ['side', 'home']) {
|
||||
const [w, h] = EMBED_RATIO[kind].split('/').map(Number)
|
||||
assert.equal(w * EMBED_MAX_HEIGHT[kind], h * EMBED_MAX_WIDTH[kind], kind)
|
||||
}
|
||||
})
|
||||
|
||||
test('붙이는 코드(상세형): 배경·크기 범위·둥근 모서리·referrerpolicy 가 들어간다', () => {
|
||||
assert.equal(
|
||||
embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind: 'home', bg: 'dark' }),
|
||||
'<iframe src="https://weather.o2o.kr/embed/card?region=5213000000&type=home&bg=dark" title="군산시 날씨 - 날씨각" width="100%" height="400" style="border:0;width:100%;height:auto;aspect-ratio:18/13;min-width:280px;max-width:720px;min-height:400px;max-height:520px;border-radius:28px" loading="lazy" referrerpolicy="origin"></iframe>',
|
||||
)
|
||||
})
|
||||
|
||||
test('붙이는 코드(기본형): 크기 범위·둥근 모서리', () => {
|
||||
assert.equal(
|
||||
embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind: 'side', bg: 'sky' }),
|
||||
'<iframe src="https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky" title="군산시 날씨 - 날씨각" width="100%" height="245" style="border:0;width:100%;height:auto;aspect-ratio:11/8;min-width:220px;max-width:440px;min-height:245px;max-height:320px;border-radius:28px" loading="lazy" referrerpolicy="origin"></iframe>',
|
||||
)
|
||||
})
|
||||
|
||||
test('붙이는 코드: 지역 이름의 따옴표가 속성을 깨지 않는다', () => {
|
||||
assert.ok(embedCode({ origin: ORIGIN, region: '5213000000', regionName: '가"짜', kind: 'side', bg: 'sky' }).includes('title="가"짜 날씨 - 날씨각"'))
|
||||
})
|
||||
|
||||
test('붙이는 코드: 지역 이름의 & < > 도 이스케이프한다', () => {
|
||||
assert.ok(embedCode({ origin: ORIGIN, region: '5213000000', regionName: 'A&B<C>', kind: 'side', bg: 'sky' }).includes('title="A&B<C> 날씨 - 날씨각"'))
|
||||
})
|
||||
|
||||
test('붙이는 코드: 지역 코드는 주소에 맞게 인코딩한다', () => {
|
||||
assert.ok(embedCode({ origin: ORIGIN, region: '52 13&x=1', kind: 'side', bg: 'sky', regionName: '군산시' }).includes('src="https://weather.o2o.kr/embed/card?region=52%2013%26x%3D1&type=side&bg=sky"'))
|
||||
})
|
||||
|
||||
test('스크립트 코드: 지역 페이지 링크 + 스크립트', () => {
|
||||
assert.equal(
|
||||
embedScript({ origin: ORIGIN, region: '5213000000', regionName: '군산시', regionPath: 'jeonbuk/gunsan', kind: 'side', bg: 'sky' }),
|
||||
'<a class="nalssigak-weather" href="https://weather.o2o.kr/today/jeonbuk/gunsan?utm_source=widget&utm_medium=embed&utm_campaign=fallback"\n' +
|
||||
' data-region="5213000000" data-type="side" data-bg="sky">군산시 날씨 - 날씨각</a>\n' +
|
||||
'<script src="https://weather.o2o.kr/embed/widget.js" async></script>',
|
||||
)
|
||||
})
|
||||
|
||||
test('스크립트 코드: 지역 페이지가 없으면 링크는 날씨각 홈', () => {
|
||||
assert.equal(
|
||||
embedScript({ origin: ORIGIN, region: '1111000000', regionName: '어떤구', regionPath: null, kind: 'home', bg: 'dark' }),
|
||||
'<a class="nalssigak-weather" href="https://weather.o2o.kr/?utm_source=widget&utm_medium=embed&utm_campaign=fallback"\n' +
|
||||
' data-region="1111000000" data-type="home" data-bg="dark">어떤구 날씨 - 날씨각</a>\n' +
|
||||
'<script src="https://weather.o2o.kr/embed/widget.js" async></script>',
|
||||
)
|
||||
})
|
||||
|
||||
test('스크립트 코드: 지역 이름이 링크를 깨지 않는다', () => {
|
||||
const code = embedScript({ origin: ORIGIN, region: '5213000000', regionName: '<b>A&"B', regionPath: null, kind: 'side', bg: 'sky' })
|
||||
assert.ok(code.includes('><b>A&"B 날씨 - 날씨각</a>'))
|
||||
assert.ok(!code.includes('<b>'))
|
||||
})
|
||||
@@ -101,6 +101,13 @@ const PAGES: { path: string; title: string; description: string; body: string; c
|
||||
keywords: '날씨 코디, 오늘의 코디, 이번 주 코디, 가을 코디, 날씨 쇼츠, 날씨각',
|
||||
body: '<h1>날씨각 · 날씨 쇼츠</h1><p>이번 주 날씨에 맞춘 20대·30대·40대 코디와 오늘 날씨 이야기를 짧은 영상으로 위아래로 넘겨 볼 수 있어요.</p>',
|
||||
},
|
||||
{
|
||||
path: 'widget',
|
||||
title: '날씨 위젯 · 내 사이트에 날씨 카드 달기 | 날씨각',
|
||||
description: '내 홈페이지·블로그에 우리 동네 오늘 날씨 카드를 달아 보세요. 무료이고 신청 없이 코드만 붙이면 돼요.',
|
||||
keywords: '날씨 위젯, 홈페이지 날씨, 날씨 퍼가기, 날씨 iframe',
|
||||
body: '<h1>날씨각 · 날씨 위젯</h1><p>내 홈페이지나 블로그에 고른 지역의 오늘 날씨 카드를 달 수 있어요. 지금 날씨 점수와 아침·낮·저녁·밤 하늘과 기온을 보여 주고, 카드의 자세히 보기 버튼을 누르면 날씨각에서 더 많은 날씨를 볼 수 있어요.</p><p>무료이고 신청 없이 바로 쓸 수 있어요. 지역을 고르고 코드를 복사해 붙이면 끝이에요.</p><p>붙이는 방법은 스크립트(권장)와 iframe 코드 두 가지예요. 모양은 기본형과 상세형, 배경은 기본형·밝은 바탕용·어두운 바탕용 3가지 가운데 고를 수 있어요.</p>',
|
||||
},
|
||||
{
|
||||
path: 'type',
|
||||
title: '날씨 유형 테스트 · 나는 무슨 날씨일까? | 날씨각',
|
||||
|
||||
Reference in new issue
Block a user