- BusinessNameInputModal에 선택 입력 URL 필드 추가 (프로토콜 미입력 시 https:// 보정) - onManualInput 콜백 체인(officialSiteUrl) 확장 - POST /marketing 요청 body에 official_site_url 전달 (미입력 시 null) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DKTAqpFj8pbWzgvq7MRDHk
354 lines
13 KiB
TypeScript
354 lines
13 KiB
TypeScript
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { searchAccommodation, cleanSearchTitle, AccommodationSearchItem, AutocompleteRequest } from '../utils/api';
|
|
import { useSearchHistory } from './SearchHistory/useSearchHistory';
|
|
import SearchHistoryDropdown from './SearchHistory/SearchHistoryDropdown';
|
|
import BusinessNameInputModal from './BusinessNameInputModal';
|
|
|
|
type SearchType = 'url' | 'name' | 'manual';
|
|
|
|
export type { SearchType };
|
|
|
|
const isValidUrl = (string: string): boolean => {
|
|
try {
|
|
const url = new URL(string);
|
|
return url.protocol === 'http:' || url.protocol === 'https:';
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
// URL 형태로 판단되는 입력: 프로토콜/www. 시작 또는 도메인 형태(naver.me/xxx 등)
|
|
const isUrlLike = (value: string): boolean => {
|
|
const trimmed = value.trim();
|
|
return /^(https?:\/\/|www\.)/i.test(trimmed)
|
|
|| /^[a-z0-9-]+(\.[a-z0-9-]+)+([/?#]|$)/i.test(trimmed);
|
|
};
|
|
|
|
const sanitizeUrlInput = (value: string): string => {
|
|
return value.replace(/[^\x00-\x7F]/g, '');
|
|
};
|
|
|
|
// 텍스트 안에 포함된 첫 번째 URL을 추출 (없으면 null)
|
|
const extractUrl = (text: string): string | null => {
|
|
const match = text.match(/(https?:\/\/|www\.)[^\s]+/i);
|
|
return match ? match[0] : null;
|
|
};
|
|
|
|
interface SearchInputFormProps {
|
|
onAnalyze?: (value: string, type: SearchType) => void;
|
|
onAutocomplete?: (data: AutocompleteRequest) => void;
|
|
onManualInput?: (businessName: string, address: string, category: string, officialSiteUrl?: string) => void;
|
|
/** 직접입력 버튼 클릭 시 기본 동작(모달 열기)을 대체합니다. 제공 시 모달을 직접 관리해야 합니다. */
|
|
onManualButtonClick?: () => void;
|
|
error?: string | null;
|
|
}
|
|
|
|
const SearchInputForm: React.FC<SearchInputFormProps> = ({
|
|
onAnalyze,
|
|
onAutocomplete,
|
|
onManualInput,
|
|
onManualButtonClick,
|
|
error: externalError,
|
|
}) => {
|
|
const { t } = useTranslation();
|
|
const [inputValue, setInputValue] = useState('');
|
|
const [searchType] = useState<SearchType>('name');
|
|
const [isFocused, setIsFocused] = useState(false);
|
|
const [isManualModalOpen, setIsManualModalOpen] = useState(false);
|
|
const [localError, setLocalError] = useState('');
|
|
const [autocompleteResults, setAutocompleteResults] = useState<AccommodationSearchItem[]>([]);
|
|
const [isAutocompleteLoading, setIsAutocompleteLoading] = useState(false);
|
|
const [showAutocomplete, setShowAutocomplete] = useState(false);
|
|
const [selectedItem, setSelectedItem] = useState<AccommodationSearchItem | null>(null);
|
|
const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
|
|
|
|
const { filteredHistory, showHistory, openHistory, closeHistory, hideOnInput, deleteItem } = useSearchHistory('name');
|
|
const debounceRef = useRef<NodeJS.Timeout | null>(null);
|
|
const autocompleteRef = useRef<HTMLDivElement>(null);
|
|
|
|
useEffect(() => {
|
|
const handleClickOutside = (event: MouseEvent) => {
|
|
if (autocompleteRef.current && !autocompleteRef.current.contains(event.target as Node)) {
|
|
setShowAutocomplete(false);
|
|
}
|
|
};
|
|
document.addEventListener('mousedown', handleClickOutside);
|
|
return () => document.removeEventListener('mousedown', handleClickOutside);
|
|
}, []);
|
|
|
|
const handleAutocompleteSearch = useCallback(async (query: string) => {
|
|
if (!query.trim()) {
|
|
setAutocompleteResults([]);
|
|
setShowAutocomplete(false);
|
|
return;
|
|
}
|
|
setIsAutocompleteLoading(true);
|
|
try {
|
|
const response = await searchAccommodation(query);
|
|
setAutocompleteResults(response.items || []);
|
|
setShowAutocomplete(response.items && response.items.length > 0);
|
|
} catch {
|
|
setAutocompleteResults([]);
|
|
setShowAutocomplete(false);
|
|
} finally {
|
|
setIsAutocompleteLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
const handleSelectAutocomplete = (item: AccommodationSearchItem) => {
|
|
const cleanTitle = cleanSearchTitle(item.title);
|
|
setInputValue(cleanTitle);
|
|
setSelectedItem({ ...item, title: cleanTitle });
|
|
setShowAutocomplete(false);
|
|
setAutocompleteResults([]);
|
|
setHighlightedIndex(-1);
|
|
};
|
|
|
|
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
|
if (showAutocomplete && autocompleteResults.length > 0) {
|
|
switch (e.key) {
|
|
case 'ArrowDown':
|
|
e.preventDefault();
|
|
setHighlightedIndex(prev => prev < autocompleteResults.length - 1 ? prev + 1 : 0);
|
|
return;
|
|
case 'ArrowUp':
|
|
e.preventDefault();
|
|
setHighlightedIndex(prev => prev > 0 ? prev - 1 : autocompleteResults.length - 1);
|
|
return;
|
|
case 'Enter':
|
|
e.preventDefault();
|
|
if (highlightedIndex >= 0 && highlightedIndex < autocompleteResults.length) {
|
|
handleSelectAutocomplete(autocompleteResults[highlightedIndex]);
|
|
}
|
|
return;
|
|
case 'Escape':
|
|
e.preventDefault();
|
|
setShowAutocomplete(false);
|
|
setHighlightedIndex(-1);
|
|
return;
|
|
}
|
|
}
|
|
if (e.key === 'Enter') {
|
|
e.preventDefault();
|
|
}
|
|
};
|
|
|
|
const handleStart = () => {
|
|
const trimmed = inputValue.trim();
|
|
if (!trimmed) {
|
|
setLocalError(t('landing.hero.errorInputRequired'));
|
|
return;
|
|
}
|
|
if (isValidUrl(trimmed)) {
|
|
setLocalError('');
|
|
onAnalyze?.(trimmed, 'url');
|
|
return;
|
|
}
|
|
|
|
setLocalError('');
|
|
|
|
if (selectedItem && onAutocomplete) {
|
|
onAutocomplete({
|
|
address: selectedItem.address,
|
|
roadAddress: selectedItem.roadAddress,
|
|
title: selectedItem.title,
|
|
});
|
|
} else if (onAnalyze) {
|
|
onAnalyze(inputValue, searchType);
|
|
}
|
|
};
|
|
|
|
const applyInputChange = (value: string) => {
|
|
setInputValue(value);
|
|
setSelectedItem(null);
|
|
setHighlightedIndex(-1);
|
|
hideOnInput(value);
|
|
if (localError) setLocalError('');
|
|
if (debounceRef.current) clearTimeout(debounceRef.current);
|
|
if (isValidUrl(value)) {
|
|
setAutocompleteResults([]);
|
|
setShowAutocomplete(false);
|
|
} else {
|
|
debounceRef.current = setTimeout(() => handleAutocompleteSearch(value), 300);
|
|
}
|
|
};
|
|
|
|
// 모바일 키보드 클립보드 추천 등 paste 이벤트 없이 여러 글자가 한 번에 들어오는 경우 처리
|
|
const handleChange = (value: string) => {
|
|
const isBulkInsert = value.length - inputValue.length > 1;
|
|
if (isBulkInsert) {
|
|
const extracted = extractUrl(value);
|
|
if (extracted && extracted !== value.trim()) {
|
|
applyInputChange(sanitizeUrlInput(extracted));
|
|
return;
|
|
}
|
|
if (isUrlLike(value)) {
|
|
const sanitized = sanitizeUrlInput(value);
|
|
if (sanitized !== value) {
|
|
applyInputChange(sanitized);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
applyInputChange(value);
|
|
};
|
|
|
|
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
|
const pastedText = e.clipboardData.getData('text');
|
|
|
|
// 붙여넣은 텍스트에 URL이 포함되어 있고 URL 외 다른 텍스트도 있으면 URL만 추출해서 입력창에 넣기
|
|
const extracted = extractUrl(pastedText);
|
|
if (extracted && extracted !== pastedText.trim()) {
|
|
e.preventDefault();
|
|
applyInputChange(sanitizeUrlInput(extracted));
|
|
return;
|
|
}
|
|
|
|
const input = e.currentTarget;
|
|
const start = input.selectionStart ?? inputValue.length;
|
|
const end = input.selectionEnd ?? inputValue.length;
|
|
const merged = inputValue.slice(0, start) + pastedText + inputValue.slice(end);
|
|
|
|
// 붙여넣은 후 완성될 전체 값이 URL 형태일 때만 비영문 문자 제거
|
|
if (!isUrlLike(merged)) return;
|
|
|
|
const sanitized = sanitizeUrlInput(merged);
|
|
if (sanitized === merged) return;
|
|
|
|
e.preventDefault();
|
|
applyInputChange(sanitized);
|
|
};
|
|
|
|
const handleManualButtonClick = () => {
|
|
if (onManualButtonClick) {
|
|
onManualButtonClick();
|
|
} else {
|
|
setIsManualModalOpen(true);
|
|
}
|
|
};
|
|
|
|
const error = externalError || localError;
|
|
|
|
return (
|
|
<div className="hero-form">
|
|
<div className={`hero-input-wrapper ${isFocused ? 'focused' : ''} ${error ? 'error' : ''} ${inputValue && !isFocused ? 'filled' : ''}`}>
|
|
{/* 유형 라벨 */}
|
|
{/* <div className="hero-dropdown-container">
|
|
<div className="hero-dropdown-trigger">
|
|
<span className="hero-dropdown-main">
|
|
{t('landing.hero.searchTypeLabel')}
|
|
</span>
|
|
</div>
|
|
</div> */}
|
|
|
|
{/* 입력 필드 */}
|
|
<div className="hero-input-container" ref={autocompleteRef}>
|
|
<input
|
|
type="text"
|
|
value={inputValue}
|
|
onChange={(e) => handleChange(e.target.value)}
|
|
onPaste={handlePaste}
|
|
onFocus={() => {
|
|
setIsFocused(true);
|
|
if (autocompleteResults.length > 0) setShowAutocomplete(true);
|
|
openHistory(inputValue);
|
|
}}
|
|
onBlur={() => { setIsFocused(false); setTimeout(() => closeHistory(), 150); }}
|
|
onKeyDown={handleKeyDown}
|
|
placeholder={t('landing.hero.placeholderCombined')}
|
|
className={`hero-input ${inputValue ? 'has-value' : ''}`}
|
|
/>
|
|
|
|
{/* 최근 검색 히스토리 */}
|
|
{showHistory && !showAutocomplete && (
|
|
<SearchHistoryDropdown
|
|
items={filteredHistory}
|
|
onSelect={(item) => {
|
|
closeHistory();
|
|
setInputValue(item.value);
|
|
if (item.type === 'name') {
|
|
setSelectedItem({ title: item.value, address: item.address || '', roadAddress: item.roadAddress || '' });
|
|
}
|
|
}}
|
|
onDelete={(e, value) => { e.preventDefault(); e.stopPropagation(); deleteItem(value); }}
|
|
className="hero-autocomplete-dropdown"
|
|
itemClassName="hero-autocomplete-item"
|
|
titleClassName="hero-autocomplete-title"
|
|
addressClassName="hero-autocomplete-address"
|
|
/>
|
|
)}
|
|
|
|
{/* 자동완성 결과 */}
|
|
{showAutocomplete && (
|
|
<div className="hero-autocomplete-dropdown">
|
|
{isAutocompleteLoading ? (
|
|
<div className="hero-autocomplete-loading">{t('landing.hero.searching')}</div>
|
|
) : (
|
|
autocompleteResults.map((item, index) => (
|
|
<button
|
|
key={index}
|
|
type="button"
|
|
className={`hero-autocomplete-item ${highlightedIndex === index ? 'highlighted' : ''}`}
|
|
onMouseDown={(e) => { e.preventDefault(); handleSelectAutocomplete(item); }}
|
|
onMouseEnter={() => setHighlightedIndex(index)}
|
|
>
|
|
<div className="hero-autocomplete-title" dangerouslySetInnerHTML={{ __html: item.title }} />
|
|
<div className="hero-autocomplete-address">{item.roadAddress || item.address}</div>
|
|
</button>
|
|
))
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* 입력 clear 버튼 */}
|
|
{inputValue && (
|
|
<button
|
|
type="button"
|
|
className="hero-input-clear"
|
|
onClick={() => {
|
|
setInputValue('');
|
|
setSelectedItem(null);
|
|
setLocalError('');
|
|
setAutocompleteResults([]);
|
|
setShowAutocomplete(false);
|
|
}}
|
|
>
|
|
<img src="/assets/images/input-clear-icon.svg" alt="Clear" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
|
|
<span className="hero-input-hint">{t('landing.hero.guideCombined')}</span>
|
|
|
|
{error && <p className="hero-error">{error}</p>}
|
|
|
|
<button onClick={handleStart} className="hero-button">
|
|
{t('landing.hero.analyzeButton')}
|
|
</button>
|
|
|
|
<div className="hero-divider"><span>또는</span></div>
|
|
|
|
<div className="hero-manual-card" onClick={handleManualButtonClick} role="button" tabIndex={0}
|
|
onKeyDown={(e) => e.key === 'Enter' && handleManualButtonClick()}>
|
|
<span className="hero-manual-card-title">{t('landing.hero.searchTypeManual')}</span>
|
|
<p className="hero-manual-button-desc">{t('landing.hero.manualButtonDesc')}</p>
|
|
</div>
|
|
|
|
{/* onManualButtonClick 미제공 시 모달을 내부에서 관리 */}
|
|
{!onManualButtonClick && isManualModalOpen && (
|
|
<BusinessNameInputModal
|
|
onClose={() => setIsManualModalOpen(false)}
|
|
onSubmit={(businessName, address, category, officialSiteUrl) => {
|
|
setIsManualModalOpen(false);
|
|
onManualInput?.(businessName, address, category, officialSiteUrl);
|
|
}}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default SearchInputForm;
|