206 lines
8.3 KiB
JavaScript
206 lines
8.3 KiB
JavaScript
/** 상태·카테고리·검색 필터 로직 및 UI */
|
|
import { state, productsData } from './state.js';
|
|
import { ITEMS_PER_PAGE, STATUS_META, STATUS_FILTERS, STATUS_ORDER, STATUS_COLOR, SEARCH_CONFIG, } from './config.js';
|
|
import { renderProducts } from './productList.js';
|
|
|
|
function getStatusChipClass(status, isActive) {
|
|
const base = STATUS_COLOR[status] ?? '';
|
|
if (isActive) {
|
|
return `${base} opacity-100 shadow-sm`;
|
|
}
|
|
return `bg-slate-50 text-slate-400 border-slate-200 opacity-30 grayscale hover:opacity-50`;
|
|
}
|
|
|
|
export function renderStatusChips() {
|
|
const container = document.getElementById('status-chips');
|
|
if (!container) return;
|
|
container.innerHTML = '';
|
|
|
|
// 이제 config에서 자동 생성된 STATUS_FILTERS를 사용합니다.
|
|
STATUS_FILTERS.forEach(({ key, label }) => {
|
|
const isActive = state.activeStatuses.has(key);
|
|
|
|
const chip = document.createElement('button');
|
|
// getStatusChipClass 함수가 기존에 정의되어 있다면 그대로 사용하세요.
|
|
chip.className = `status-chip px-3 py-1.5 md:px-4 md:py-2 rounded-full text-xs md:text-sm font-medium transition-all duration-200 border ${getStatusChipClass(key, isActive)}`;
|
|
chip.textContent = label;
|
|
chip.onclick = () => toggleStatusFilter(key);
|
|
container.appendChild(chip);
|
|
});
|
|
}
|
|
|
|
function toggleStatusFilter(status) {
|
|
if (state.activeStatuses.has(status)) {
|
|
state.activeStatuses.delete(status);
|
|
} else {
|
|
state.activeStatuses.add(status);
|
|
}
|
|
if (state.activeStatuses.size === 0) {
|
|
STATUS_FILTERS.filter((f) => f.defaultActive).forEach((f) => state.activeStatuses.add(f.key));
|
|
}
|
|
applyFilters();
|
|
renderStatusChips();
|
|
}
|
|
|
|
// [핵심] 필터 적용 함수
|
|
export function applyFilters() {
|
|
// [수정] 무조건 1페이지로 초기화하지 않고, 나중에 데이터 개수에 맞춰 계산합니다.
|
|
const keyword = state.searchKeyword.toLowerCase();
|
|
|
|
// 1. 데이터 필터링 및 정렬
|
|
state.visibleProducts = productsData
|
|
.filter((product) => {
|
|
const meta = STATUS_META[product.status];
|
|
|
|
// [1] 시스템 가시성 체크 (isSystemVisible이 false면 목록에서 완전히 제외)
|
|
if (!meta || !meta.isSystemVisible) return false;
|
|
|
|
// [2] 상태 필터 체크 (사용자가 필터 칩을 클릭해 활성화했는지)
|
|
const statusMatch = state.activeStatuses.has(product.status);
|
|
|
|
// [3] 카테고리 필터 체크
|
|
const categoryMatch = state.activeCategories.has('All') || state.activeCategories.has(product.category);
|
|
|
|
// [4] 검색어 매칭 로직
|
|
const searchMatch =
|
|
keyword === '' ||
|
|
(() => {
|
|
const searchPool = [];
|
|
if (SEARCH_CONFIG.USE_TITLE) searchPool.push(product.title);
|
|
if (SEARCH_CONFIG.USE_CUSTOM_TAG && product.customTag) searchPool.push(product.customTag);
|
|
if (SEARCH_CONFIG.USE_DESCRIPTION && product.description) searchPool.push(product.description);
|
|
if (SEARCH_CONFIG.USE_TAGS && product.tags) searchPool.push(...product.tags);
|
|
if (SEARCH_CONFIG.USE_FULL_DESCRIPTION && product.fullDescription) searchPool.push(...product.fullDescription);
|
|
|
|
return searchPool.some((text) => String(text || '').toLowerCase().includes(keyword));
|
|
})();
|
|
|
|
return statusMatch && categoryMatch && searchMatch;
|
|
})
|
|
.sort((a, b) => {
|
|
const aOrder = STATUS_ORDER[a.status] ?? 999;
|
|
const bOrder = STATUS_ORDER[b.status] ?? 999;
|
|
return aOrder - bOrder;
|
|
});
|
|
|
|
// 2. [추가] 페이지 위치 안전 조정 로직
|
|
// 필터링된 결과로 가질 수 있는 최대 페이지 계산
|
|
const totalPages = Math.ceil(state.visibleProducts.length / ITEMS_PER_PAGE);
|
|
|
|
if (state.currentPage > totalPages) {
|
|
// 만약 필터링 후 전체 페이지가 현재 페이지보다 적어지면 마지막 페이지로 이동
|
|
state.currentPage = Math.max(1, totalPages);
|
|
} else if (state.currentPage < 1) {
|
|
// 혹시 모를 에러 방지용 1페이지 고정
|
|
state.currentPage = 1;
|
|
}
|
|
// ※ 참고: 필터를 걸 때마다 무조건 첫 페이지를 보게 하고 싶다면
|
|
// 위 로직 대신 단순히 state.currentPage = 1; 을 쓰시면 됩니다.
|
|
|
|
// 3. UI 업데이트
|
|
renderTotalCount(state.visibleProducts.length);
|
|
renderProducts(state.currentPage);
|
|
}
|
|
|
|
/** 총 개수를 화면에 표시하는 보조 함수 */
|
|
function renderTotalCount(count) {
|
|
const totalCountElement = document.getElementById('total-count');
|
|
if (totalCountElement) {
|
|
totalCountElement.textContent = count.toLocaleString(); // 3자리마다 콤마
|
|
}
|
|
}
|
|
|
|
export function getCategories(products) {
|
|
return ['All', ...new Set(products.map((p) => p.category))];
|
|
}
|
|
|
|
export function renderCategoryChips(products) {
|
|
const container = document.getElementById('filter-chips');
|
|
if (!container) return;
|
|
|
|
// [핵심] 시스템 가시성이 true인 상품의 카테고리만 추출합니다.
|
|
const validCategories = products
|
|
.filter(p => {
|
|
const meta = STATUS_META[p.status];
|
|
// 해당 상태가 정의되어 있고, 시스템에서 보여주기로 한 경우만 포함
|
|
return meta && meta.isSystemVisible;
|
|
})
|
|
.map(p => p.category);
|
|
|
|
// 'All'은 항상 포함하고, 필터링된 카테고리들만 중복 제거하여 합침
|
|
const categories = ['All', ...new Set(validCategories)];
|
|
|
|
container.innerHTML = '';
|
|
|
|
categories.forEach((cat) => {
|
|
const isActive = state.activeCategories.has(cat);
|
|
const chip = document.createElement('button');
|
|
chip.className = `filter-chip px-3 py-1.5 md:px-4 md:py-2 rounded-full text-xs md:text-sm font-medium transition border ${
|
|
isActive
|
|
? 'bg-primary text-white border-primary shadow-sm'
|
|
: 'bg-slate-50 text-slate-600 border-slate-200'
|
|
}`;
|
|
chip.textContent = cat;
|
|
chip.dataset.category = cat;
|
|
chip.onclick = () => toggleCategory(cat);
|
|
container.appendChild(chip);
|
|
});
|
|
}
|
|
|
|
export function toggleCategory(category) {
|
|
if (category === 'All') {
|
|
state.activeCategories.clear();
|
|
state.activeCategories.add('All');
|
|
} else {
|
|
state.activeCategories.delete('All');
|
|
state.activeCategories.has(category) ? state.activeCategories.delete(category) : state.activeCategories.add(category);
|
|
if (state.activeCategories.size === 0) state.activeCategories.add('All');
|
|
}
|
|
renderCategoryChips(productsData);
|
|
applyFilters();
|
|
}
|
|
|
|
export function bindCategoryFilter(products) {
|
|
const chips = document.querySelectorAll('.filter-chip');
|
|
chips.forEach((chip) => {
|
|
chip.addEventListener('click', () => {
|
|
const category = chip.dataset.category;
|
|
if (category === 'All') {
|
|
state.activeCategories.clear();
|
|
state.activeCategories.add('All');
|
|
} else {
|
|
state.activeCategories.delete('All');
|
|
if (state.activeCategories.has(category)) state.activeCategories.delete(category);
|
|
else state.activeCategories.add(category);
|
|
if (state.activeCategories.size === 0) state.activeCategories.add('All');
|
|
}
|
|
applyFilters();
|
|
});
|
|
});
|
|
}
|
|
|
|
// 로고 클릭 시 초기화 로직
|
|
document.getElementById('logo-title')?.addEventListener('click', () => {
|
|
// 1. 검색어 초기화
|
|
state.searchKeyword = '';
|
|
const searchInput = document.getElementById('search-input'); // 검색창 ID가 있다면
|
|
if (searchInput) searchInput.value = '';
|
|
|
|
// 2. 카테고리 초기화 (All 선택)
|
|
state.activeCategories.clear();
|
|
state.activeCategories.add('All');
|
|
|
|
// 3. 상태 필터 초기화 (기본 활성화 상태로)
|
|
state.activeStatuses.clear();
|
|
STATUS_FILTERS.filter(f => f.defaultActive).forEach(f => state.activeStatuses.add(f.key));
|
|
|
|
// 4. 필터 적용 및 UI 갱신
|
|
applyFilters();
|
|
renderStatusChips();
|
|
renderCategoryChips(productsData);
|
|
|
|
// 5. 페이지 최상단으로 스크롤 (선택 사항)
|
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
|
});
|
|
|