구조: 사장님(solution)과 내부 운영(admin)을 두 앱으로 가른다
최상단을 프로젝트 단위로 평평하게 둔다 — o2o-negosium 과 같은 규약이고, 이 레포만
다르게 갈 이유가 없다. negodata/{backend,front} 가 프로젝트 안에서 f/b 를 가르는 선례,
lps-admin/ 이 백엔드 없이 프론트만 가진 최상단 폴더의 선례다.
backend/ frontend/{admin,site,shared} → solution/{backend,front,site,shared} + admin/
## 왜
내부 라우트(/local-content, /places/:id/seo)의 이름과 화면 코드가 사장님 번들에
그대로 실려 나가고 있었다. UserRole.DEVELOPER 주석의 "고객사에 존재를 노출하지 않는다"를
번들이 깨고 있었다 — 라우트 가드는 화면을 가리지 번들은 못 가린다.
번들을 갈라 확인했다: 사장님 dist 에서 local-content · /places · SeoAudit 이 전부 0건이다.
그 과정에서 두 곳이 더 새고 있었다.
- AppShell 의 NAV 배열이 내부 메뉴를 하드코딩하고 있었다. 앱을 가른 뒤에도 dist 에
local-content 가 남아서 찾았다. 메뉴는 이제 앱이 prop 으로 들고 온다.
- EditorHeader·BuilderPage·LoginPage 가 /places 로 링크하고 있었다. 그 화면이 admin 으로
나갔으니 사장님 앱에서는 404 다. 링크를 걷어내고 LoginPage 기본 도착지는 '/' 로 바꿨다
(앱마다 홈이 다르고 각 라우터의 '/' 가 이미 그걸 안다).
## admin 에 백엔드를 두지 않았다
내부 화면이 부르는 훅이 전부 router/v1/{place,fact,local,validator} 에 이미 있다.
자체 백엔드를 두면 place·fact·link 를 같은 DB 에 대고 두 번 구현하게 된다.
대가는 solution/backend 가 죽으면 admin 도 멈추는 것 — 내부 도구라 감수한다.
## admin 의 `@` 는 solution/front/src 를 가리킨다
내부 화면이 쓰는 API 클라이언트·UI·수집 배선이 solution 에 한 벌만 있고 그 파일들끼리도
`@/...` 로 서로를 부른다. admin 에서 `@` 를 자기 src 로 잡으면 그 참조가 전부 깨진다
(실측 TS2307 14건). 복제하는 길도 있지만 RecollectPanel 주석이 금지한다 —
"수집 경로를 두 벌 만들면 확정 게이트"가 갈라진다.
admin 자기 파일만 `@admin` 이고, 의존 방향은 admin → solution 한 쪽뿐이다.
admin 이 여는 빌더는 다른 오리진이라 절대 URL + 새 탭이다(admin/src/lib/solutionUrl.ts).
react-router Link 로 두면 admin 안에서 라우트를 찾다 404 다.
## 그 밖
- npm 워크스페이스 루트를 레포 루트로 올렸다(admin 이 solution 밖이라).
- docker-compose 를 255→174줄로 줄이고 admin(:3002) 서비스를 넣었다. ADMIN_BIND 기본값은
127.0.0.1 — 0.0.0.0 으로 열면 앱을 가른 의미가 없다.
- 발행 호스트를 프론트 .env 에 따로 적지 않는다. compose 가 루트의 SITE_PUBLIC_HOST 를
VITE_PUBLISH_HOST 로 흘려보낸다 — 두 곳에 적으면 canonical 과 화면 주소가 조용히 갈라진다.
- nginx/site.conf 를 git 에서 빼고 .example 만 남겼다(.env·*.toml 과 같은 규약).
compose 가 bind mount 하므로 클론 직후 복사해야 한다 — 없으면 Docker 가 그 자리에
디렉토리를 만들어 nginx 가 설정 없이 뜬다.
- config.test.toml.example 을 추가했다. 없으면 클론한 사람이 pytest 를 아예 못 돌린다
(conftest import 단계에서 죽는다). 외부 API 키는 전부 빈값이다 —
APP_ENV=test 가 .env 를 안 읽는 이유를 여기서 우회하면 안 된다.
- 경로가 한 칸 깊어져 test_schema_ddl(parents[2]→[3]) 과 test_site_theme 을 고쳤다.
검증: front·admin·site 전부 lint 0 / build 0. 백엔드 514 passed.
남은 4건(test_build_publish 3 · test_snapshot 1)은 이 변경 전부터 실패하던 것으로,
손대지 않은 메인 체크아웃에서 같은 4건이 같게 실패하는 것을 확인했다.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019uYhHQdssRubirPirrdJJC
This commit is contained in:
1 parent
139d460839
commit
9d25ed613e
714 files changed
+782
-440
No files matched your search
@@ -0,0 +1,297 @@
|
||||
import {
|
||||
LinkChannel,
|
||||
PlaceCategory,
|
||||
factText,
|
||||
sanitizeUnits,
|
||||
selectPublishable,
|
||||
selectPublishableFaqs,
|
||||
type ChannelLink,
|
||||
type FactEntry,
|
||||
type MediaItem,
|
||||
type SitePayload,
|
||||
type UnitInfo,
|
||||
} from '@o2o/shared';
|
||||
import {UNIT_SPEC} from '@/seo/jsonld';
|
||||
|
||||
/**
|
||||
* payload → 화면이 바로 쓰는 모양.
|
||||
*
|
||||
* 컴포넌트가 fact 배열을 직접 뒤지지 않게 한 층 둔다. 여기 한 곳에서만
|
||||
* selectPublishable() 을 통과시키므로, 컴포넌트가 실수로 미검증 값을 그릴 수가 없다.
|
||||
*/
|
||||
|
||||
export interface InfoRow {
|
||||
label: string;
|
||||
value: string;
|
||||
/** 부가 설명. 출처가 아니라 사장님이 붙인 보충 문구. */
|
||||
note?: string;
|
||||
}
|
||||
|
||||
/** 사업장 단위 이용 정보 표. 확인된 것만 들어간다. */
|
||||
export function essentialRows(payload: SitePayload): InfoRow[] {
|
||||
return selectPublishable(payload.facts)
|
||||
.filter((fact) => fact.scope === 'place')
|
||||
.map((fact) => ({
|
||||
label: fact.label,
|
||||
value: displayValue(fact, payload.facts),
|
||||
}))
|
||||
.filter((row) => row.value !== '');
|
||||
}
|
||||
|
||||
function displayValue(fact: FactEntry, all: FactEntry[]): string {
|
||||
const text = factText(all, fact.key);
|
||||
if (!text) return '';
|
||||
if (fact.type !== 'bool') return text;
|
||||
if (text === 'true') return '가능';
|
||||
if (text === 'false') return '불가';
|
||||
return text;
|
||||
}
|
||||
|
||||
export interface UnitView {
|
||||
unitId: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
intro?: string;
|
||||
/** 스펙 칩 — 인원 · 침대 · 면적처럼 한눈에 보는 값. */
|
||||
chips: {label: string; value: string}[];
|
||||
rows: InfoRow[];
|
||||
images: MediaItem[];
|
||||
priceText?: string;
|
||||
href: string;
|
||||
}
|
||||
|
||||
export function unitViews(payload: SitePayload): UnitView[] {
|
||||
const spec = UNIT_SPEC[payload.place.category];
|
||||
const mediaById = new Map(payload.media.map((m) => [m.mediaId, m]));
|
||||
|
||||
return sanitizeUnits(payload.units).map((unit) => {
|
||||
const intro = factText(unit.facts, 'room_intro') ?? factText(unit.facts, 'description');
|
||||
const chipKeys =
|
||||
payload.place.category === PlaceCategory.LODGING
|
||||
? ['max_capacity', 'bed_type', 'room_size']
|
||||
: ['price', 'volume', 'origin'];
|
||||
|
||||
return {
|
||||
unitId: unit.unitId,
|
||||
slug: unit.slug,
|
||||
name: unit.name,
|
||||
intro,
|
||||
chips: chipKeys
|
||||
.map((key) => {
|
||||
const value = factText(unit.facts, key);
|
||||
const label = unit.facts.find((f) => f.key === key)?.label ?? key;
|
||||
return value ? {label, value} : null;
|
||||
})
|
||||
.filter((chip): chip is {label: string; value: string} => chip !== null),
|
||||
rows: unit.facts
|
||||
.map((fact) => ({label: fact.label, value: displayValue(fact, unit.facts)}))
|
||||
.filter((row) => row.value !== ''),
|
||||
images: unit.mediaIds
|
||||
.map((id) => mediaById.get(id))
|
||||
.filter((m): m is MediaItem => Boolean(m?.alt?.trim())),
|
||||
priceText: unitPriceText(unit),
|
||||
href: `/${spec.path}/${unit.slug}`,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function unitPriceText(unit: UnitInfo): string | undefined {
|
||||
const weekday = Number(factText(unit.facts, 'weekday_price')?.replace(/[^0-9]/g, ''));
|
||||
const price = Number(factText(unit.facts, 'price')?.replace(/[^0-9]/g, ''));
|
||||
const base = Number.isFinite(weekday) && weekday > 0 ? weekday : price;
|
||||
if (!Number.isFinite(base) || base <= 0) return undefined;
|
||||
return `${base.toLocaleString('ko-KR')}원부터`;
|
||||
}
|
||||
|
||||
/** 갤러리에 낼 이미지 — 대체 텍스트 없는 것은 뺀다(검색·낭독기 모두 못 읽는다). */
|
||||
export function galleryImages(payload: SitePayload): MediaItem[] {
|
||||
return payload.media.filter((m) => m.alt?.trim() && !m.unitId);
|
||||
}
|
||||
|
||||
export function faqList(payload: SitePayload) {
|
||||
return selectPublishableFaqs(payload.faqs);
|
||||
}
|
||||
|
||||
/** 켜져 있는 섹션인지. 순서도 payload 가 정한다. */
|
||||
export function enabledSections(payload: SitePayload) {
|
||||
return payload.theme.sections.filter((section) => section.enabled);
|
||||
}
|
||||
|
||||
export function isSectionEnabled(payload: SitePayload, id: string): boolean {
|
||||
return payload.theme.sections.find((section) => section.id === id)?.enabled ?? false;
|
||||
}
|
||||
|
||||
export function unitSpec(payload: SitePayload) {
|
||||
return UNIT_SPEC[payload.place.category];
|
||||
}
|
||||
|
||||
/**
|
||||
* 섹션 제목 — 사장님이 [섹션] 패널에서 붙인 이름(`theme.sections[].name`)을 그대로 쓴다.
|
||||
*
|
||||
* ★ 왜 필요한가
|
||||
* 지금까지 발행본 소제목은 컴포넌트에 박힌 문자열이었다. 사장님이 "객실 안내"를
|
||||
* "우리 방 소개"로 바꿔도 에디터 캔버스만 바뀌고 발행본은 옛 문구로 나갔다 —
|
||||
* 사장님 입장에서는 고친 게 반영이 안 된 것이고, 실제로 반영이 안 된 게 맞다.
|
||||
*
|
||||
* ★ **모든 섹션이 이걸 쓰는 건 아니다.** 기준은 하나다 — 에디터 캔버스가 그 섹션에서
|
||||
* 무엇을 제목으로 쓰는가. 두 화면이 같아야 하므로 발행본은 에디터를 따라간다.
|
||||
*
|
||||
* 이걸 쓰는 섹션 rules · booking · inquiry · space · exhibition · rooms/menu/programs
|
||||
* (에디터: `title={section.name}`)
|
||||
* 쓰지 않는 섹션 intro · info · photos · map · local · faq
|
||||
* (에디터가 자체 제목을 쓴다: "공간 갤러리", "오시는 길", `${상호} 소개` …)
|
||||
*
|
||||
* 한때 발행본에서 여섯 섹션 전부에 이걸 걸었다가 소개 제목이 "조이모텔 소개" 에서
|
||||
* "소개" 로 짧아졌다. `theme.sections[].name` 은 사장님이 붙인 이름이기도 하지만,
|
||||
* 아직 아무것도 안 바꿨으면 서버 기본표(_DEFAULT_THEME)의 짧은 목록 라벨이다 —
|
||||
* 그 라벨은 좌측 패널의 navigation 용이지 <h2> 용이 아니다.
|
||||
*
|
||||
* ★ 폴백을 두는 이유
|
||||
* name 이 비어 있는 payload(옛 버전·손으로 만든 fixture)에서 제목 없는 <h2> 가
|
||||
* 나가면 문서 구조가 무너지고 검색·낭독기가 섹션을 못 읽는다. 제목은 반드시 채운다.
|
||||
*/
|
||||
export function sectionName(payload: SitePayload, id: string, fallback: string): string {
|
||||
const name = payload.theme.sections.find((section) => section.id === id)?.name?.trim();
|
||||
return name ? name : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* key 목록 순서대로 확인된 place fact 를 표 행으로.
|
||||
*
|
||||
* ★ 순서가 곧 화면 순서다. 값이 없거나 미검증인 key 는 조용히 빠진다 —
|
||||
* "확인 중"이라는 빈 줄을 그리면 손님은 그걸 규정으로 읽는다.
|
||||
*/
|
||||
function placeRowsByKeys(payload: SitePayload, keys: readonly string[]): InfoRow[] {
|
||||
const map = new Map(
|
||||
selectPublishable(payload.facts)
|
||||
.filter((fact) => fact.scope === 'place')
|
||||
.map((fact) => [fact.key, fact] as const),
|
||||
);
|
||||
|
||||
return keys
|
||||
.map((key) => map.get(key))
|
||||
.filter((fact): fact is FactEntry => fact !== undefined)
|
||||
.map((fact) => ({label: fact.label, value: displayValue(fact, payload.facts)}))
|
||||
.filter((row) => row.value !== '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 이용 규정으로 읽히는 fact key.
|
||||
*
|
||||
* ★ 관리자 캔버스의 `builder/canvas/variants/common.ts` RULE_FIELD_IDS 와 같은 목록이다.
|
||||
* 에디터에서 규정으로 보인 항목이 발행본에서 다른 항목이 되면 사장님은 어느 쪽을
|
||||
* 믿어야 할지 모른다. 목록이 바뀌면 양쪽을 같이 고친다.
|
||||
* ★ 여기 없는 규정은 만들어 내지 않는다. 업종 스키마(lodging.json)에 있는 key 만 적는다.
|
||||
*/
|
||||
const RULE_FACT_KEYS = [
|
||||
'check_in_time',
|
||||
'check_out_time',
|
||||
'cancel_policy',
|
||||
'cooking_allowed',
|
||||
'pet_allowed',
|
||||
'smoking',
|
||||
'extra_person_fee',
|
||||
] as const;
|
||||
|
||||
/** 이용 규정 줄. 확인된 fact 에서만 만든다 — 없으면 빈 목록이고 섹션 자체가 안 나간다. */
|
||||
export function ruleRows(payload: SitePayload): InfoRow[] {
|
||||
return placeRowsByKeys(payload, RULE_FACT_KEYS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약 안내에 실을 fact.
|
||||
*
|
||||
* 숙박에는 없고(예약은 채널이 받는다) 음식점·관광체험 스키마에만 있는 key 다.
|
||||
* 값이 없는 업종에서는 그냥 빠진다.
|
||||
*/
|
||||
const BOOKING_FACT_KEYS = ['reservation_required', 'reservation_channel'] as const;
|
||||
|
||||
export function bookingRows(payload: SitePayload): InfoRow[] {
|
||||
return placeRowsByKeys(payload, BOOKING_FACT_KEYS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 공간 안내에 실을 fact — "자리가 어떻게 생겼나"에 답하는 것만.
|
||||
*
|
||||
* ★ 주차·와이파이 같은 편의시설은 넣지 않는다. 그건 이용 정보(info) 표가 이미 낸다.
|
||||
*/
|
||||
const SPACE_FACT_KEYS = [
|
||||
'seat_count',
|
||||
'terrace',
|
||||
'room_available',
|
||||
'group_seat_max',
|
||||
'power_outlet',
|
||||
'study_allowed',
|
||||
'wheelchair_accessible',
|
||||
] as const;
|
||||
|
||||
export function spaceRows(payload: SitePayload): InfoRow[] {
|
||||
return placeRowsByKeys(payload, SPACE_FACT_KEYS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 관람 안내에 실을 fact — 관광체험 스키마(tour_activity.json)의 관람 관련 key.
|
||||
*
|
||||
* ★ 준비물·안전 유의사항은 뺐다. 그건 "관람 안내"가 아니라 체험 전 주의사항이고,
|
||||
* 이용 정보(info) 표에 이미 나간다.
|
||||
*/
|
||||
const EXHIBITION_FACT_KEYS = [
|
||||
'operating_hours',
|
||||
'session_times',
|
||||
'closed_days',
|
||||
'age_limit',
|
||||
'guide_language',
|
||||
] as const;
|
||||
|
||||
export function exhibitionRows(payload: SitePayload): InfoRow[] {
|
||||
return placeRowsByKeys(payload, EXHIBITION_FACT_KEYS);
|
||||
}
|
||||
|
||||
/** 채널 코드 → 사람이 읽는 이름. link.title 이 있으면 그쪽이 우선이다. */
|
||||
export const CHANNEL_LABEL: Record<number, string> = {
|
||||
[LinkChannel.YANOLJA]: '야놀자',
|
||||
[LinkChannel.GOODCHOICE]: '여기어때',
|
||||
[LinkChannel.NAVER_PLACE]: '네이버 플레이스',
|
||||
[LinkChannel.INSTAGRAM]: '인스타그램',
|
||||
[LinkChannel.OFFICIAL_SITE]: '공식 사이트',
|
||||
[LinkChannel.BLOG]: '블로그',
|
||||
[LinkChannel.ETC]: '채널',
|
||||
};
|
||||
|
||||
export function channelLabel(link: ChannelLink): string {
|
||||
return link.title ?? CHANNEL_LABEL[link.channel] ?? '채널';
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약을 실제로 받는 채널.
|
||||
*
|
||||
* ★ 블로그·인스타그램은 뺀다. 눌러도 예약 화면이 안 나오는 링크를 "예약하기" 자리에
|
||||
* 두면 손님이 예약한 줄 알고 안 온다. 공식 사이트도 뺀다 — 지금 보고 있는 이 사이트가
|
||||
* 그 자리라, 자기 자신으로 돌려보내는 버튼이 된다.
|
||||
*/
|
||||
const BOOKING_CHANNELS: readonly number[] = [
|
||||
LinkChannel.YANOLJA,
|
||||
LinkChannel.GOODCHOICE,
|
||||
LinkChannel.NAVER_PLACE,
|
||||
];
|
||||
|
||||
/**
|
||||
* 문의를 실제로 받을 수 있는 채널 — 네이버 톡톡·인스타 DM 처럼 말을 걸 수 있는 곳만.
|
||||
*
|
||||
* ★ 블로그·공식 사이트·기타(ETC)는 뺀다. 읽기만 되는 링크를 "문의" 버튼으로 두면
|
||||
* 손님이 남긴 말이 아무 데도 도착하지 않는다.
|
||||
*/
|
||||
const CONTACT_CHANNELS: readonly number[] = [LinkChannel.NAVER_PLACE, LinkChannel.INSTAGRAM];
|
||||
|
||||
/** 확정된 링크만. 확정 전 URL 은 동명 업소일 수 있다(sanitizePayloadForPublish 와 같은 규칙). */
|
||||
function confirmedLinks(payload: SitePayload, channels: readonly number[]): ChannelLink[] {
|
||||
return payload.links.filter((link) => link.confirmed && channels.includes(link.channel));
|
||||
}
|
||||
|
||||
export function bookingLinks(payload: SitePayload): ChannelLink[] {
|
||||
return confirmedLinks(payload, BOOKING_CHANNELS);
|
||||
}
|
||||
|
||||
export function contactLinks(payload: SitePayload): ChannelLink[] {
|
||||
return confirmedLinks(payload, CONTACT_CHANNELS);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/** "280000" → "280,000원". 숫자가 아니면 원문 그대로 돌려준다. */
|
||||
export function formatWon(value: string | number | null | undefined): string {
|
||||
if (value == null || value === '') return '';
|
||||
const num = typeof value === 'string' ? Number(value.replace(/,/g, '')) : value;
|
||||
if (!Number.isFinite(num)) return String(value);
|
||||
return `${num.toLocaleString('ko-KR')}원`;
|
||||
}
|
||||
|
||||
/** ISO → "2026년 8월 27일". 화면에 "언제 기준"을 찍는 데 쓴다. */
|
||||
export function formatKoreanDate(iso: string | null | undefined): string {
|
||||
if (!iso) return '';
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return `${date.getFullYear()}년 ${date.getMonth() + 1}월 ${date.getDate()}일`;
|
||||
}
|
||||
|
||||
/** 네이버 검색으로 보내는 링크. 우리가 지어낸 URL 을 링크하지 않기 위한 통로. */
|
||||
export function naverSearchUrl(query: string): string {
|
||||
return `https://search.naver.com/search.naver?query=${encodeURIComponent(query)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 카카오맵 **길찾기**. 좌표가 있으면 목적지가 찍힌 길찾기 화면으로 바로 열린다.
|
||||
*
|
||||
* ★ 좌표가 없으면 검색으로 떨어진다 — 없는 좌표를 지어내면 엉뚱한 곳으로 안내하게 되고,
|
||||
* 그건 검색 결과를 한 번 더 누르게 하는 것보다 훨씬 나쁘다.
|
||||
*/
|
||||
export function kakaoDirectionsUrl(name: string, lat?: number, lng?: number): string {
|
||||
if (lat == null || lng == null) {
|
||||
return `https://map.kakao.com/link/search/${encodeURIComponent(name)}`;
|
||||
}
|
||||
return `https://map.kakao.com/link/to/${encodeURIComponent(name)},${lat},${lng}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 네이버지도 **길찾기**. v5 주소 형식은 `/p/directions/{출발}/{도착}/{경유}/{수단}` 이고,
|
||||
* 각 지점은 `경도,위도,이름` 이다. 출발지를 `-` 로 비워 두면 네이버가 방문자의 현재 위치를
|
||||
* 채운다 — 우리가 방문자 위치를 알 필요도, 물어볼 필요도 없다.
|
||||
*
|
||||
* ★ 수단을 대중교통(transit)으로 고정하는 이유: 차로 오는 사람은 화면에서 한 번만 바꾸면 되지만,
|
||||
* 대중교통으로 오는 사람에게는 이 화면이 곧 답이다. 기본값은 덜 아는 쪽에 맞춘다.
|
||||
*/
|
||||
export function naverDirectionsUrl(name: string, lat?: number, lng?: number): string {
|
||||
if (lat == null || lng == null) {
|
||||
return `https://map.naver.com/p/search/${encodeURIComponent(name)}`;
|
||||
}
|
||||
return `https://map.naver.com/p/directions/-/${lng},${lat},${encodeURIComponent(name)}/-/transit`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 지도 그림(OpenStreetMap 임베드) 주소.
|
||||
*
|
||||
* ★ 왜 카카오·네이버 지도가 아닌가
|
||||
* 둘 다 지도를 그리려면 키가 필요하다(카카오는 JS 키, 네이버 정적지도는 NCP 헤더 인증).
|
||||
* 그런데 이 렌더러는 **런타임 환경변수를 쓰지 않는다**(site/.env.example) — payload 하나로
|
||||
* 같은 HTML 이 재현되어야 하기 때문이다. 키를 읽는 순간 그 규칙이 깨진다.
|
||||
* OSM 임베드는 키가 없고 좌표만으로 만들어져 payload 만으로 재현된다.
|
||||
*
|
||||
* ★ 지도는 사람이 보는 것이고, 기계가 읽을 위치 정보는 이미 따로 나간다
|
||||
* (JSON-LD 의 geo·PostalAddress, 화면의 <address>). 그래서 지도가 iframe 이어도
|
||||
* AEO 는 손해 보지 않는다.
|
||||
*/
|
||||
export function osmEmbedUrl(lat: number, lng: number, aspect = 16 / 9, halfLat = 0.0022): string {
|
||||
// ★ bbox 의 종횡비를 iframe 과 맞춰야 한다. OSM 임베드는 bbox 모양대로 지도 캔버스를 잡고
|
||||
// 남는 자리를 흰색으로 둔다 — 안 맞추면 넓은 프레임 왼쪽 3분의 1만 지도가 그려진다(실측).
|
||||
// ★ 경도는 cos(위도) 만큼 좁다. 이 보정을 빼면 한국(위도 37도)에서 가로로 눌린 지도가 나온다.
|
||||
const cos = Math.max(Math.cos((lat * Math.PI) / 180), 0.01);
|
||||
const halfLng = (aspect * halfLat) / cos;
|
||||
const bbox = [lng - halfLng, lat - halfLat, lng + halfLng, lat + halfLat]
|
||||
.map((n) => n.toFixed(6))
|
||||
.join(',');
|
||||
return `https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=mapnik&marker=${lat},${lng}`;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {createContext, useContext, type ReactNode} from 'react';
|
||||
import type {SitePayload} from '@o2o/shared';
|
||||
|
||||
/**
|
||||
* payload 를 트리 전체에 흘린다.
|
||||
*
|
||||
* ★ 컴포넌트가 데이터를 *가져오지* 않는다. 발행 사이트에는 API 호출이 없다 —
|
||||
* 빌드 시점에 확정된 사실만 그린다. 그래서 서버 렌더와 브라우저 렌더가 항상 같고,
|
||||
* 크롤러가 보는 HTML 과 사람이 보는 화면이 어긋날 수 없다.
|
||||
*/
|
||||
const SiteContext = createContext<SitePayload | null>(null);
|
||||
|
||||
export function SiteProvider({payload, children}: {payload: SitePayload; children: ReactNode}) {
|
||||
return <SiteContext.Provider value={payload}>{children}</SiteContext.Provider>;
|
||||
}
|
||||
|
||||
export function useSite(): SitePayload {
|
||||
const payload = useContext(SiteContext);
|
||||
if (!payload) {
|
||||
// payload 없이 렌더되면 조용히 빈 화면이 나가는 게 최악이다 — 빌드를 실패시킨다.
|
||||
throw new Error('SiteProvider 밖에서 useSite() 를 불렀습니다. payload 없이는 렌더할 수 없습니다.');
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import {useEffect, useState} from 'react';
|
||||
|
||||
/**
|
||||
* 화면에 보이는 섹션의 id — 한 장짜리 사이트의 내비게이션 활성 표시용.
|
||||
*
|
||||
* ★ 라우터를 걷어내면서 `useLocation` 으로 하던 활성 표시가 사라졌다. 한 장이 되면
|
||||
* 하단 탭이 유일한 내비게이션이라, 지금 어디인지 안 보이면 이전보다 나빠진다.
|
||||
*
|
||||
* ★ rootMargin 으로 판정선을 화면 위쪽 35% 지점에 둔다. 가운데로 두면 짧은 섹션이
|
||||
* 영영 활성화되지 않고, 위쪽 0 으로 두면 스크롤 도중 두 섹션이 번갈아 깜빡인다.
|
||||
*
|
||||
* ★ 배열을 문자열 키로 바꿔 의존성에 넣는다. `ids` 를 그대로 넣으면 부모가 매 렌더마다
|
||||
* 새 배열을 만들어 넘기므로 옵저버가 계속 재생성된다.
|
||||
*/
|
||||
export function useActiveSection(ids: string[]): string | null {
|
||||
const key = ids.join('|');
|
||||
const [active, setActive] = useState<string | null>(ids[0] ?? null);
|
||||
|
||||
useEffect(() => {
|
||||
const targets = key
|
||||
.split('|')
|
||||
.map((id) => document.getElementById(id))
|
||||
.filter((el): el is HTMLElement => el !== null);
|
||||
if (targets.length === 0) return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
const visible = entries
|
||||
.filter((entry) => entry.isIntersecting)
|
||||
.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
|
||||
if (visible) setActive(visible.target.id);
|
||||
},
|
||||
{rootMargin: '-35% 0px -55% 0px'},
|
||||
);
|
||||
|
||||
for (const target of targets) observer.observe(target);
|
||||
return () => observer.disconnect();
|
||||
}, [key]);
|
||||
|
||||
return active;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import {useEffect, useState} from 'react';
|
||||
import type {WeatherSnapshot} from '@o2o/shared';
|
||||
|
||||
export interface LiveWeather extends WeatherSnapshot {
|
||||
stale?: boolean;
|
||||
}
|
||||
|
||||
function condition(code: number): string {
|
||||
if (code === 0) return '맑음';
|
||||
if (code >= 1 && code <= 3) return '구름많음';
|
||||
if (code >= 50 && code <= 69) return '비';
|
||||
if (code >= 70 && code <= 79) return '눈';
|
||||
return '흐림';
|
||||
}
|
||||
|
||||
/** 프리렌더 스냅샷으로 시작하고, 하이드레이션이 끝난 뒤에만 최신 캐시를 반영한다. */
|
||||
export function useLiveWeather({
|
||||
initial,
|
||||
regionCode,
|
||||
latitude,
|
||||
longitude,
|
||||
}: {
|
||||
initial?: WeatherSnapshot;
|
||||
regionCode?: string;
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
}): LiveWeather | undefined {
|
||||
const [weather, setWeather] = useState<LiveWeather | undefined>(initial);
|
||||
|
||||
useEffect(() => {
|
||||
if (!regionCode || latitude == null || longitude == null) return;
|
||||
const controller = new AbortController();
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9800';
|
||||
const query = new URLSearchParams({
|
||||
region_code: regionCode!,
|
||||
latitude: String(latitude),
|
||||
longitude: String(longitude),
|
||||
});
|
||||
const response = await fetch(`${baseUrl}/v1/local/weather?${query}`, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) return;
|
||||
const body = await response.json();
|
||||
if (!body?.result?.success || !body.weather) return;
|
||||
setWeather((previous) => ({
|
||||
temperature: Number(body.weather.temperature),
|
||||
condition: condition(Number(body.weather.weather_code)),
|
||||
note: previous?.note,
|
||||
observedAt: body.weather.observed_at,
|
||||
stale: Boolean(body.stale),
|
||||
}));
|
||||
} catch {
|
||||
// 정적 payload의 날씨를 유지한다. 날씨 장애가 사이트 렌더를 깨면 안 된다.
|
||||
}
|
||||
}
|
||||
|
||||
void refresh();
|
||||
const timer = window.setInterval(() => void refresh(), 10 * 60 * 1000);
|
||||
return () => {
|
||||
controller.abort();
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [latitude, longitude, regionCode]);
|
||||
|
||||
return weather;
|
||||
}
|
||||
Reference in new issue
Block a user