v7.0.0 release

This commit is contained in:
HeuJung committed 2026-07-01 10:30:32 +09:00
1 parent 0e7fa04b03
commit c4ea9a6cd1
3582 files changed
+626189 -160151

No files matched your search

@@ -1,3 +1,4 @@
// e2e:allow편집기 passthrough 결함#2 수정(admin 동기, data-editor-*/id 를 시각적 루트 Div 로 라우팅). 단위 회귀는 FileInput.test.tsx passthrough describe.
import React, { forwardRef, useRef, useCallback, useState } from 'react';
import { Div } from './Div';
import { Span } from './Span';
@@ -40,6 +41,20 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
const inputRef = (ref as React.RefObject<HTMLInputElement>) || internalRef;
const [fileName, setFileName] = useState<string>('');
// 레이아웃 편집기 식별 표식(data-editor-*) 과 DOM id 는 시각적 루트(<Div>)에 부착해야
// 캔버스에서 선택/편집이 닿는다. basic 컴포넌트라 DynamicRenderer 가 개별 data-editor-*
// 키를 props 로 주입하는데, 숨겨진 <Input className="hidden"> 는 0×0 이라 식별 표식이 닿아도
// 선택 불가. 식별/표식 키만 분리해 루트로 보낸다.
const rootEditorProps: Record<string, unknown> = {};
const inputProps: Record<string, unknown> = {};
Object.entries(props as Record<string, unknown>).forEach(([key, val]) => {
if (key.startsWith('data-editor-') || key === 'id' || key === 'onMouseMove' || key === 'onMouseLeave') {
rootEditorProps[key] = val;
} else {
inputProps[key] = val;
}
});
const handleClick = useCallback(() => {
if (!disabled && inputRef.current) {
inputRef.current.click();
@@ -81,7 +96,7 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
}, [onChange, inputRef]);
return (
<Div className={`flex items-center gap-2 ${className}`}>
<Div className={`flex items-center gap-2 ${className}`} {...rootEditorProps}>
<Input
ref={inputRef}
type="file"
@@ -89,7 +104,7 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
onChange={handleChange as any}
disabled={disabled}
className="hidden"
{...props}
{...inputProps}
/>
<Button
type="button"
@@ -320,8 +320,22 @@ export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
// HTML 표준 속성이 아닌 것들을 필터링 (타입 안전성 개선)
const { loadingactions, formdata, ...validProps } = props as typeof props & NonStandardProps;
// 레이아웃 편집기 표식/핸들러(data-editor-*, onMouseMove/Leave 등)는 시각적
// 루트(wrapper div)에 부착해야 캔버스 선택/드래그가 컴포넌트 전체를 잡는다.
// 내부 input 에만 spread 하면 선택 박스가 input 으로 한정되고 error/검증/토글이
// 선택 영역 밖이 된다.
const editorRootProps: Record<string, unknown> = {};
const inputRestProps: Record<string, unknown> = {};
for (const [k, v] of Object.entries(validProps as Record<string, unknown>)) {
if (k.startsWith('data-editor-') || k === 'onMouseMove' || k === 'onMouseLeave') {
editorRootProps[k] = v;
} else {
inputRestProps[k] = v;
}
}
return (
<div className={`relative ${wrapperClassName}`}>
<div className={`relative ${wrapperClassName}`} {...editorRootProps}>
{/* 입력 필드 wrapper */}
<div className="relative">
<input
@@ -334,7 +348,7 @@ export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
onKeyDown={handleKeyEvent}
onKeyUp={handleKeyEvent}
disabled={disabled}
{...validProps}
{...inputRestProps}
/>
{/* 비밀번호 보기/숨기기 버튼 */}
@@ -1,3 +1,4 @@
// e2e:allow커스텀 드롭다운 루트 props spread 타입 안전 캐스팅(admin 동기). 단위 회귀는 Select.test.tsx.
import React, { useMemo, useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Div } from './Div';
@@ -28,6 +29,12 @@ export interface SelectProps extends Omit<React.SelectHTMLAttributes<HTMLSelectE
searchable?: boolean;
/** 검색 input placeholder */
searchPlaceholder?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용). Select 는 커스텀 드롭다운 루트에
* 개별 data-editor-* 키를 spread 해야 선택/편집이 닿는다(커스텀 루트
* passthrough). basic 컴포넌트라 `{...props}` 로 DOM 표준 속성(id 등)도 함께 흐른다.
*/
editorAttrs?: Record<string, unknown>;
}
/**
@@ -67,6 +74,7 @@ export const Select: React.FC<SelectProps> = ({
disabled,
searchable = false,
searchPlaceholder,
editorAttrs,
...props
}) => {
const [isOpen, setIsOpen] = useState(false);
@@ -237,6 +245,7 @@ export const Select: React.FC<SelectProps> = ({
value={value}
onChange={onChange as React.ChangeEventHandler<HTMLSelectElement>}
disabled={disabled}
{...editorAttrs}
{...props}
>
{children}
@@ -252,8 +261,13 @@ export const Select: React.FC<SelectProps> = ({
? `${className}${hasTextColor ? '' : ' text-gray-700 dark:text-gray-200'}`
: `w-full px-4 py-2.5 bg-gray-100 dark:bg-gray-700 border-0 rounded-xl text-gray-700 dark:text-gray-200 font-medium focus:ring-2 focus:ring-blue-500 focus:outline-none ${className}`;
// props 는 SelectHTMLAttributes 기반이라 Div(HTMLDivElement) 에 직접 spread 시 타입 불일치.
// 런타임 동작(편집기 data-editor-* / id 등 DOM 표준 속성 passthrough)은 동일하므로
// DOM-safe 레코드로 캐스팅해 커스텀 드롭다운 루트에 전달한다.
const rootDomProps = { ...editorAttrs, ...props } as Record<string, unknown>;
return (
<Div ref={containerRef} className="relative">
<Div ref={containerRef} className="relative" {...rootDomProps}>
<Button
ref={buttonRef}
type="button"
@@ -0,0 +1,48 @@
import { describe, it, expect } from 'vitest';
import { render } from '@testing-library/react';
import { FileInput } from '../FileInput';
describe('FileInput 컴포넌트 (sirsoft-basic)', () => {
// ========================================
// 레이아웃 편집기 passthrough
// ========================================
// 편집 모드에서 basic 컴포넌트에 주입되는 data-editor-* / id 는 시각적 루트(<div>)에
// 부착되어야 한다. 숨겨진 <input class="hidden"> (0×0) 에 부착되면 캔버스에서 선택 불가.
describe('편집기 passthrough (data-editor-* / id → 시각적 루트 <div>)', () => {
it('data-editor-* 표식이 숨겨진 input 이 아닌 루트 div 에 부착된다', () => {
const { container } = render(
<FileInput
data-editor-name="FileInput"
data-editor-path="1.children.0"
id="fi-root-id"
/>
);
const root = container.querySelector('[data-editor-name="FileInput"]') as HTMLElement;
expect(root).toBeTruthy();
expect(root.tagName.toLowerCase()).toBe('div');
expect(root.getAttribute('data-editor-path')).toBe('1.children.0');
expect(root.getAttribute('id')).toBe('fi-root-id');
expect(root.querySelector('button')).toBeTruthy();
});
it('숨겨진 file input 에는 편집 표식이 없다', () => {
const { container } = render(
<FileInput data-editor-name="FileInput" data-editor-path="2.children.1" id="fi-id" />
);
const hiddenInput = container.querySelector('input[type="file"]') as HTMLElement;
expect(hiddenInput).toBeTruthy();
expect(hiddenInput.getAttribute('data-editor-name')).toBeNull();
expect(hiddenInput.getAttribute('data-editor-path')).toBeNull();
expect(hiddenInput.getAttribute('id')).toBeNull();
});
it('기능 prop(name 등)은 file input 에 그대로 전달된다', () => {
const { container } = render(
<FileInput name="upload_field" data-editor-name="FileInput" />
);
const hiddenInput = container.querySelector('input[type="file"]') as HTMLInputElement;
expect(hiddenInput.getAttribute('name')).toBe('upload_field');
});
});
});
@@ -431,4 +431,49 @@ describe('PasswordInput 컴포넌트', () => {
expect(screen.getByTestId('icon-triangle-exclamation')).toBeInTheDocument();
});
});
// 레이아웃 편집기 표식(data-editor-*)은 내부 input 이 아니라
// 시각적 루트(wrapper div)에 부착되어야 캔버스 선택/드래그가 컴포넌트 전체를 잡는다.
describe('레이아웃 편집기 표식 부착 위치', () => {
it('data-editor-* / onMouseMove 는 wrapper 루트 div 에 부착', () => {
const onMouseMove = vi.fn();
const { container } = render(
<PasswordInput
wrapperClassName="vpw-root"
{...({
'data-editor-id': 'auto_PW_1',
'data-editor-name': 'PasswordInput',
'data-editor-path': '0.children.1',
onMouseMove,
} as Record<string, unknown>)}
/>
);
// 루트 div 가 표식을 가져야 함
const root = container.firstElementChild as HTMLElement;
expect(root.tagName).toBe('DIV');
expect(root).toHaveClass('vpw-root');
expect(root.getAttribute('data-editor-id')).toBe('auto_PW_1');
expect(root.getAttribute('data-editor-name')).toBe('PasswordInput');
expect(root.getAttribute('data-editor-path')).toBe('0.children.1');
// 내부 input 에는 data-editor-* 가 없어야 함 (루트로만 흘러야 함)
const input = container.querySelector('input') as HTMLElement;
expect(input.getAttribute('data-editor-path')).toBeNull();
expect(input.getAttribute('data-editor-id')).toBeNull();
});
it('일반 input 속성(name/placeholder)은 내부 input 에 그대로 전달', () => {
const { container } = render(
<PasswordInput
name="user_password"
placeholder="비밀번호 입력"
{...({ 'data-editor-name': 'PasswordInput' } as Record<string, unknown>)}
/>
);
const input = container.querySelector('input') as HTMLInputElement;
expect(input.getAttribute('name')).toBe('user_password');
expect(input.getAttribute('placeholder')).toBe('비밀번호 입력');
// 편집기 표식은 input 에 누출되지 않음
expect(input.getAttribute('data-editor-name')).toBeNull();
});
});
});
@@ -1,3 +1,4 @@
// e2e:allow 편집기 ComponentRegistry 등록 정합(basic Header/Footer export 제거 — composite 와 이름 충돌 해소, SlotContainer 번들 포함). 편집기 캔버스 렌더는 Chrome MCP 라이브 실측 + Vitest(headerEditorSpecAndCurrencySlot/HeaderPropRender)로 검증. 사용자 사이트 런타임 무변경.
/**
* 기본 HTML 매핑 컴포넌트 Export
*
@@ -38,8 +39,10 @@ export { Section, type SectionProps } from './Section';
export { Svg, type SvgProps } from './Svg';
export { Icon, type IconProps } from './Icon';
export { Code, type CodeProps } from './Code';
export { Footer, type FooterProps } from './Footer';
export { Header, type HeaderProps } from './Header';
// basic Header/Footer(HTML <header>/<footer> 래퍼)는 레이아웃 사용처 0이며 composite
// Header/Footer 와 이름이 겹쳐 편집기 ComponentRegistry 에서 중복 등록 경고를 유발한다.
// 사이트 헤더/푸터는 composite 컴포넌트가 담당하므로 basic 래퍼 export 를 제거한다
// (필요 시 Div + role/시맨틱 태그로 대체). 파일 자체는 보존(직접 import 경로는 유지).
export { Hr, type HrProps } from './Hr';
// Icon 타입 정의 (enum 및 타입)
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react';
import { Div } from '../basic/Div';
import { Img } from '../basic/Img';
import { Icon } from '../basic/Icon';
import type { EditorAttrs } from '../../types';
/**
* 아바타 크기 타입
@@ -80,6 +81,14 @@ export interface AvatarProps {
isWithdrawn?: boolean;
/** 비회원 여부 (author.is_guest보다 우선) @default false */
isGuest?: boolean;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -131,6 +140,8 @@ export const Avatar: React.FC<AvatarProps> = ({
text,
isWithdrawn = false,
isGuest = false,
id,
editorAttrs,
}) => {
// 명시적 props > author 추출값 순서로 결정
const actualAvatar = avatar ?? author?.avatar;
@@ -179,7 +190,7 @@ export const Avatar: React.FC<AvatarProps> = ({
};
return (
<Div className={containerClasses}>
<Div className={containerClasses} id={id} {...editorAttrs}>
{actualAvatar && !actualIsGuest && !actualIsWithdrawn ? (
<Img
src={actualAvatar}
@@ -21,6 +21,7 @@ import { Label } from '../basic/Label';
import { Input } from '../basic/Input';
import { Img } from '../basic/Img';
import { Avatar } from './Avatar';
import type { EditorAttrs } from '../../types';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
@@ -74,6 +75,12 @@ export interface AvatarUploaderProps {
deleteSuccessActions?: Array<Record<string, any>>;
/** 삭제 실패 시 실행할 액션 배열 */
deleteErrorActions?: Array<Record<string, any>>;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
// AvatarUploader size를 Avatar size로 매핑
@@ -111,6 +118,8 @@ export function AvatarUploader({
uploadErrorActions,
deleteSuccessActions,
deleteErrorActions,
id,
editorAttrs,
}: AvatarUploaderProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [isUploading, setIsUploading] = useState(false);
@@ -420,7 +429,7 @@ export function AvatarUploader({
);
return (
<Div className={`flex flex-col items-center gap-3 ${className}`}>
<Div className={`flex flex-col items-center gap-3 ${className}`} id={id} {...editorAttrs}>
{/* 아바타 이미지 - 업로드 확인 시 미리보기 표시 */}
{showUploadConfirm && previewUrl ? (
<Div className="relative">
@@ -3,6 +3,7 @@ import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { Icon } from '../basic/Icon';
import type { EditorAttrs } from '../../types';
/**
* G7Core 다국어 헬퍼
@@ -39,6 +40,15 @@ export interface ExpandableContentProps {
* children 렌더링
*/
children?: React.ReactNode;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -68,6 +78,8 @@ export const ExpandableContent: React.FC<ExpandableContentProps> = ({
collapseText,
className = '',
children,
id,
editorAttrs,
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const [needsExpand, setNeedsExpand] = useState(false);
@@ -120,7 +132,7 @@ export const ExpandableContent: React.FC<ExpandableContentProps> = ({
const resolvedCollapseText = collapseText || t('sirsoft-ecommerce.shop.product.collapse_detail');
return (
<Div className={className}>
<Div className={className} id={id} {...editorAttrs}>
{/* 콘텐츠 컨테이너 */}
<Div className="relative">
<Div
@@ -60,6 +60,8 @@ export const FileUploader = forwardRef<FileUploaderRef, FileUploaderProps>(
enablePrimarySelection = false,
primaryFileId,
onPrimaryChange,
id,
editorAttrs,
},
ref
) => {
@@ -208,7 +210,7 @@ export const FileUploader = forwardRef<FileUploaderRef, FileUploaderProps>(
return (
<FileUploaderProvider value={contextValue}>
<Div className={className}>
<Div id={id} className={className} {...editorAttrs}>
{/* 드롭존 + 파일 목록 통합 영역 */}
<FileDropZone
isDragOver={uploader.isDragOver}
@@ -4,6 +4,8 @@
* @module composite/FileUploader/types
*/
import type { EditorAttrs } from '../../../types';
// ========== Types ==========
export interface Attachment {
@@ -151,6 +153,10 @@ export interface FileUploaderProps {
/** 순서 변경 API (기본값: /api/attachments/reorder) */
reorder?: string;
};
/** DOM id 속성 (레이아웃 편집기 코어 일괄 ID) */
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
export interface FileUploaderRef {
@@ -33,6 +33,13 @@ import { Icon } from '../basic/Icon';
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
// G7 표준 반응형 breakpoint — 모바일(< 768) / 데스크톱(>= 1024).
// 레이아웃 편집기 프리뷰 호환을 위해 Tailwind md:/lg:/sm: 미디어쿼리 대신
// G7Core.useResponsive() width 기반 분기 사용 (편집 가능 템플릿은 G7 표준
// responsive 만 허용 — viewport 미디어쿼리는 프리뷰 overrideWidth 를 무시).
const TABLET_BREAKPOINT = 768;
const DESKTOP_BREAKPOINT = 1024;
// G7Core.dispatch() navigate 헬퍼
const navigate = (path: string) => {
(window as any).G7Core?.dispatch?.({
@@ -72,6 +79,8 @@ interface FooterProps {
linkGroups?: FooterLinkGroup[];
/** 추가 CSS 클래스 */
className?: string;
/** 레이아웃 편집기 식별 속성(data-editor-*) — 시각적 루트에 spread */
editorAttrs?: Record<string, unknown>;
}
/**
@@ -103,9 +112,23 @@ const Footer: React.FC<FooterProps> = ({
socialLinks = {},
linkGroups,
className = '',
editorAttrs,
}) => {
const currentYear = new Date().getFullYear();
// G7 표준 반응형 — useResponsive() 로 프리뷰 overrideWidth 수신 (편집기 디바이스
// 전환에 정상 반응). hook 미주입 시 window.innerWidth fallback.
const G7Core = (window as any).G7Core;
const useResponsive = G7Core?.useResponsive as (() => { width: number }) | undefined;
const responsiveValue = useResponsive?.();
const width =
responsiveValue?.width ??
(typeof window !== 'undefined' ? window.innerWidth : DESKTOP_BREAKPOINT);
const isMobile = width < TABLET_BREAKPOINT;
const isDesktop = width >= DESKTOP_BREAKPOINT;
// 링크 그룹 그리드 컬럼 — 모바일 1열 / 태블릿 2열 / 데스크톱 5열.
const gridColumns = isMobile ? 1 : isDesktop ? 5 : 2;
// 기본 링크 그룹
const defaultLinkGroups: FooterLinkGroup[] = [
{
@@ -146,11 +169,17 @@ const Footer: React.FC<FooterProps> = ({
};
return (
<FooterBasic className={`bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-800 ${className}`}>
<FooterBasic
{...((editorAttrs ?? {}) as Record<string, never>)}
className={`bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-800 ${className}`}
>
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
<Div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-8">
{/* 사이트 정보 */}
<Div className="lg:col-span-2">
<Div
className="grid gap-8"
style={{ gridTemplateColumns: `repeat(${gridColumns}, minmax(0, 1fr))` }}
>
{/* 사이트 정보 — 데스크톱(5열)에서만 2칸 차지 */}
<Div style={isDesktop ? { gridColumn: 'span 2 / span 2' } : undefined}>
<H3 className="text-lg font-bold text-gray-900 dark:text-white">{siteName}</H3>
{siteDescription && (
<P className="mt-2 text-sm text-gray-600 dark:text-gray-400">{siteDescription}</P>
@@ -198,7 +227,10 @@ const Footer: React.FC<FooterProps> = ({
</Div>
{/* 저작권 */}
<Div className="mt-8 pt-8 border-t border-gray-200 dark:border-gray-800 flex flex-col sm:flex-row justify-between items-center gap-4">
<Div
className="mt-8 pt-8 border-t border-gray-200 dark:border-gray-800 flex justify-between items-center gap-4"
style={{ flexDirection: isMobile ? 'column' : 'row' }}
>
<P className="text-sm text-gray-500 dark:text-gray-400">
{copyrightText || `© ${currentYear} ${siteName}. All rights reserved.`}
</P>
@@ -33,6 +33,9 @@ import { ThemeToggle } from './ThemeToggle';
// Avatar 컴포넌트 import
import { Avatar } from './Avatar';
// SlotContainer — 헤더 통화 등 모듈 주입 UI 를 떙겨 렌더 (헤더는 주입 모듈을 모름)
import { SlotContainer } from './SlotContainer';
// NotificationCenter 컴포넌트 import
import { NotificationCenter, type NotificationItem } from './NotificationCenter';
@@ -87,6 +90,8 @@ interface HeaderProps {
shopBase?: string;
/** 추가 CSS 클래스 */
className?: string;
/** 레이아웃 편집기 식별 속성(data-editor-*) — 시각적 루트에 spread */
editorAttrs?: Record<string, unknown>;
// ===== 알림센터 드롭다운 Props =====
/** 알림 목록 (NotificationCenter에 전달) */
@@ -157,6 +162,7 @@ const Header: React.FC<HeaderProps> = ({
currentLocale = 'ko',
shopBase = '/shop',
className = '',
editorAttrs,
// 알림센터
notifications = [],
notificationHasMore = false,
@@ -178,10 +184,12 @@ const Header: React.FC<HeaderProps> = ({
const [searchQuery, setSearchQuery] = useState('');
const [showUserMenu, setShowUserMenu] = useState(false);
const [showMoreBoards, setShowMoreBoards] = useState(false);
const [showLangMenu, setShowLangMenu] = useState(false);
const [dropdownPosition, setDropdownPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
const [currentPath, setCurrentPath] = useState(window.location.pathname);
const userMenuRef = useRef<HTMLDivElement>(null);
const moreButtonRef = useRef<HTMLDivElement>(null);
const langMenuRef = useRef<HTMLDivElement>(null);
// G7Core.useResponsive를 통해 반응형 상태 구독 (G7 표준 — 위지윅 overrideWidth 호환)
const G7Core = (window as any).G7Core;
@@ -244,6 +252,9 @@ const Header: React.FC<HeaderProps> = ({
if (moreButtonRef.current && !moreButtonRef.current.contains(event.target as Node)) {
setShowMoreBoards(false);
}
if (langMenuRef.current && !langMenuRef.current.contains(event.target as Node)) {
setShowLangMenu(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
@@ -267,17 +278,25 @@ const Header: React.FC<HeaderProps> = ({
});
};
// 언어 변경 핸들러
// 언어 변경 핸들러 — 헤더 독립 언어 버튼(코어 기능)에서 호출. setLocale 은 비회원도 동작.
const handleLocaleChange = (locale: string) => {
(window as any).G7Core?.dispatch?.({
handler: 'setLocale',
target: locale,
});
setShowUserMenu(false);
setShowLangMenu(false);
};
// 로케일 코드 → 표시명 (활성 언어팩 native_name 우선, 폴백 사전)
const getLocaleName = (locale: string): string =>
(window as any).G7Core?.state?.get?.('_global.appConfig.localeNames')?.[locale] ??
(locale === 'ko' ? '한국어' : locale === 'en' ? 'English' : locale === 'ja' ? '日本語' : locale === 'zh' ? '中文' : locale === 'es' ? 'Español' : locale === 'fr' ? 'Français' : locale === 'de' ? 'Deutsch' : locale.toUpperCase());
return (
<HeaderBasic className={`sticky top-0 z-50 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 ${className}`}>
<HeaderBasic
{...((editorAttrs ?? {}) as Record<string, never>)}
className={`sticky top-0 z-50 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 ${className}`}
>
{/* 상단 바 */}
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Div className="flex items-center justify-between h-16">
@@ -352,6 +371,57 @@ const Header: React.FC<HeaderProps> = ({
)}
</Button>
{/* 언어 선택 — 헤더 독립 버튼(코어 기능, 비회원 포함 전체 노출). 공간 절약 위해 아이콘+로케일 코드만.
언어는 항상 존재(이커머스 무관) → 템플릿 헤더 내장. */}
{availableLocales && availableLocales.length > 1 && (
<Div ref={langMenuRef} className="relative">
<Button
onClick={() => setShowLangMenu(!showLangMenu)}
className="flex items-center gap-1.5 px-2.5 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg cursor-pointer transition-colors"
aria-haspopup="listbox"
aria-expanded={showLangMenu}
aria-label={t('common.language')}
>
<Icon name="globe" className="w-4 h-4" />
<Span className="font-medium uppercase">{currentLocale}</Span>
<Icon name="chevron-down" className="w-3 h-3" />
</Button>
{showLangMenu && (
<Div
role="listbox"
className="absolute right-0 mt-2 w-44 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 z-50 overflow-hidden"
>
{availableLocales.map((locale) => {
const isActive = locale === currentLocale;
return (
<Button
key={locale}
role="option"
aria-selected={isActive}
onClick={() => handleLocaleChange(locale)}
className={`w-full px-4 py-2.5 text-left text-sm flex items-center gap-3 cursor-pointer transition-colors ${
isActive
? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<Icon name="globe" className="w-4 h-4" />
<Span className="flex-1 font-medium">{getLocaleName(locale)}</Span>
{isActive && <Icon name="check" className="w-4 h-4" />}
</Button>
);
})}
</Div>
)}
</Div>
)}
{/* 통화 선택 — 이커머스 모듈이 'header_currency' 슬롯에 주입(layout_extensions).
헤더는 슬롯 이름만 알고 통화/모듈을 모름. 모듈 비활성 시 빈 슬롯 → 미렌더(인프라 자동 게이트).
id 지정 필수 — 같은 슬롯이 모바일 헤더 SlotContainer 와 동시 렌더되므로 주입 컴포넌트
root id 가 컨테이너별로 스코프되도록(SlotContainer 가 id 로 자식 root id 를 고유화) 한다. */}
<SlotContainer slotId="header_currency" id="header_currency_slot_desktop" className="flex items-center" />
{/* 사용자 메뉴 */}
{user?.uuid ? (
<Div ref={userMenuRef} className="relative">
@@ -415,31 +485,7 @@ const Header: React.FC<HeaderProps> = ({
</Button>
</Div>
{/* 언어 선택 (availableLocales가 있을 때만 표시) */}
{availableLocales && availableLocales.length > 1 && (
<>
<Hr className="my-1 border-gray-200 dark:border-gray-700" />
<Div className="py-1">
<Div className="px-4 py-2 text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
{t('common.language')}
</Div>
{availableLocales.map((locale) => (
<Button
key={locale}
onClick={() => handleLocaleChange(locale)}
className={`block w-full text-left px-4 py-2 text-sm cursor-pointer ${
locale === currentLocale
? 'text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<Icon name="globe" className="inline w-4 h-4 mr-2" />
{(window as any).G7Core?.state?.get?.('_global.appConfig.localeNames')?.[locale] ?? (locale === 'ko' ? '한국어' : locale === 'en' ? 'English' : locale === 'ja' ? '日本語' : locale === 'zh' ? '中文' : locale === 'es' ? 'Español' : locale === 'fr' ? 'Français' : locale === 'de' ? 'Deutsch' : locale.toUpperCase())}
</Button>
))}
</Div>
</>
)}
{/* 언어 선택은 헤더 독립 버튼으로 일원화(드롭다운에서 제거) — 비회원도 헤더에서 전환 가능 */}
<Hr className="my-1 border-gray-200 dark:border-gray-700" />
<Button
@@ -453,16 +499,23 @@ const Header: React.FC<HeaderProps> = ({
)}
</Div>
) : (
<Div className="flex items-center gap-2">
<Div className="flex items-center gap-1.5">
{/* 주문조회 — 로그인 페이지로 진입. 회원은 로그인 후 redirect 파라미터로 마이페이지 주문 내역으로 이동, 비회원은 로그인 페이지의 '비회원 주문 조회' 링크로 폼 진입. 로그아웃된 회원이 비회원 페이지에서 막다른 길에 빠지는 케이스를 차단한다. */}
<Button
onClick={() => navigate('/login?redirect=/mypage/orders')}
className="px-2.5 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white cursor-pointer"
>
{t('shop.guest_order_form.nav_link')}
</Button>
<Button
onClick={() => navigate('/login')}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white cursor-pointer"
className="px-2.5 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white cursor-pointer"
>
{t('auth.login')}
</Button>
<Button
onClick={() => navigate('/register')}
className="px-4 py-2 text-sm font-medium text-white bg-emerald-500 rounded-lg hover:bg-emerald-600 cursor-pointer"
className="ml-1 px-3 py-2 text-sm font-medium text-white bg-emerald-500 rounded-lg hover:bg-emerald-600 cursor-pointer"
>
{t('auth.register_link')}
</Button>
@@ -487,14 +540,14 @@ const Header: React.FC<HeaderProps> = ({
<Nav className="border-t border-gray-200 dark:border-gray-800">
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Div className="flex items-center gap-1 h-12 overflow-x-auto">
<Button onClick={() => navigate('/')} className={getNavButtonClass(isActiveRoute('/', true))}>
<Button onClick={() => navigate('/')} className={getNavButtonClass(isActiveRoute('/', true))} data-testid="nav-home">
{t('nav.home')}
</Button>
<Button onClick={() => navigate('/boards/popular')} className={`flex items-center gap-1 ${getNavButtonClass(isActiveRoute('/boards/popular'))}`}>
<Button onClick={() => navigate('/boards/popular')} className={`flex items-center gap-1 ${getNavButtonClass(isActiveRoute('/boards/popular'))}`} data-testid="nav-popular">
<Span className="text-orange-500">🔥</Span>
{t('nav.popular')}
</Button>
<Button onClick={() => navigate(`${shopBase === '/' ? '' : shopBase}/products`)} className={`flex items-center gap-1 ${getNavButtonClass(isShopActive())}`}>
<Button onClick={() => navigate(`${shopBase === '/' ? '' : shopBase}/products`)} className={`flex items-center gap-1 ${getNavButtonClass(isShopActive())}`} data-testid="nav-shop">
<Span>🛒</Span>
{t('nav.shop')}
</Button>
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react';
// @ts-ignore - DOMPurify 타입 정의 없음
import DOMPurify from 'dompurify';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface HtmlContentProps {
/**
@@ -32,6 +33,15 @@ export interface HtmlContentProps {
* content보다 우선순위가 높음
*/
text?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -69,6 +79,8 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
isHtml = true,
className = '',
purifyConfig,
id,
editorAttrs,
}) => {
// text prop이 우선순위가 높음 (레이아웃 JSON에서 사용)
const actualContent = text ?? content ?? '';
@@ -88,7 +100,7 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
`.trim().replace(/\s+/g, ' ');
return (
<Div className={textClasses}>
<Div className={textClasses} id={id} {...editorAttrs}>
{actualContent}
</Div>
);
@@ -181,8 +193,10 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
return (
<Div
id={id}
className={containerClasses}
dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
{...editorAttrs}
/>
);
};
@@ -5,6 +5,7 @@ import { Button } from '../basic/Button';
import { Textarea } from '../basic/Textarea';
import { Input } from '../basic/Input';
import { HtmlContent } from './HtmlContent';
import type { EditorAttrs } from '../../types';
// G7Core 참조
const G7Core = () => (window as any).G7Core;
@@ -90,6 +91,15 @@ export interface HtmlEditorProps {
* 읽기 전용 모드
*/
readOnly?: boolean;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -127,6 +137,8 @@ export const HtmlEditor: React.FC<HtmlEditorProps> = ({
name = 'content',
htmlFieldName = 'content_mode',
readOnly = false,
id,
editorAttrs,
}) => {
// HTML 모드 내부 상태 (Toggle과 동기화)
const [isHtml, setIsHtml] = useState(isHtmlProp);
@@ -188,7 +200,7 @@ export const HtmlEditor: React.FC<HtmlEditorProps> = ({
}, []);
return (
<Div className={`space-y-2 ${className}`}>
<Div className={`space-y-2 ${className}`} id={id} {...editorAttrs}>
{/* 라벨 및 HTML 모드 토글 */}
<Div className="flex items-center justify-between">
@@ -20,6 +20,9 @@ import 'yet-another-react-lightbox/plugins/thumbnails.css';
import { Button } from '../basic/Button';
import { I } from '../basic/I';
import { Div } from '../basic/Div';
import { Img } from '../basic/Img';
import type { EditorAttrs } from '../../types';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
@@ -70,6 +73,18 @@ export interface ImageGalleryProps {
showThumbnails?: boolean;
/** 커스텀 다운로드 핸들러 (제공 시 기본 다운로드 로직 대신 실행) */
onDownload?: (image: GalleryImage, index: number) => void;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용).
* 본 컴포넌트는 서드파티 Lightbox 모달(`createPortal` 로 body 렌더)이라 런타임에는
* 인라인 DOM 이 없다. 편집 모드(editorAttrs 존재)에서는 캔버스 선택·속성 편집이
* 가능하도록 인라인 placeholder(이미지 썸네일 그리드)를 대신 렌더하고 거기에
* editorAttrs·id 를 부착한다. 런타임(editorAttrs 미주입)은 종전 Lightbox 동작 그대로.
*
*/
editorAttrs?: EditorAttrs;
/** DOM id 속성 (레이아웃 편집기 코어 일괄 ID — 편집 placeholder 루트에 부착) */
id?: string;
}
// ========== Helper Functions ==========
@@ -185,6 +200,8 @@ export const ImageGallery: React.FC<ImageGalleryProps> = ({
showDownload = true,
showThumbnails = true,
onDownload,
editorAttrs,
id,
}) => {
// 현재 슬라이드 인덱스 (다운로드 버튼용)
const [currentIndex, setCurrentIndex] = useState(startIndex);
@@ -214,6 +231,37 @@ export const ImageGallery: React.FC<ImageGalleryProps> = ({
currentIndexRef.current = currentIndex;
}, [currentIndex]);
// 편집 모드(편집기 캔버스) — Lightbox 모달은 인라인 DOM 이 없어 선택·편집 불가.
// editorAttrs 가 주입되면 인라인 placeholder(썸네일 그리드)를 대신 렌더해
// 캔버스에서 선택·속성 편집이 가능하게 한다. 런타임(editorAttrs 미주입)은 미진입.
// (Hooks 규칙 — 모든 hook 호출 이후에 분기 return)
if (editorAttrs) {
const previewImages = (images ?? []).slice(0, 4);
return (
<Div
id={id}
className="grid grid-cols-2 gap-2 p-3 rounded-lg border border-dashed border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-800"
{...editorAttrs}
>
{previewImages.length > 0 ? (
previewImages.map((image, index) => (
<Img
key={index}
src={image.thumbnail || image.src}
alt={image.title || ''}
className="w-full aspect-square object-cover rounded bg-gray-200 dark:bg-gray-700"
/>
))
) : (
<Div className="col-span-2 flex items-center justify-center py-6 text-sm text-gray-400 dark:text-gray-500">
<I className="fa-regular fa-images mr-2" />
{t('editor.component.image_gallery')}
</Div>
)}
</Div>
);
}
return (
<Lightbox
open={isOpen}
@@ -5,6 +5,7 @@ import { Span } from '../basic/Span';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Input } from '../basic/Input';
import type { EditorAttrs } from '../../types';
/**
* 알림 아이템 인터페이스
@@ -61,6 +62,10 @@ export interface NotificationCenterProps {
/** 드롭다운 정렬 방향 — "right"(기본): 우측 정렬되어 좌측으로 확장 / "left": 좌측 정렬되어 우측으로 확장 */
dropdownAlign?: 'left' | 'right';
className?: string;
/** DOM id 속성 (레이아웃 편집기 코어 일괄 ID) */
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
/**
@@ -102,6 +107,8 @@ export const NotificationCenter: React.FC<NotificationCenterProps> = ({
onUnreadOnlyToggle,
dropdownAlign = 'right',
className = '',
id,
editorAttrs,
}) => {
const [showNotifications, setShowNotifications] = useState(false);
const notificationRef = useRef<HTMLDivElement>(null);
@@ -277,7 +284,7 @@ export const NotificationCenter: React.FC<NotificationCenterProps> = ({
}, [showNotifications, dropdownAlign, notifications.length]);
return (
<Div ref={notificationRef} className={`relative ${className}`}>
<Div ref={notificationRef} className={`relative ${className}`} id={id} {...editorAttrs}>
<Button
onClick={handleToggle}
className="relative p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors cursor-pointer"
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
@@ -17,6 +18,14 @@ export interface PaginationProps {
style?: React.CSSProperties;
prevText?: string;
nextText?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -47,6 +56,8 @@ export const Pagination: React.FC<PaginationProps> = ({
style,
prevText,
nextText,
id,
editorAttrs,
}) => {
// 페이지 번호 생성 알고리즘
@@ -122,6 +133,7 @@ export const Pagination: React.FC<PaginationProps> = ({
style={style}
role="navigation"
aria-label={t('common.pagination')}
id={id} {...editorAttrs}
>
{/* First Button */}
{showFirstLast && (
@@ -9,6 +9,7 @@ import React from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:PostReactions')) ?? {
@@ -43,6 +44,12 @@ interface PostReactionsProps {
size?: 'sm' | 'md' | 'lg';
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
interface ReactionConfig {
@@ -100,6 +107,8 @@ const PostReactions: React.FC<PostReactionsProps> = ({
onReact,
size = 'md',
className = '',
id,
editorAttrs,
}) => {
const sizeClasses = {
sm: 'px-2 py-1 text-xs gap-1',
@@ -147,7 +156,7 @@ const PostReactions: React.FC<PostReactionsProps> = ({
};
return (
<Div className={`flex flex-wrap gap-2 ${className}`}>
<Div className={`flex flex-wrap gap-2 ${className}`} id={id} {...editorAttrs}>
{REACTION_CONFIGS.map((config) => {
const count = getReactionCount(config.type);
const isActive = userReaction === config.type;
@@ -5,7 +5,7 @@
* 다중 통화를 지원하며, 할인율 뱃지를 표시합니다.
*/
import React from 'react';
import React, { useEffect, useState } from 'react';
// @ts-ignore - DOMPurify 타입 정의 없음
import DOMPurify from 'dompurify';
@@ -16,10 +16,39 @@ import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { H3 } from '../basic/H3';
import { Img } from '../basic/Img';
import type { EditorAttrs } from '../../types';
// G7Core 전역 상태 훅
const useGlobalState = (key: string) =>
(window as any).G7Core?.state?.get?.(key);
/**
* 선호 통화를 전역 상태에서 읽고, 변경을 구독하는 훅.
*
* 회귀 배경: 종전 `G7Core.state.get('preferredCurrency')` 는 key 를 무시하고
* _global 전체 객체를 반환해(G7CoreGlobals: get: () => getGlobalState()) 통화 코드가
* 아닌 객체가 들어가 multi_currency 조회가 항상 KRW 폴백되었고, 단발 get 이라 헤더에서
* 통화를 바꿔도 카드가 리렌더되지 않았다(상품 리스트/검색/캐러셀 KRW 고정 결함).
* → 전체 객체에서 `.preferredCurrency` 키로 접근 + state.subscribe 로 리렌더한다.
*
* @returns 현재 선호 통화 코드(미설정 시 'KRW')
*/
const usePreferredCurrency = (): string => {
const read = (): string => {
const state = (window as any).G7Core?.state?.get?.();
return (state && state.preferredCurrency) || 'KRW';
};
const [currency, setCurrency] = useState<string>(read);
useEffect(() => {
const subscribe = (window as any).G7Core?.state?.subscribe;
// 구독 시점과 마운트 사이 변경분 보정
setCurrency(read());
if (typeof subscribe !== 'function') return;
const unsubscribe = subscribe((state: Record<string, any>) => {
setCurrency((state && state.preferredCurrency) || 'KRW');
});
return typeof unsubscribe === 'function' ? unsubscribe : undefined;
}, []);
return currency;
};
// G7Core.dispatch() navigate 헬퍼
const navigate = (path: string) => {
@@ -78,6 +107,14 @@ interface ProductCardProps {
shopBase?: string;
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -132,8 +169,10 @@ const ProductCard: React.FC<ProductCardProps> = ({
onClick,
shopBase = '/shop',
className = '',
id,
editorAttrs,
}) => {
const preferredCurrency = useGlobalState('preferredCurrency') || 'KRW';
const preferredCurrency = usePreferredCurrency();
/**
* 다중 통화 가격을 가져옵니다.
@@ -187,6 +226,7 @@ const ProductCard: React.FC<ProductCardProps> = ({
<Button
onClick={handleClick}
className={`block w-full text-left group bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-lg transition-shadow cursor-pointer ${className}`}
id={id} {...editorAttrs}
>
{/* 이미지 영역 */}
<Div className="relative aspect-square overflow-hidden bg-gray-100 dark:bg-gray-700">
@@ -13,6 +13,7 @@ import { Img } from '../basic/Img';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { ImageGallery, useImageGallery, GalleryImage } from './ImageGallery';
import type { EditorAttrs } from '../../types';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
@@ -42,6 +43,12 @@ export interface ProductImageViewerProps {
images: ProductImage[];
/** 커스텀 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
// ========== Helper ==========
@@ -58,6 +65,8 @@ const getImageSrc = (image: ProductImage): string => {
export const ProductImageViewer: React.FC<ProductImageViewerProps> = ({
images = [],
className = '',
id,
editorAttrs,
}) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const { openGallery, galleryProps } = useImageGallery();
@@ -80,6 +89,7 @@ export const ProductImageViewer: React.FC<ProductImageViewerProps> = ({
return (
<Div
className={`flex items-center justify-center bg-gray-100 dark:bg-gray-700 rounded-lg aspect-square ${className}`}
id={id} {...editorAttrs}
>
<Div className="text-center text-gray-400 dark:text-gray-500">
<Icon name="image" size="3x" className="mb-3 opacity-50" />
@@ -92,7 +102,7 @@ export const ProductImageViewer: React.FC<ProductImageViewerProps> = ({
const currentImage = images[selectedIndex] ?? images[0];
return (
<Div className={className}>
<Div id={id} className={className} {...editorAttrs}>
{/* 메인 이미지 */}
<Div className="relative overflow-hidden rounded-lg bg-gray-100 dark:bg-gray-700 aspect-square mb-3">
<Button
@@ -10,6 +10,7 @@ import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Input } from '../basic/Input';
import { Icon } from '../basic/Icon';
import type { EditorAttrs } from '../../types';
interface QuantitySelectorProps {
/** 현재 수량 */
@@ -26,6 +27,14 @@ interface QuantitySelectorProps {
disabled?: boolean;
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -72,6 +81,8 @@ const QuantitySelector: React.FC<QuantitySelectorProps> = ({
size = 'md',
disabled = false,
className = '',
id,
editorAttrs,
}) => {
const sizeClasses = {
sm: {
@@ -128,6 +139,7 @@ const QuantitySelector: React.FC<QuantitySelectorProps> = ({
return (
<Div
className={`inline-flex items-center border border-gray-300 dark:border-gray-600 rounded-lg ${classes.container} ${className}`}
id={id} {...editorAttrs}
>
{/* 감소 버튼 */}
<Button
@@ -21,6 +21,7 @@ import { Input } from '../basic/Input';
import { Textarea } from '../basic/Textarea';
import { H3 } from '../basic/H3';
import { Label } from '../basic/Label';
import type { EditorAttrs } from '../../types';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
@@ -43,6 +44,14 @@ interface RichTextEditorProps {
disabled?: boolean;
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
type FormatType =
@@ -96,6 +105,8 @@ const RichTextEditor: React.FC<RichTextEditorProps> = ({
minHeight = '300px',
disabled = false,
className = '',
id,
editorAttrs,
}) => {
const editorRef = useRef<HTMLDivElement>(null);
const [content, setContent] = useState(initialValue);
@@ -185,7 +196,7 @@ const RichTextEditor: React.FC<RichTextEditorProps> = ({
];
return (
<Div className={`border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden ${className}`}>
<Div className={`border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden ${className}`} id={id} {...editorAttrs}>
{/* 툴바 */}
<Div className="flex flex-wrap items-center gap-1 p-2 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
{/* 텍스트 포맷 */}
@@ -6,6 +6,7 @@ import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
@@ -28,6 +29,14 @@ export interface SearchBarProps {
showSuggestions?: boolean;
className?: string;
style?: React.CSSProperties;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -72,6 +81,8 @@ export const SearchBar: React.FC<SearchBarProps> = ({
showSuggestions = false,
className = '',
style,
id,
editorAttrs,
}) => {
// props로 전달된 값이 없으면 다국어 키 사용
const resolvedPlaceholder = placeholder ?? t('common.search_placeholder');
@@ -127,7 +138,7 @@ export const SearchBar: React.FC<SearchBarProps> = ({
};
return (
<Div ref={containerRef} className={`relative ${className}`} style={style}>
<Div ref={containerRef} className={`relative ${className}`} style={style} id={id} {...editorAttrs}>
<Form onSubmit={handleSubmit} className="relative">
<Div className={`relative flex items-center ${showButton ? 'gap-2' : ''}`}>
{/* Input wrapper */}
@@ -0,0 +1,259 @@
/**
* SlotContainer.tsx
*
* 동적 슬롯에 등록된 컴포넌트들을 렌더링하는 컨테이너 컴포넌트
*
* SlotContainer는 SlotContext에서 지정된 슬롯 ID에 등록된 모든 컴포넌트를 수집하고,
* slotOrder 기준으로 정렬하여 렌더링합니다.
*
* 통짜 TSX 컴포넌트(예: Header)가 레이아웃 JSON 노드(`"slot": "..."`)로 주입된 UI를
* 떙겨 쓰는 코어 슬롯 시스템의 소비 측 컴포넌트입니다. 빈 슬롯이면 null 을 렌더하므로
* "모듈 활성 시에만 노출"이 확장 주입 인프라로 자동 충족됩니다(헤더는 주입 모듈을 모름).
*
* @module SlotContainer
*
* @example
* ```json
* {
* "type": "composite",
* "name": "SlotContainer",
* "props": {
* "slotId": "header_currency",
* "className": "flex items-center"
* }
* }
* ```
*/
import React, { useEffect, useState, useCallback } from 'react';
import { Div } from '../basic/Div';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:SlotContainer')) ?? {
log: (...args: unknown[]) => console.log('[Comp:SlotContainer]', ...args),
warn: (...args: unknown[]) => console.warn('[Comp:SlotContainer]', ...args),
error: (...args: unknown[]) => console.error('[Comp:SlotContainer]', ...args),
};
/**
* 슬롯에 주입된 컴포넌트의 root id 를 컨테이너 id 로 스코프해 고유화한다.
*
* 같은 슬롯 컴포넌트가 여러 SlotContainer(예: 헤더 데스크톱/모바일)에서 렌더되면 주입
* 컴포넌트의 정적 root id 가 컨테이너마다 같은 값으로 중복 출력되어 HTML id 유일성을
* 위반한다. 컨테이너 고유 id 가 있고 컴포넌트가 root id 를 가지면 `{id}__{containerId}`
* 로 스코프한다. 둘 중 하나라도 없으면 원본 그대로(무영향).
*
* @param componentDef 주입 컴포넌트 정의
* @param containerId 이 SlotContainer 의 DOM id (없으면 스코프 안 함)
* @returns 스코프된(또는 원본) 컴포넌트 정의
*/
export function scopeSlotChildDef<T extends { id?: unknown }>(
componentDef: T,
containerId: string | undefined,
): T {
if (
containerId &&
componentDef &&
typeof componentDef.id === 'string' &&
componentDef.id.length > 0
) {
return { ...componentDef, id: `${componentDef.id}__${containerId}` };
}
return componentDef;
}
/**
* SlotContainer Props
*/
export interface SlotContainerProps {
/**
* 슬롯 ID
*
* 이 슬롯에 등록된 컴포넌트들을 렌더링합니다.
*/
slotId: string;
/**
* 컨테이너 CSS 클래스
*/
className?: string;
/**
* 빈 슬롯일 때 표시할 내용
*/
emptyContent?: React.ReactNode;
/**
* 인라인 스타일
*/
style?: React.CSSProperties;
/**
* 컴포넌트 ID (DOM id)
*/
id?: string;
/**
* 자식 컴포넌트 (children을 통한 fallback 또는 slot 컴포넌트가 아닌 정적 컨텐츠)
*/
children?: React.ReactNode;
}
/**
* SlotRegistration 타입 (SlotContext에서 정의된 것과 호환)
*/
interface SlotRegistration {
componentDef: any;
dataContext: Record<string, any>;
order: number;
parentFormContext: any;
getParentComponentContext: () => { state: Record<string, any>; setState: (updates: any) => void };
translationContext: any;
registrationKey: string;
}
/**
* SlotContext 값 타입
*/
interface SlotContextValue {
getSlotComponents: (slotId: string) => SlotRegistration[];
subscribeToSlot: (slotId: string, callback: () => void) => () => void;
isEnabled: boolean;
}
/**
* SlotContainer 컴포넌트
*
* SlotContext에서 지정된 슬롯 ID에 등록된 컴포넌트들을 수집하여 렌더링합니다.
* 컴포넌트는 slotOrder 기준으로 정렬됩니다.
*
* 이 컴포넌트는 SlotContext를 사용하므로 SlotProvider 내부에서만 동작합니다.
* SlotProvider는 DynamicRenderer의 루트에서 자동으로 래핑됩니다.
*
* @param props SlotContainerProps
*/
export const SlotContainer: React.FC<SlotContainerProps> = ({
slotId,
className = '',
emptyContent,
style,
id,
children,
}) => {
const [slotComponents, setSlotComponents] = useState<SlotRegistration[]>([]);
const [, forceUpdate] = useState({});
// SlotContext 가져오기 (window.__slotContextValue 또는 G7Core.getSlotContext() 사용)
const getSlotContext = useCallback((): SlotContextValue | null => {
const directSlotContext = (window as any).__slotContextValue;
if (directSlotContext) {
return directSlotContext;
}
const g7Core = (window as any).G7Core;
if (!g7Core) return null;
const slotContext = g7Core.getSlotContext?.();
return slotContext || null;
}, []);
// 슬롯 컴포넌트 업데이트 함수
const updateSlotComponents = useCallback(() => {
const slotContext = getSlotContext();
if (slotContext && slotContext.isEnabled) {
setSlotComponents(slotContext.getSlotComponents(slotId));
}
}, [slotId, getSlotContext]);
// 슬롯 구독 및 업데이트
useEffect(() => {
const slotContext = getSlotContext();
if (!slotContext || !slotContext.isEnabled) {
return;
}
updateSlotComponents();
const unsubscribe = slotContext.subscribeToSlot(slotId, () => {
updateSlotComponents();
forceUpdate({});
});
return unsubscribe;
}, [slotId, getSlotContext, updateSlotComponents]);
// G7Core에서 DynamicRenderer 가져오기
const getDynamicRenderer = useCallback(() => {
const g7Core = (window as any).G7Core;
if (!g7Core) return null;
return g7Core.getDynamicRenderer?.();
}, []);
// 빈 슬롯 처리
if (slotComponents.length === 0) {
if (emptyContent) {
return (
<Div className={className} style={style} id={id}>
{emptyContent}
</Div>
);
}
if (children) {
return (
<Div className={className} style={style} id={id}>
{children}
</Div>
);
}
return null;
}
const DynamicRenderer = getDynamicRenderer();
const g7Core = (window as any).G7Core;
if (!DynamicRenderer || !g7Core) {
logger.error('G7Core or DynamicRenderer not available');
return null;
}
return (
<Div className={className} style={style} id={id}>
{slotComponents.map((registration) => {
const {
componentDef,
dataContext,
parentFormContext,
getParentComponentContext,
translationContext,
} = registration;
// 같은 슬롯 컴포넌트가 여러 SlotContainer(헤더 데스크톱/모바일)에서 렌더될 때
// 주입 컴포넌트 root id 를 컨테이너 id 로 스코프해 HTML id 중복을 막는다.
const scopedDef = scopeSlotChildDef(componentDef, id);
return (
<DynamicRenderer
key={scopedDef.id || `slot-${slotId}-${registration.order}`}
componentDef={scopedDef}
dataContext={dataContext}
translationContext={translationContext}
registry={g7Core.getComponentRegistry()}
bindingEngine={g7Core.getDataBindingEngine()}
translationEngine={g7Core.getTranslationEngine()}
actionDispatcher={g7Core.getActionDispatcher()}
parentComponentContext={getParentComponentContext?.()}
parentFormContextProp={parentFormContext}
isRootRenderer={false}
/>
);
})}
{children}
</Div>
);
};
export default SlotContainer;
@@ -9,6 +9,7 @@ import React from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
/**
* 소셜 로그인 아이콘 SVG 컴포넌트
@@ -70,6 +71,12 @@ interface SocialLoginButtonsProps {
variant?: 'full' | 'icon';
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
interface ProviderConfig {
@@ -144,6 +151,8 @@ const SocialLoginButtons: React.FC<SocialLoginButtonsProps> = ({
mode = 'login',
variant = 'full',
className = '',
id,
editorAttrs,
}) => {
const handleSocialLogin = (provider: SocialProvider) => {
// OAuth 인증 URL로 리다이렉트
@@ -164,7 +173,7 @@ const SocialLoginButtons: React.FC<SocialLoginButtonsProps> = ({
if (variant === 'icon') {
return (
<Div className={`flex justify-center gap-4 ${className}`}>
<Div className={`flex justify-center gap-4 ${className}`} id={id} {...editorAttrs}>
{filteredProviders.map((provider) => (
<Button
key={provider.id}
@@ -180,7 +189,7 @@ const SocialLoginButtons: React.FC<SocialLoginButtonsProps> = ({
}
return (
<Div className={`space-y-3 ${className}`}>
<Div className={`space-y-3 ${className}`} id={id} {...editorAttrs}>
{filteredProviders.map((provider) => (
<Button
key={provider.id}
@@ -6,6 +6,7 @@ import { IconName } from '../basic/IconTypes';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
import { Select } from '../basic/Select';
import type { EditorAttrs } from '../../types';
export interface Tab {
id: string | number;
@@ -26,6 +27,14 @@ export interface TabNavigationProps {
hiddenTabIds?: (string | number)[];
/** 모바일 전환 임계값 (px). 기본값 768 — G7 ResponsiveContext mobile 프리셋과 동일 */
mobileBreakpoint?: number;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -67,6 +76,8 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
style,
hiddenTabIds = [],
mobileBreakpoint = 768,
id,
editorAttrs,
}) => {
// G7Core.useResponsive를 통해 반응형 상태 구독 (G7 표준)
const G7Core = (window as any).G7Core;
@@ -102,9 +113,12 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
: tabs;
// 모바일: Select 드롭다운 단일 렌더
// 데스크톱 분기와 동일하게 id/editorAttrs 를 루트에 spread 해야 레이아웃 편집기가
// 모바일 디바이스 미리보기에서도 이 노드를 선택/측정할 수 있다(모든 렌더 분기 패리티 —
// 누락 시 모바일 프리뷰에서 data-editor-* 가 사라져 캔버스에서 선택 불가).
if (isMobile) {
return (
<Div className={`relative ${className}`} style={style}>
<Div className={`relative ${className}`} style={style} id={id} {...editorAttrs}>
<Select
value={activeTabId !== undefined ? String(activeTabId) : ''}
onChange={handleSelectChange}
@@ -154,7 +168,7 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
// 데스크톱: 탭 버튼 단일 렌더
return (
<Div className={`relative ${className}`} style={style}>
<Div className={`relative ${className}`} style={style} id={id} {...editorAttrs}>
<Nav className={navClasses}>
{visibleTabs.map((tab) => (
<Button
@@ -4,6 +4,7 @@ import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
/**
* 테마 모드 타입
@@ -24,6 +25,10 @@ export interface ThemeToggleProps {
lightText?: string;
/** 다크 모드 텍스트 (다국어 키 사용 권장) */
darkText?: string;
/** DOM id 속성 (레이아웃 편집기 코어 일괄 ID) */
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
/**
@@ -93,6 +98,8 @@ export const ThemeToggle: React.FC<ThemeToggleProps> = ({
autoText = 'System',
lightText = 'Light',
darkText = 'Dark',
id,
editorAttrs,
}) => {
// 초기 테마를 즉시 로드하고 적용
const initialTheme = getInitialTheme();
@@ -157,7 +164,7 @@ export const ThemeToggle: React.FC<ThemeToggleProps> = ({
};
return (
<Div ref={menuRef} className={`relative ${className}`}>
<Div ref={menuRef} className={`relative ${className}`} id={id} {...editorAttrs}>
{/* 테마 토글 버튼 */}
<Button
onClick={() => setShowMenu(!showMenu)}
@@ -45,6 +45,7 @@ import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { Icon } from '../basic/Icon';
import type { EditorAttrs } from '../../types';
// G7Core 참조
const getG7Core = () => (window as any).G7Core;
@@ -177,6 +178,15 @@ export interface UserInfoProps {
hideMenuItems?: string[];
/** 기본 메뉴에 추가할 항목 */
appendMenuItems?: MenuItemConfig[];
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
// 레이아웃별 컨테이너 클래스
@@ -234,6 +244,8 @@ export const UserInfo: React.FC<UserInfoProps> = ({
menuItems,
hideMenuItems = [],
appendMenuItems = [],
id,
editorAttrs,
}) => {
// 명시적 props > author 추출값 순서로 결정
const actualUserId = userId ?? author?.uuid;
@@ -365,7 +377,7 @@ export const UserInfo: React.FC<UserInfoProps> = ({
// 비회원인 경우
if (actualIsGuest || !actualUserId) {
return (
<Div className={containerClass}>
<Div className={containerClass} id={id} {...editorAttrs}>
<Div className="flex items-center gap-1.5 text-gray-400 dark:text-gray-500">
<Span>{actualName}</Span>
<Span className="text-xs px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded">
@@ -380,7 +392,7 @@ export const UserInfo: React.FC<UserInfoProps> = ({
// 탈퇴한 사용자인 경우
if (actualIsWithdrawn) {
return (
<Div className={containerClass}>
<Div className={containerClass} id={id} {...editorAttrs}>
<Span className="text-gray-400 dark:text-gray-500 line-through">
{actualName}
</Span>
@@ -399,7 +411,7 @@ export const UserInfo: React.FC<UserInfoProps> = ({
: `${defaultColorClass} font-medium`.trim();
return (
<Div ref={containerRef} className={`relative inline-block ${className}`}>
<Div ref={containerRef} className={`relative inline-block ${className}`} id={id} {...editorAttrs}>
<Div className={LAYOUT_CLASSES[layout]}>
<Button
ref={buttonRef}
@@ -0,0 +1,90 @@
/**
* Footer 반응형 회귀 테스트
*
* 정책: 레이아웃 편집 가능 템플릿은 G7 표준 responsive(useResponsive) 만 사용한다.
* Footer 는 Tailwind md:/lg:/sm: 미디어쿼리 대신 useResponsive().width 기반으로
* 그리드 컬럼/flex 방향을 분기해야 위지윅 프리뷰 디바이스 전환(overrideWidth)에
* 정상 반응한다. 본 테스트는 width 별 분기를 가드한다.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render } from '@testing-library/react';
import Footer from '../Footer';
function mockResponsive(width: number) {
return vi.fn(() => ({
width,
isMobile: width < 768,
isTablet: width >= 768 && width < 1024,
isDesktop: width >= 1024,
matchedPreset: (width < 768 ? 'mobile' : width < 1024 ? 'tablet' : 'desktop') as
| 'mobile'
| 'tablet'
| 'desktop',
}));
}
describe('Footer — G7 표준 responsive 분기', () => {
let originalG7Core: any;
function setWidth(width: number) {
originalG7Core = (window as any).G7Core;
(window as any).G7Core = {
...originalG7Core,
useResponsive: mockResponsive(width),
t: (k: string) => k,
};
}
afterEach(() => {
(window as any).G7Core = originalG7Core;
vi.clearAllMocks();
});
it('데스크톱(1280) — 링크 그룹 그리드 5열', () => {
setWidth(1280);
const { container } = render(<Footer />);
const grid = container.querySelector('.grid') as HTMLElement;
expect(grid).toBeTruthy();
expect(grid.style.gridTemplateColumns).toBe('repeat(5, minmax(0, 1fr))');
});
it('태블릿(820) — 그리드 2열', () => {
setWidth(820);
const { container } = render(<Footer />);
const grid = container.querySelector('.grid') as HTMLElement;
expect(grid.style.gridTemplateColumns).toBe('repeat(2, minmax(0, 1fr))');
});
it('모바일(390) — 그리드 1열 + 저작권 영역 세로(column)', () => {
setWidth(390);
const { container } = render(<Footer />);
const grid = container.querySelector('.grid') as HTMLElement;
expect(grid.style.gridTemplateColumns).toBe('repeat(1, minmax(0, 1fr))');
// 저작권 영역 flexDirection = column (모바일)
const cols = Array.from(container.querySelectorAll('div')).filter(
(d) => d.style.flexDirection === 'column'
);
expect(cols.length).toBeGreaterThan(0);
});
it('데스크톱 — 저작권 영역 flexDirection row', () => {
setWidth(1280);
const { container } = render(<Footer />);
const rows = Array.from(container.querySelectorAll('div')).filter(
(d) => d.style.flexDirection === 'row'
);
expect(rows.length).toBeGreaterThan(0);
});
it('Footer 마크업에 Tailwind 반응형 그리드 클래스(md:grid-cols / lg:grid-cols)를 사용하지 않음', () => {
setWidth(1280);
const { container } = render(<Footer />);
const html = container.innerHTML;
// 정책: 편집 가능 템플릿은 viewport 미디어쿼리 그리드/flex 분기 금지
expect(html).not.toContain('md:grid-cols');
expect(html).not.toContain('lg:grid-cols');
expect(html).not.toContain('sm:flex-row');
});
});
@@ -0,0 +1,114 @@
// e2e:allow Vitest 컴포넌트 렌더 테스트(편집기 속성→실제 Header prop 렌더 검증). 편집기 캔버스 통합은 Chrome MCP 라이브 실측으로 별도 검증.
/**
* @file HeaderPropRender.test.tsx
* @description 실제 Header 컴포넌트 prop 렌더링 검증.
*
* 기존 Header.test.tsx 는 MockHeader(가짜)로 구조만 본다. 본 스위트는 실제 Header.tsx 를
* 렌더해 editor-spec 으로 노출한 핵심 prop(siteName / logo / maxVisibleBoards / shopBase /
* availableLocales / currentLocale)이 실제 출력 DOM·동작에 반영됨을 검증한다.
*
* 데스크톱 폭으로 useResponsive 를 모킹해 데스크톱 헤더 분기(검색바·언어 선택기·게시판 탭)를
* 렌더한다.
*
* @vitest-environment jsdom
*/
import React from 'react';
import { render, screen, within } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Header from '../Header';
const navigate = vi.fn();
beforeEach(() => {
(window as any).G7Core = {
t: (key: string, params?: Record<string, unknown>) => {
const map: Record<string, string> = {
'common.search_placeholder': '검색어를 입력하세요...',
'common.language': '언어',
};
return map[key] ?? key;
},
// 데스크톱 폭 — 검색바/언어선택기/게시판 탭 데스크톱 분기 렌더
useResponsive: () => ({ width: 1280, breakpoint: 'desktop' }),
dispatch: vi.fn((action: any) => {
if (action?.handler === 'navigate') navigate(action?.params?.path);
}),
state: { getLocal: () => ({}), getGlobal: () => ({}) },
getSlotContext: () => ({
getSlotComponents: () => [],
subscribeToSlot: () => () => {},
isEnabled: true,
}),
};
(window as any).__slotContextValue = (window as any).G7Core.getSlotContext();
});
afterEach(() => {
vi.clearAllMocks();
delete (window as any).G7Core;
delete (window as any).__slotContextValue;
});
const boards = [
{ id: 1, table_id: 'free', subject: '자유게시판', name: '자유게시판' },
{ id: 2, table_id: 'qa', subject: '질문답변', name: '질문답변' },
{ id: 3, table_id: 'notice', subject: '공지사항', name: '공지사항' },
{ id: 4, table_id: 'review', subject: '후기', name: '후기' },
];
describe('Header prop 렌더링 — 편집기 속성이 사용자 화면에 반영', () => {
it('siteName prop 이 로고 영역 텍스트로 렌더된다 (logo 없을 때)', () => {
render(<Header siteName="우리 사이트" availableLocales={['ko', 'en']} currentLocale="ko" />);
expect(screen.getByText('우리 사이트')).toBeInTheDocument();
});
it('logo prop 이 있으면 img 의 src/alt 로 렌더된다', () => {
render(
<Header siteName="우리 사이트" logo="/custom-logo.png" availableLocales={['ko', 'en']} currentLocale="ko" />,
);
const img = screen.getByAltText('우리 사이트') as HTMLImageElement;
expect(img).toBeInTheDocument();
expect(img.getAttribute('src')).toBe('/custom-logo.png');
});
it('maxVisibleBoards prop 이 탭에 표시되는 게시판 수를 제한한다', () => {
const { container } = render(
<Header
siteName="S"
boards={boards as any}
maxVisibleBoards={2}
availableLocales={['ko', 'en']}
currentLocale="ko"
/>,
);
// 처음 2개 게시판은 탭으로 노출, 나머지는 "더보기" 뒤로 숨김
const nav = container.querySelector('nav');
expect(nav).not.toBeNull();
const navText = nav!.textContent ?? '';
expect(navText).toContain('자유게시판');
expect(navText).toContain('질문답변');
});
it('availableLocales 가 2개 이상이면 언어 선택기(현재 로케일 코드)가 렌더된다', () => {
render(<Header siteName="S" availableLocales={['ko', 'en']} currentLocale="en" />);
// 현재 로케일 코드가 uppercase 로 트리거에 표시
expect(screen.getByText('en')).toBeInTheDocument();
});
it('availableLocales 가 1개 이하이면 언어 선택기가 렌더되지 않는다', () => {
const { container } = render(<Header siteName="S" availableLocales={['ko']} currentLocale="ko" />);
// globe 아이콘(언어 트리거)이 없어야 함
const langTrigger = container.querySelector('[aria-label="언어"]');
expect(langTrigger).toBeNull();
});
it('header_currency 슬롯 컨테이너가 렌더된다 (모듈 통화 셀렉터 주입 지점)', () => {
// SlotContainer 는 빈 슬롯이면 null 이지만, 컴포넌트가 마운트되어 슬롯을 구독해야 한다.
// 슬롯 등록분이 생기면 즉시 렌더되도록 SlotContext 구독이 성립함을 보장(번들 포함 회귀 차단은
// headerEditorSpecAndCurrencySlot.test 가 담당). 여기서는 렌더가 throw 없이 완료됨을 확인.
expect(() =>
render(<Header siteName="S" availableLocales={['ko', 'en']} currentLocale="ko" />),
).not.toThrow();
});
});
@@ -0,0 +1,83 @@
/**
* ImageGallery 편집 모드 placeholder 회귀 테스트
*
* ImageGallery 는 서드파티 Lightbox 모달(isOpen=false 시 DOM 미렌더)이라 편집기
* 캔버스에서 선택·편집이 불가능했다(6 propControl 도달 불가). 편집 모드(editorAttrs
* 주입) 에서는 인라인 placeholder(썸네일 그리드)를 대신 렌더해 editorAttrs·id 를
* 부착하도록 보강했다. 본 테스트는 그 동작을 잠근다.
*/
import React from 'react';
import { render } from '@testing-library/react';
import { describe, it, expect, beforeEach } from 'vitest';
import { ImageGallery } from '../ImageGallery';
// G7Core.t mock (편집 모드 placeholder 라벨 + basic 컴포넌트 의존)
beforeEach(() => {
(window as any).G7Core = {
t: (key: string) => key,
};
});
const editorAttrs = {
'data-editor-id': 'auto_ImageGallery_test',
'data-editor-name': 'ImageGallery',
'data-editor-type': 'composite',
'data-editor-path': '3',
} as Record<string, string>;
const sampleImages = [
{ src: 'https://example.com/a.jpg', title: '이미지 A' },
{ src: 'https://example.com/b.jpg', title: '이미지 B', thumbnail: 'https://example.com/b-thumb.jpg' },
];
describe('ImageGallery 편집 모드 placeholder', () => {
it('editorAttrs 주입 시 인라인 placeholder 루트에 editorAttrs 와 id 가 부착된다', () => {
const { container } = render(
<ImageGallery
images={sampleImages}
isOpen={false}
onClose={() => {}}
id="ig-edit"
editorAttrs={editorAttrs}
/>
);
const node = container.querySelector('[data-editor-name="ImageGallery"]');
expect(node, '편집 모드에서 인라인 placeholder 가 렌더되어야 함').not.toBeNull();
expect(node).toHaveAttribute('data-editor-path', '3');
expect(node).toHaveAttribute('id', 'ig-edit');
});
it('editorAttrs 주입 시 이미지 썸네일이 placeholder 에 렌더된다 (썸네일 우선)', () => {
const { container } = render(
<ImageGallery
images={sampleImages}
isOpen={false}
onClose={() => {}}
editorAttrs={editorAttrs}
/>
);
const imgs = container.querySelectorAll('img');
expect(imgs.length).toBe(2);
// 두 번째 이미지는 thumbnail 우선
expect(imgs[1]).toHaveAttribute('src', 'https://example.com/b-thumb.jpg');
});
it('이미지가 없으면 placeholder 안내 라벨을 렌더한다', () => {
const { container } = render(
<ImageGallery images={[]} isOpen={false} onClose={() => {}} editorAttrs={editorAttrs} />
);
const node = container.querySelector('[data-editor-name="ImageGallery"]');
expect(node).not.toBeNull();
expect(node?.textContent).toContain('editor.component.image_gallery');
});
it('editorAttrs 미주입(런타임)이면 인라인 placeholder 를 렌더하지 않는다', () => {
const { container } = render(
<ImageGallery images={sampleImages} isOpen={false} onClose={() => {}} />
);
// 런타임 경로 — placeholder div(data-editor-name) 가 없어야 함
const node = container.querySelector('[data-editor-name="ImageGallery"]');
expect(node).toBeNull();
});
});
@@ -5,7 +5,7 @@
*/
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { render, screen, fireEvent, act } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import ProductCard from '../ProductCard';
@@ -471,6 +471,119 @@ describe('ProductCard 컴포넌트', () => {
});
});
describe('다중 통화 표시 (선택 통화 환산)', () => {
const multiCurrencyProduct = {
id: 7,
name_localized: '면 손수건',
thumbnail_url: '/img/handkerchief.jpg',
selling_price: 3000,
selling_price_formatted: '3,000원',
list_price: 5000,
list_price_formatted: '5,000원',
discount_rate: 40,
multi_currency_selling_price: {
KRW: { value: 3000, formatted: '3,000원' },
USD: { value: 2.55, formatted: '$2.55' },
JPY: { value: 345, formatted: '¥345' },
},
multi_currency_list_price: {
KRW: { value: 5000, formatted: '5,000원' },
USD: { value: 4.25, formatted: '$4.25' },
JPY: { value: 575, formatted: '¥575' },
},
};
/**
* 실 환경처럼 G7Core.state.get() 은 인자(key)를 무시하고 _global 전체 객체를 반환한다.
* (G7CoreGlobals.ts: get: () => templateApp.getGlobalState())
* ProductCard 가 키 접근/구독을 올바로 하지 않으면 이 mock 에서 KRW 폴백으로 회귀한다.
*/
const installGlobalState = (preferredCurrency: string) => {
const listeners: Array<(s: any) => void> = [];
const state = { preferredCurrency };
(window as any).__templateApp = {
getGlobalState: () => state,
onGlobalStateChange: (l: (s: any) => void) => {
listeners.push(l);
return () => {
const i = listeners.indexOf(l);
if (i >= 0) listeners.splice(i, 1);
};
},
};
(window as any).G7Core = {
...mockG7Core,
state: {
get: () => state, // key 무시, 전체 객체 반환 (실 동작)
set: (updates: Record<string, any>) => {
Object.assign(state, updates);
listeners.forEach((l) => l(state));
},
subscribe: (l: (s: any) => void) => {
listeners.push(l);
return () => {
const i = listeners.indexOf(l);
if (i >= 0) listeners.splice(i, 1);
};
},
},
};
};
it('USD 선택 시 판매가/정가가 USD 로 표시되어야 함 (KRW 고정 회귀 차단)', () => {
installGlobalState('USD');
render(<ProductCard product={multiCurrencyProduct} />);
expect(screen.getByText('$2.55')).toBeInTheDocument();
expect(screen.getByText('$4.25')).toBeInTheDocument();
expect(screen.queryByText('3,000원')).not.toBeInTheDocument();
expect(screen.queryByText('5,000원')).not.toBeInTheDocument();
});
it('JPY 선택 시 JPY 로 표시되어야 함', () => {
installGlobalState('JPY');
render(<ProductCard product={multiCurrencyProduct} />);
expect(screen.getByText('¥345')).toBeInTheDocument();
expect(screen.getByText('¥575')).toBeInTheDocument();
});
it('KRW(기본) 선택 시 KRW 로 표시되어야 함', () => {
installGlobalState('KRW');
render(<ProductCard product={multiCurrencyProduct} />);
expect(screen.getByText('3,000원')).toBeInTheDocument();
expect(screen.getByText('5,000원')).toBeInTheDocument();
});
it('통화를 USD 로 변경하면 리렌더되어 USD 로 갱신되어야 함 (반응성 회귀 차단)', async () => {
installGlobalState('KRW');
render(<ProductCard product={multiCurrencyProduct} />);
expect(screen.getByText('3,000원')).toBeInTheDocument();
// 헤더에서 통화 변경 → 전역 상태 갱신 (set 이 구독자에게 통지)
await act(async () => {
(window as any).G7Core.state.set({ preferredCurrency: 'USD' });
});
expect(screen.getByText('$2.55')).toBeInTheDocument();
expect(screen.queryByText('3,000원')).not.toBeInTheDocument();
});
it('multi_currency 데이터가 없으면 기본 포맷(_formatted)으로 폴백해야 함', () => {
installGlobalState('USD');
render(
<ProductCard
product={{
id: 8,
name_localized: '단순 상품',
thumbnail_url: '/img/x.jpg',
selling_price: 10000,
selling_price_formatted: '10,000원',
}}
/>
);
expect(screen.getByText('10,000원')).toBeInTheDocument();
});
});
describe('검색 하이라이트', () => {
const highlightedProduct: Product = {
...mockProduct,
@@ -210,6 +210,30 @@ describe('TabNavigation 컴포넌트', () => {
expect(trigger).toBeInTheDocument();
});
// 회귀: 모바일 분기 루트에도 id/editorAttrs 가
// spread 되어야 레이아웃 편집기가 모바일 디바이스 미리보기에서 이 노드를 선택/측정할 수
// 있다. 종전 모바일 분기는 데스크톱 분기와 달리 id/editorAttrs 누락 → 모바일 프리뷰에서
// data-editor-* 가 사라져 캔버스 선택 불가(모든 렌더 분기 editorAttrs 패리티 규율).
it('모바일 분기 루트에도 id/editorAttrs(data-editor-*)가 spread 되어야 함', () => {
const { container } = render(
<TabNavigation
tabs={defaultTabs}
activeTabId="detail"
id="mypageTabNavigation"
editorAttrs={{
'data-editor-path': '2.children.1',
'data-editor-name': 'TabNavigation',
'data-editor-type': 'composite',
} as any}
/>
);
const root = container.firstElementChild as HTMLElement;
expect(root).toBeTruthy();
expect(root.id).toBe('mypageTabNavigation');
expect(root.getAttribute('data-editor-path')).toBe('2.children.1');
expect(root.getAttribute('data-editor-name')).toBe('TabNavigation');
});
it('현재 활성 탭의 label을 Select trigger에 표시해야 함', () => {
render(<TabNavigation tabs={defaultTabs} activeTabId="detail" />);
@@ -422,3 +422,55 @@ describe('UserInfo 드롭다운 위치 (fixed 배치)', () => {
expect(screen.queryByTestId('author-dropdown-menu')).not.toBeInTheDocument();
});
});
// #1 회귀: UserInfo 의 비회원/탈퇴 분기 렌더가
// editorAttrs(data-editor-*) 와 id 를 루트에 전달해야 한다. 누락 시 레이아웃 편집기에서
// isGuest/isWithdrawn 상태의 UserInfo 가 캔버스에서 선택·편집 불가(데이터 결정 노드처럼
// data-editor-name 미부착). 회원 분기는 이미 전달하므로 세 분기 모두 패리티를 보장한다.
describe('UserInfo 편집기 패스스루 (editorAttrs/id) — 전 분기 패리티', () => {
const editorAttrs = {
'data-editor-id': 'auto_UserInfo_test',
'data-editor-name': 'UserInfo',
'data-editor-type': 'composite',
'data-editor-path': '3',
} as Record<string, string>;
it('비회원 분기 루트에 editorAttrs 와 id 가 전달되어야 함', () => {
const { container } = render(
<UserInfo name="익명" isGuest id="ui-guest" editorAttrs={editorAttrs} />
);
const node = container.querySelector('[data-editor-name="UserInfo"]');
expect(node).not.toBeNull();
expect(node).toHaveAttribute('data-editor-path', '3');
expect(node).toHaveAttribute('id', 'ui-guest');
});
it('탈퇴 회원 분기 루트에 editorAttrs 와 id 가 전달되어야 함', () => {
const { container } = render(
<UserInfo
author={{ id: 1, uuid: 'u1', name: '탈퇴자', status: 'withdrawn' }}
isWithdrawn
id="ui-withdrawn"
editorAttrs={editorAttrs}
/>
);
const node = container.querySelector('[data-editor-name="UserInfo"]');
expect(node).not.toBeNull();
expect(node).toHaveAttribute('data-editor-path', '3');
expect(node).toHaveAttribute('id', 'ui-withdrawn');
});
it('회원 분기 루트에도 editorAttrs 와 id 가 전달되어야 함 (패리티 기준)', () => {
const { container } = render(
<UserInfo
author={{ id: 1, uuid: 'u1', name: '홍길동' }}
id="ui-member"
editorAttrs={editorAttrs}
/>
);
const node = container.querySelector('[data-editor-name="UserInfo"]');
expect(node).not.toBeNull();
expect(node).toHaveAttribute('data-editor-path', '3');
expect(node).toHaveAttribute('id', 'ui-member');
});
});
@@ -1,3 +1,4 @@
// e2e:allow 편집기 ComponentRegistry 등록맵에 SlotContainer 추가(편집기 IIFE 번들 포함 — 헤더 통화 슬롯 렌더). 편집기 캔버스 렌더는 Chrome MCP 라이브 실측 + Vitest 로 검증. 사용자 사이트 런타임 무변경.
/**
* sirsoft-basic 템플릿 Composite 컴포넌트 등록
*
@@ -44,6 +45,7 @@ export { AvatarUploader } from './AvatarUploader';
export { UserInfo } from './UserInfo';
export { Modal } from './Modal';
export { TabNavigation } from './TabNavigation';
export { SlotContainer } from './SlotContainer';
// AddressSearch는 별도 컴포넌트가 아닌 sirsoft-daum_postcode 플러그인의 extension_point 방식 사용
/**
@@ -65,6 +67,10 @@ export const compositeComponents = {
Header: () => import('./Header'),
Footer: () => import('./Footer'),
MobileNav: () => import('./MobileNav'),
// 슬롯 컨테이너 — 모듈 주입 UI(헤더 통화 셀렉터 등)를 떙겨 렌더. 등록맵 누락 시
// 편집기 캔버스 IIFE 번들에 포함되지 않아 "Component not found in bundle" 로 렌더 실패한다
// (운영 사이트는 별도 등록 경로라 정상이나 편집기 미리보기에서만 슬롯이 통째로 비는 회귀).
SlotContainer: () => import('./SlotContainer'),
NotificationCenter: () => import('./NotificationCenter'),
// 상품
@@ -1,5 +1,6 @@
import React from 'react';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface ContainerProps {
/**
@@ -21,6 +22,11 @@ export interface ContainerProps {
* 자식 요소
*/
children?: React.ReactNode;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -33,9 +39,10 @@ export const Container: React.FC<ContainerProps> = ({
className,
style,
children,
editorAttrs,
}) => {
return (
<Div id={id} className={className} style={style}>
<Div id={id} className={className} style={style} {...editorAttrs}>
{children}
</Div>
);
@@ -1,7 +1,13 @@
import React from 'react';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface FlexProps {
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* Flex 방향
*/
@@ -56,6 +62,11 @@ export interface FlexProps {
* 클릭 이벤트 핸들러
*/
onClick?: () => void;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -79,6 +90,7 @@ export interface FlexProps {
* </Flex>
*/
export const Flex: React.FC<FlexProps> = ({
id,
children,
direction = 'row',
justify = 'start',
@@ -90,6 +102,7 @@ export const Flex: React.FC<FlexProps> = ({
className = '',
style,
onClick,
editorAttrs,
}) => {
// Tailwind CSS 클래스 생성
const classes: string[] = ['flex'];
@@ -159,7 +172,7 @@ export const Flex: React.FC<FlexProps> = ({
}
return (
<Div className={classes.join(' ')} style={style} onClick={onClick}>
<Div id={id} className={classes.join(' ')} style={style} onClick={onClick} {...editorAttrs}>
{children}
</Div>
);
@@ -1,7 +1,13 @@
import React from 'react';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface GridProps {
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* Grid 열 개수
*/
@@ -67,6 +73,11 @@ export interface GridProps {
* 클릭 이벤트 핸들러
*/
onClick?: () => void;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -95,6 +106,7 @@ export interface GridProps {
* </Grid>
*/
export const Grid: React.FC<GridProps> = ({
id,
children,
cols = 1,
responsive,
@@ -107,6 +119,7 @@ export const Grid: React.FC<GridProps> = ({
className = '',
style,
onClick,
editorAttrs,
}) => {
// Tailwind CSS 클래스 생성
const classes: string[] = ['grid'];
@@ -178,7 +191,7 @@ export const Grid: React.FC<GridProps> = ({
}
return (
<Div className={classes.join(' ')} style={style} onClick={onClick}>
<Div id={id} className={classes.join(' ')} style={style} onClick={onClick} {...editorAttrs}>
{children}
</Div>
);
@@ -3,8 +3,14 @@ import { Section as BaseSection } from '../basic/Section';
import { Div } from '../basic/Div';
import { H2 } from '../basic/H2';
import { P } from '../basic/P';
import type { EditorAttrs } from '../../types';
export interface SectionLayoutProps {
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 섹션 제목
*/
@@ -69,6 +75,11 @@ export interface SectionLayoutProps {
* 클릭 이벤트 핸들러
*/
onClick?: () => void;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -95,6 +106,7 @@ export interface SectionLayoutProps {
* </Section>
*/
export const SectionLayout: React.FC<SectionLayoutProps> = ({
id,
title,
subtitle,
children,
@@ -108,6 +120,7 @@ export const SectionLayout: React.FC<SectionLayoutProps> = ({
className = '',
style,
onClick,
editorAttrs,
}) => {
// Tailwind CSS 클래스 생성
const classes: string[] = [];
@@ -183,7 +196,7 @@ export const SectionLayout: React.FC<SectionLayoutProps> = ({
}
return (
<BaseSection className={classes.join(' ')} style={style} onClick={onClick}>
<BaseSection id={id} className={classes.join(' ')} style={style} onClick={onClick} {...editorAttrs}>
{/* 제목 영역 */}
{(title || subtitle) && (
<Div className="mb-4">
@@ -1,7 +1,13 @@
import React from 'react';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface ThreeColumnLayoutProps {
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 왼쪽 영역 너비
*/
@@ -36,6 +42,11 @@ export interface ThreeColumnLayoutProps {
* 인라인 스타일
*/
style?: React.CSSProperties;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -54,6 +65,7 @@ export interface ThreeColumnLayoutProps {
* />
*/
export const ThreeColumnLayout: React.FC<ThreeColumnLayoutProps> = ({
id,
leftWidth = '250px',
rightWidth = '300px',
leftSlot,
@@ -61,6 +73,7 @@ export const ThreeColumnLayout: React.FC<ThreeColumnLayoutProps> = ({
rightSlot,
className = '',
style,
editorAttrs,
}) => {
// 컨테이너 스타일
const containerClasses = `flex flex-row w-full h-full ${className}`.trim();
@@ -84,7 +97,7 @@ export const ThreeColumnLayout: React.FC<ThreeColumnLayoutProps> = ({
};
return (
<Div className={containerClasses} style={style}>
<Div id={id} className={containerClasses} style={style} {...editorAttrs}>
{/* 왼쪽 영역 */}
<Div className="flex flex-col" style={leftStyle}>
{leftSlot}