Sure! Based on the existing logic you've provided for loading texts, below is the implementation of the JavaScript logic for displaying the text divided into pages, with each word being clickable to trigger the updateBubble(event) function. I've also included the corresponding HTML where the loaded text will be placed.
HTML Structure
First, ensure you have the following HTML structure in your page:
<!-- Container for the text list (already existing) -->
<ul id="textList" class="list-group"></ul>
<!-- Container where the loaded text will be displayed -->
<div id="textContainer">
<div id="text-with-blanks"></div>
</div>
<!-- Place for page navigation controls -->
<div id="page-navigation"></div>
<!-- Optional: Container for alerts -->
<div id="alert-container"></div>
JavaScript Code
Here is the complete JavaScript code integrating with your existing functions:
let actionBubble = null;
let selectedTextName = "";
let selectedWords = [];
let wordCount = "";
let alertShown = false;
const textContainer = document.getElementById('text-with-blanks');
let totalPages = 1;
let allTexts = [];
let currentPage = 1; // Current page for text list pagination
///////////////////////////////////////////////
// # LOGIKA WCZYTYWANIA TEKSTÓW #//
///////////////////////////////////////////////
// Główna funkcja inicjalizująca aplikację
document.addEventListener('DOMContentLoaded', () => {
decideWhichTextToLoad();
});
// Pobranie tekstów z serwera z uwzględnieniem limitu i wyszukiwania
function decideWhichTextToLoad() {
const limit = document.getElementById('textLimit') ? document.getElementById('textLimit').value : 10;
const searchQuery = document.getElementById('searchInput') ? document.getElementById('searchInput').value : '';
const tagQuery = document.getElementById('tagInput') ? document.getElementById('tagInput').value : '';
fetch(`/user/get_texts_for_insert_words_to_text?limit=${limit}&page=${currentPage}&search=${searchQuery}&tag=${tagQuery}`)
.then(response => response.json())
.then(data => {
allTexts = data.text_names;
totalPages = data.total_pages;
populateTextList(allTexts);
updatePaginationControls();
showAlert('Lista tekstów została załadowana!', 'success');
})
.catch(error => {
console.error('Błąd przy pobieraniu listy tekstów:', error);
showAlert('Błąd przy pobieraniu listy tekstów.', 'danger');
});
}
// Funkcja generująca listę tekstów
function populateTextList(textNames) {
const textList = document.getElementById('textList');
textList.innerHTML = ''; // Czyszczenie listy
textNames.forEach(text => {
const listItem = createTextListItem(text);
textList.appendChild(listItem);
});
}
// Funkcja tworząca element listy tekstów
function createTextListItem(text) {
const listItem = document.createElement('li');
listItem.className = 'list-group-item';
listItem.dataset.name = text.name;
listItem.innerText = text.name;
listItem.addEventListener('click', () => fetchAndLoadText(text.name));
return listItem;
}
function updatePaginationControls() {
const nextPageBtn = document.getElementById('nextPage');
const prevPageBtn = document.getElementById('prevPage');
nextPageBtn.disabled = currentPage >= totalPages;
prevPageBtn.disabled = currentPage <= 1;
}
function nextPage() {
if (currentPage < totalPages) {
currentPage++;
decideWhichTextToLoad();
}
}
function prevPage() {
if (currentPage > 1) {
currentPage--;
decideWhichTextToLoad();
}
}
// Filtrowanie tekstów po nazwie
function filterTextsByName() {
currentPage = 1;
decideWhichTextToLoad();
}
function filterTextsByTag() {
currentPage = 1;
decideWhichTextToLoad();
}
// Funkcja pobierająca i wyświetlająca wybrany tekst
function fetchAndLoadText(textName) {
selectedWords = [];
wordCount = {};
// Usunięcie podświetlenia z poprzednio aktywnego elementu
const previousActiveItem = document.querySelector('.list-group-item.active-text');
if (previousActiveItem) {
previousActiveItem.classList.remove('active-text');
}
// Znalezienie klikniętego elementu listy na podstawie nazwy tekstu i dodanie klasy podświetlenia
const activeItem = document.querySelector(`li[data-name="${textName}"]`);
if (activeItem) {
activeItem.classList.add('active-text');
}
if (actionBubble != null) {
document.body.removeChild(actionBubble);
actionBubble = null;
}
// Pobierz zawartość tekstu z serwera
fetch(`/user/get_text_content?name=${encodeURIComponent(textName)}`)
.then(response => response.json())
.then(data => {
const textContent = data.content; // Załóżmy, że serwer zwraca { content: '...' }
if (textContent) {
// Przetwarzaj i wyświetl tekst
processAndDisplayText(textContent);
showAlert('Tekst został załadowany!', 'success');
} else {
showAlert('Nie udało się wczytać tekstu.', 'danger');
}
})
.catch(error => {
console.error('Błąd przy pobieraniu tekstu:', error);
showAlert('Błąd przy pobieraniu tekstu.', 'danger');
});
}
// Funkcja przetwarzająca i wyświetlająca tekst z podziałem na strony i klikalnymi słowami
function processAndDisplayText(textContent) {
const words = textContent.split(/\s+/); // Podziel tekst na słowa
const wordsPerPage = 500; // Liczba słów na stronę
const totalPages = Math.ceil(words.length / wordsPerPage);
// Utwórz tablicę stron, każda zawiera tablicę słów
const pages = [];
for (let i = 0; i < totalPages; i++) {
const startIndex = i * wordsPerPage;
const endIndex = startIndex + wordsPerPage;
const pageWords = words.slice(startIndex, endIndex);
pages.push(pageWords);
}
// Inicjalizacja aktualnej strony
let currentPageIndex = 0;
// Funkcja renderująca stronę
function renderPage(pageIndex) {
const pageWords = pages[pageIndex];
const textContainer = document.getElementById('text-with-blanks');
textContainer.innerHTML = ''; // Wyczyść istniejącą zawartość
const pageElement = document.createElement('div');
pageElement.classList.add('page');
pageWords.forEach((word, index) => {
const wordSpan = document.createElement('span');
wordSpan.innerText = word + ' '; // Dodaj spację po każdym słowie
wordSpan.classList.add('word');
// Dodaj event listener do każdego słowa
wordSpan.addEventListener('click', (event) => {
updateBubble(event);
});
pageElement.appendChild(wordSpan);
});
textContainer.appendChild(pageElement);
updatePageNavigation();
}
// Funkcja aktualizująca kontrolki nawigacji po stronach
function updatePageNavigation() {
let pageNavContainer = document.getElementById('page-navigation');
if (!pageNavContainer) {
// Jeśli nie istnieje, utwórz kontener nawigacji po stronach
pageNavContainer = document.createElement('div');
pageNavContainer.id = 'page-navigation';
const prevButton = document.createElement('button');
prevButton.id = 'prevTextPage';
prevButton.innerText = 'Poprzednia strona';
prevButton.addEventListener('click', () => {
if (currentPageIndex > 0) {
currentPageIndex--;
renderPage(currentPageIndex);
}
});
const nextButton = document.createElement('button');
nextButton.id = 'nextTextPage';
nextButton.innerText = 'Następna strona';
nextButton.addEventListener('click', () => {
if (currentPageIndex < totalPages - 1) {
currentPageIndex++;
renderPage(currentPageIndex);
}
});
const pageInfo = document.createElement('span');
pageInfo.id = 'textPageInfo';
pageInfo.innerText = `Strona ${currentPageIndex + 1} z ${totalPages}`;
pageNavContainer.appendChild(prevButton);
pageNavContainer.appendChild(pageInfo);
pageNavContainer.appendChild(nextButton);
textContainer.parentElement.appendChild(pageNavContainer);
} else {
// Jeśli istnieje, zaktualizuj informacje
const pageInfo = document.getElementById('textPageInfo');
pageInfo.innerText = `Strona ${currentPageIndex + 1} z ${totalPages}`;
}
// Wyłącz/włącz przyciski w zależności od aktualnej strony
document.getElementById('prevTextPage').disabled = currentPageIndex === 0;
document.getElementById('nextTextPage').disabled = currentPageIndex === totalPages - 1;
}
// Renderuj pierwszą stronę
renderPage(currentPageIndex);
}
// Przykładowa implementacja funkcji showAlert
function showAlert(message, type) {
const alertContainer = document.getElementById('alert-container');
const alertElement = document.createElement('div');
alertElement.className = `alert alert-${type}`;
alertElement.innerText = message;
alertContainer.appendChild(alertElement);
setTimeout(() => {
alertContainer.removeChild(alertElement);
}, 3000);
}
// Przykładowa implementacja funkcji updateBubble (funkcja już istnieje)
function updateBubble(event, finalizePosition = false) {
// Implementacja obsługi dymka (przyjmujemy, że jest gotowa)
}
Wyjaśnienia
- fetchAndLoadText(textName): Ta funkcja pobiera zawartość tekstu z serwera i wywołuje
processAndDisplayText(textContent) w celu przetworzenia i wyświetlenia tekstu.
- processAndDisplayText(textContent): Dzieli tekst na słowa i grupuje je w strony po
wordsPerPage słów. Następnie renderuje aktualną stronę i ustawia nawigację.
- renderPage(pageIndex): Renderuje stronę o podanym indeksie, tworząc klikalne elementy
<span> dla każdego słowa. Kliknięcie słowa wywołuje funkcję updateBubble(event).
- updatePageNavigation(): Aktualizuje kontrolki nawigacji między stronami i informacje o aktualnej stronie.
- HTML Structure: Upewnij się, że masz kontener o
id="text-with-blanks" w swoim HTML, w którym będzie wyświetlany tekst. Kontrolki nawigacji stron zostaną dodane poniżej tego kontenera.
- Event Listeners: Każde słowo jest klikalne i po kliknięciu wywołuje
updateBubble(event), zgodnie z Twoimi wymaganiami.
- Alerty: Funkcja
showAlert jest przykładową implementacją wyświetlania komunikatów dla użytkownika.
Uwaga
- Stylowanie: Możesz dodać własne style CSS, aby dostosować wygląd tekstu, stron i kontrolek nawigacji.
- Optymalizacja: Dla bardzo długich tekstów rozważ paginację serwerową lub dynamiczne ładowanie stron, aby poprawić wydajność.
- Dalsza Integracja: Upewnij się, że wszystkie zmienne globalne i funkcje są odpowiednio zdefiniowane w Twoim kodzie, aby uniknąć konfliktów i błędów.
W ten sposób zaimplementowana została logika wyświetlania tekstu z podziałem na strony, gdzie każde słowo jest klikalne i wywołuje funkcję updateBubble(event). Kod został zintegrowany z wcześniej przedstawionymi funkcjami, zgodnie z Twoimi instrukcjami.