// Объект для отслеживания выбранных фильтров
export const selectedFilters = {
colors: new Set(),
types: new Set(),
languages: new Set()
};
/**
Инициализирует IndexedDB и загружает данные при необходимости
@returns {Promise}
*/
export function initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("FlagsDatabase", 1);
code
Assistant
request.onupgradeneeded = function(event) {
const db = event.target.result;
// Создаём объектные хранилища и индексы
Object.values(dataMapping).forEach(config => {
if (!db.objectStoreNames.contains(config.storeName)) {
if (Array.isArray(config.keyPath)) {
const store = db.createObjectStore(config.storeName, { keyPath: config.keyPath });
// Создаём индексы, если необходимо
if (config.storeName === "flagNames") {
store.createIndex("flag_id", "flag_id", { unique: false });
store.createIndex("language_id", "language_id", { unique: false });
}
// Добавьте другие индексы при необходимости
} else {
const store = db.createObjectStore(config.storeName, { keyPath: config.keyPath });
// Создаём индексы
if (config.storeName === "languages") {
store.createIndex("en_name", "en_name", { unique: false });
store.createIndex("ru_name", "ru_name", { unique: false });
store.createIndex("zh_name", "zh_name", { unique: false });
} else if (config.storeName === "flags") {
store.createIndex("types", "types", { unique: false, multiEntry: true });
store.createIndex("colors", "colors", { unique: false, multiEntry: true });
store.createIndex("parent_flag_id", "parent_flag_id", { unique: false });
} else if (config.storeName === "flagSubdivisions") {
store.createIndex("parent_flag_id", "parent_flag_id", { unique: false });
}
// Добавьте другие индексы для других хранилищ при необходимости
}
}
});
};
request.onsuccess = function(event) {
const db = event.target.result;
console.log("База данных успешно открыта");
resolve(db);
};
request.onerror = function(event) {
console.error("Не удалось открыть базу данных", event.target.error);
reject(event.target.error);
};
});
}
/**
Добавляет данные в указанное объектное хранилище
@param {IDBDatabase} db - Открытая база данных
@param {string} storeName - Имя объектного хранилища
@param {Array} dataArray - Массив данных для добавления
@param {string|Array} keyPath - Ключевое поле или составной ключ
@returns {Promise}
*/
export function addData(db, storeName, dataArray, keyPath) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], "readwrite");
const store = transaction.objectStore(storeName);
code
transaction.oncomplete = function() {
console.log(`Все данные добавлены в ${storeName}`);
resolve();
};
transaction.onerror = function(event) {
console.error(`Ошибка при добавлении данных в ${storeName}:`, event.target.error);
reject(event.target.error);
};
dataArray.forEach(item => store.put(item));
});
}
/**
Получает количество записей в указанном объектном хранилище
@param {IDBDatabase} db - Открытая база данных
@param {string} storeName - Имя объектного хранилища
@returns {Promise}
*/
export function getCount(db, storeName) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], "readonly");
const store = transaction.objectStore(storeName);
const request = store.count();
code
request.onsuccess = function(event) {
resolve(event.target.result);
};
request.onerror = function(event) {
console.error(`Ошибка при подсчёте записей в ${storeName}:`, event.target.error);
reject(event.target.error);
};
});
}
/**
Загружает все данные в IndexedDB при необходимости
Данные загружаются только при первом создании базы данных
@param {IDBDatabase} db - Открытая база данных
@returns {Promise}
*/
export async function loadData(db) {
try {
// Проверяем, пусто ли объектное хранилище "languages"
const countLanguages = await getCount(db, "languages");
console.log(Количество записей в 'languages': ${countLanguages});
code
if (countLanguages === 0) {
for (const [key, config] of Object.entries(dataMapping)) {
console.log(`Добавление данных в хранилище: ${config.storeName}`);
await addData(db, config.storeName, config.data, config.keyPath);
console.log(`Данные добавлены в хранилище: ${config.storeName}`);
}
console.log("Все данные успешно загружены в IndexedDB.");
} else {
console.log("Данные уже существуют в базе данных. Загрузка не требуется.");
}
} catch (error) {
console.error("Произошла ошибка при загрузке данных. Пожалуйста, попробуйте позже.", error);
}
}
/**
Получает все записи из указанного объектного хранилища
@param {IDBDatabase} db - Открытая IndexedDB база данных
@param {string} storeName - Имя объектного хранилища
@returns {Promise}
*/
export function getAllRecords(db, storeName) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], "readonly");
const store = transaction.objectStore(storeName);
const request = store.getAll();
code
request.onsuccess = function(event) {
resolve(event.target.result);
};
request.onerror = function(event) {
console.error(`Ошибка при получении данных из ${storeName}:`, event.target.error);
reject(event.target.error);
};
});
}
// ----- Начало файла: ./js\events.js -----
// events.js - Содержит все обработчики событий и назначение слушателей.
import { selectedFilters } from './db.js';
import { handleViewData, paginationState, viewFlagsAsCards } from './main.js';
import { debounce } from './utils.js';
import i18next from 'https://cdn.skypack.dev/i18next@21.6.16';
/**
Добавляет обработчики событий для фильтров
*/
export function addFilterEventListeners() {
// Фильтр по цветам
const colorCheckboxes = document.querySelectorAll("#color-filters input[type='checkbox']");
colorCheckboxes.forEach(checkbox => {
checkbox.addEventListener("change", (event) => {
if (event.target.checked) {
selectedFilters.colors.add(event.target.value);
} else {
selectedFilters.colors.delete(event.target.value);
}
handleViewData();
});
});
Добавляет обработчики событий для различных кнопок и элементов
*/
export function setupEventListeners() {
// Кнопка Поиска
document.getElementById("search-button").addEventListener("click", async () => {
handleViewData();
});
Настраивает реализацию фильтрации в реальном времени
@param {IDBDatabase} db - Открытая база данных
*/
export function setupRealTimeFiltering(db) {
const searchInput = document.getElementById("search-input");
Обработчик события прокрутки для Infinite Scrolling с debounce
*/
export function setupInfiniteScroll() {
window.addEventListener("scroll", debounce(async () => {
if (paginationState.isLoading || !paginationState.hasMore) return;
// Установка текущего языка в селектор
languageSelect.value = i18next.language || 'en';
languageSelect.addEventListener('change', function (e) {
const selectedLang = e.target.value;
i18next.changeLanguage(selectedLang);
});
});
// Обработчик изменения языка
i18next.on('languageChanged', () => {
updateContent();
// Повторно отобразить текущие данные с учетом нового языка
handleViewData(handleViewData());
});
// Объект состояния пагинации
export const paginationState = {
currentPage: 1,
pageSize: 36,
isLoading: false,
hasMore: true,
filteredFlags: []
};
/**
Инициализирует и загружает приложение
*/
export async function initializeApp() {
try {
// Инициализация i18next
i18next
.use(HttpBackend)
.use(LanguageDetector)
.init({
fallbackLng: 'en',
debug: true,
backend: {
loadPath: '../locales/{{lng}}/translations.json'
}
}, function (err, t) {
if (err) return console.error(err);
updateContent();
});
code
const db = await initDB();
await loadData(db);
await populateAllFilters(db);
addFilterEventListeners();
setupEventListeners(); // Настраиваем обработчики для остальных кнопок
setupRealTimeFiltering(db); // Настраиваем фильтрацию в реальном времени
setupFilterToggle(); // Настраиваем переключение фильтров
setupInfiniteScroll(db); // Настраиваем Infinite Scroll
console.log("Приложение инициализировано успешно.");
handleViewData(db); // Отображаем данные по умолчанию
Показывает/обновляет данные в зависимости от выбранного типа данных и применённых фильтров
@param {IDBDatabase} db - Открытая база данных
*/
export async function handleViewData(db) {
const searchQuery = document.getElementById("search-input").value.trim();
// Сброс состояния пагинации
paginationState.currentPage = 1;
paginationState.hasMore = true;
// Получаем все флаги, соответствующие фильтрам и поиску
const allFlags = await getFilteredFlags(db, searchQuery, selectedFilters);
paginationState.filteredFlags = allFlags;
} else {
// Fallback для браузеров без поддержки Intersection Observer
lazyImages.forEach(img => {
const realSrc = img.getAttribute("data-src");
if (realSrc) {
img.src = realSrc;
img.removeAttribute("data-src");
}
});
}
}
/**
Получает подразделения флага
@param {IDBDatabase} db - Открытая база данных
@param {string} flagId - ID флага
@returns {Promise} - Массив подразделений с названиями
*/
export async function getFlagSubdivisions(db, flagId) {
try {
// Получаем все подразделения для данного флага
const subdivisions = await new Promise((resolve, reject) => {
const transaction = db.transaction(["flagSubdivisions"], "readonly");
const store = transaction.objectStore("flagSubdivisions");
const index = store.index("parent_flag_id");
const request = index.getAll(IDBKeyRange.only(flagId));
code
request.onsuccess = function(event) {
resolve(event.target.result);
};
request.onerror = function(event) {
console.error(`Ошибка при получении подразделений для флага "${flagId}":`, event.target.error);
resolve([]); // Возвращаем пустой массив в случае ошибки
};
});
if (subdivisions.length === 0) {
return [];
}
// Получаем названия подразделений
const subdivisionIds = subdivisions.map(sub => sub.id);
const subdivisionNames = await new Promise((resolve, reject) => {
const transaction = db.transaction(["flagSubdivisionNames"], "readonly");
const store = transaction.objectStore("flagSubdivisionNames");
const request = store.getAll(); // Получаем все и фильтруем в коде
request.onsuccess = function(event) {
const allNames = event.target.result;
const matchedNames = allNames.filter(name => subdivisionIds.includes(name.id));
resolve(matchedNames);
};
request.onerror = function(event) {
console.error(`Ошибка при получении названий подразделений для флага "${flagId}":`, event.target.error);
resolve([]); // Возвращаем пустой массив в случае ошибки
};
});
return subdivisionNames;
// ----- Начало файла: ./js\ui.js -----
// ui.js - Управляет всеми функциями, связанными с изменением интерфейса пользователя, такими как отображение фильтров и карточек флагов.
import { updateContent } from './main.js';
import { getAllRecords } from './db.js';
import i18next from 'https://cdn.skypack.dev/i18next@21.6.16';
// Объявление необходимых переменных и карт
export let colorsMap = {};
export let languagesMap = {};
// ----- Начало файла: ./js\utils.js -----
// utils.js - Включает вспомогательные функции, такие как debounce и lazy loading.
import i18next from 'https://cdn.skypack.dev/i18next@21.6.16';
Функция debounce, которая ограничивает частоту вызовов функции
@param {Function} func - Функция для обертки
@param {number} delay - Задержка в миллисекундах
*/
export function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
/**
Показывает загрузочный спиннер
*/
export function showLoading() {
const spinner = document.getElementById("loading-spinner");
if (spinner) {
spinner.style.display = "block";
}
}
/**
Скрывает загрузочный спиннер
*/
export function hideLoading() {
const spinner = document.getElementById("loading-spinner");
if (spinner) {
spinner.style.display = "none";
}
}
Your application comprises several modular JavaScript files that handle different aspects of the functionality, such as database interactions, event handling, UI updates, and utilities. Overall, the structure is well-organized, leveraging ES modules and modern JavaScript features. However, there are a few areas where improvements can be made to enhance functionality, performance, and code readability. Below are some observations, potential issues, and recommendations:
1. Issue with Recursive handleViewData Call
Problem:
In your main.js file, within the languageChanged event listener, you have the following line:
javascript
handleViewData(handleViewData());
This line inadvertently causes a recursive call to handleViewData, which can lead to a stack overflow error.
Solution:
You should pass the db instance to handleViewData instead of calling it recursively. Modify the event listener as follows:
javascript
i18next.on('languageChanged', () => {
updateContent();
// Ensure `db` is accessible here; you might need to store it in a higher scope
handleViewData(db);
});
However, since db is obtained asynchronously within initializeApp, you'll need to ensure that db is accessible within the scope of the event listener. One way to achieve this is by declaring db in a higher scope:
javascript
let dbInstance;
export async function initializeApp() {
try {
// ... initialization code ...
dbInstance = await initDB();
await loadData(dbInstance);
// ... rest of the initialization code ...
} catch (error) {
// ... error handling ...
}
}
i18next.on('languageChanged', () => {
updateContent();
if (dbInstance) {
handleViewData(dbInstance);
}
});
2. Redundant Data Fetching in handleViewData and viewFlagsAsCards
Problem:
Both handleViewData and viewFlagsAsCards functions are fetching and processing data, leading to redundant operations. This can negatively impact performance, especially with large datasets.
Solution:
Refactor the code to centralize data fetching and filtering. Here's a streamlined approach:
handleViewData: Handle filtering and pagination logic.
viewFlagsAsCards: Solely responsible for rendering the data.
Refactored handleViewData:
javascript
export async function handleViewData(db) {
const searchQuery = document.getElementById("search-input").value.trim();
// Reset pagination state
paginationState.currentPage = 1;
paginationState.hasMore = true;
// Fetch and filter flags
const filteredFlags = await getFilteredFlags(db, searchQuery, selectedFilters);
paginationState.filteredFlags = filteredFlags;
// Render the first page
await viewFlagsAsCards(filteredFlags, paginationState.currentPage, paginationState.pageSize);
}
Refactored viewFlagsAsCards:
javascript
export async function viewFlagsAsCards(filteredFlags, page = 1, pageSize = 36) {
try {
if (page === 1) {
showLoading(); // Show spinner only on the first load
}
// Determine the slice of data to display
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const flagsToDisplay = filteredFlags.slice(startIndex, endIndex);
// Handle no data scenario
const output = document.getElementById("output");
if (page === 1) {
output.innerHTML = "";
}
if (page === 1 && flagsToDisplay.length === 0) {
output.innerHTML = "<p>Нет флагов, соответствующих выбранным фильтрам.</p>";
hideLoading();
return;
}
// Create a document fragment to optimize DOM manipulation
const fragment = document.createDocumentFragment();
for (const flag of flagsToDisplay) {
const card = await createFlagCard(flag);
fragment.appendChild(card);
}
output.appendChild(fragment);
hideLoading();
// Initialize lazy loading for images
initLazyLoadImages();
} catch (error) {
console.log(error);
showError("errorLoadingFlags");
hideLoading();
}
}
/**
* Creates a flag card element asynchronously.
*/
async function createFlagCard(flag) {
// ...existing logic to create a card...
// Example:
const card = document.createElement("div");
// Populate card with flag data
// ...
return card;
}
This separation ensures that data processing is handled once, and rendering is managed independently, improving performance and maintainability.
3. Handling Asynchronous Operations in UI Updates
Problem:
Functions like viewFlagsAsCards involve asynchronous operations (e.g., fetching subdivisions). However, these operations are mixed with synchronous DOM manipulations, which can lead to unexpected behaviors or race conditions.
Solution:
Ensure that all asynchronous operations are properly awaited before updating the DOM. Consider using async functions and modularizing the code further to handle these operations cleanly.
Fetching all records from object stores like "flags", "flagNames", etc., can be inefficient, especially with large datasets.
Solution:
Implement indexing and querying mechanisms to fetch only the necessary data based on filters. This reduces memory consumption and improves performance.
Example:
Instead of fetching all flags and then filtering them in JavaScript, leverage IndexedDB's indexes to perform queries:
javascript
export async function getFilteredFlags(db, searchQuery, filters) {
const transaction = db.transaction("flags", "readonly");
const store = transaction.objectStore("flags");
let request;
if (searchQuery) {
// Implement search logic using indexes if available
// For example, searching by ID or name
} else {
request = store.getAll();
}
return new Promise((resolve, reject) => {
request.onsuccess = function(event) {
let flags = event.target.result;
// Apply additional filtering (colors, types, languages) if necessary
// ...
resolve(flags);
};
request.onerror = function(event) {
console.error("Error fetching filtered flags:", event.target.error);
reject(event.target.error);
};
});
}
Additionally, ensure that appropriate indexes are created during the onupgradeneeded event in your db.js to facilitate efficient querying.
5. Lazy Loading Enhancements
Problem:
While you have implemented lazy loading for images using IntersectionObserver, there's an opportunity to optimize it further, especially regarding the placeholder images and performance.
Solution:
Use Low-Quality Image Placeholders (LQIP): Instead of a generic placeholder, use a blurred version of the image or a dominant color placeholder to enhance user experience.
Throttle Scroll Events: Although you're using debouncing, ensure that the scroll event listener is optimized to prevent performance bottlenecks.
Enhanced Lazy Loading Example:
javascript
function initLazyLoadImages() {
const lazyImages = document.querySelectorAll("img.lazy-image");
if ("IntersectionObserver" in window) {
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const realSrc = img.getAttribute("data-src");
if (realSrc) {
img.src = realSrc;
img.onload = () => img.classList.add('loaded'); // Add a class once loaded
img.onerror = () => img.src = 'https://placehold.co/400/ff0000'; // Fallback on error
img.removeAttribute("data-src");
}
imageObserver.unobserve(img);
}
});
}, {
rootMargin: "200px 0px", // Preload images earlier
threshold: 0.01
});
lazyImages.forEach(img => {
imageObserver.observe(img);
});
} else {
// Fallback for browsers without IntersectionObserver
lazyImages.forEach(img => {
const realSrc = img.getAttribute("data-src");
if (realSrc) {
img.src = realSrc;
img.classList.add('loaded');
img.removeAttribute("data-src");
}
});
}
}
Ensure that the subdivisionsContainer has an id that matches the aria-controls attribute.
7. Internationalization (i18next) Optimization
Problem:
The current implementation initializes i18next within the initializeApp function, which might lead to sequences where translations are not fully loaded before UI rendering.
Solution:
Ensure that i18next is fully initialized before any UI elements that depend on translations are rendered. You can achieve this by restructuring the initialization logic.
By using await with i18next.init, you ensure that translations are loaded before proceeding with other initializations.
8. Code Readability and Maintainability
Recommendations:
Consistent Naming Conventions: Ensure that function and variable names are consistently in English or another chosen language to maintain uniformity.
Modularize Repeated Logic: Functions like creating filter checkboxes can be abstracted into reusable components to reduce code duplication.
Commenting and Documentation: While some parts of the code are commented, adding more detailed explanations, especially for complex functions, can aid future maintenance.
Error Handling: Implement more granular error handling to provide better feedback and recovery options in case of failures.
9. Potential Enhancements
a. Pagination Controls:
Provide users with controls to navigate between pages, jump to a specific page, or change the number of items per page.
b. Caching Mechanisms:
Implement caching strategies for frequently accessed data to reduce database reads and improve performance.
c. Responsive Design:
Ensure that the UI is responsive across different devices and screen sizes, enhancing user experience.
d. Testing:
Incorporate unit and integration tests to ensure that each module functions as expected. Tools like Jest or Mocha can be beneficial.
10. Final Thoughts
Your application's modular approach is commendable and lays a solid foundation for scalability and maintainability. By addressing the identified issues and implementing the recommended optimizations, you can enhance performance, user experience, and code quality. Additionally, continuously monitoring and profiling the application can help identify and resolve performance bottlenecks as your dataset grows.
If you have specific questions or need further assistance with any part of your code, feel free to ask!