// Pobranie tekstów z serwera z uwzględnieniem limitu i wyszukiwania
function decideWhichTextToLoad() {
const limit = document.getElementById('textLimit').value || 10;
const searchQuery = document.getElementById('searchInput').value || '';
const tagQuery = document.getElementById('tagInput').value || '';
code
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; // Załóżmy, że serwer zwraca też liczbę stron
populateTextList(allTexts);
updatePaginationControls(); // Funkcja aktualizująca przyciski paginacji
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
function nextPage() {
if (currentPage < totalPages) {
currentPage++;
decideWhichTextToLoad();
}
}
function prevPage() {
if (currentPage > 1) {
currentPage--;
decideWhichTextToLoad();
}
}
// Filtrowanie tekstów po nazwie
function filterTextsByName() {
currentPage = 1;
const query = document.getElementById('searchInput').value.toLowerCase();
decideWhichTextToLoad();
}
function filterTextsByTag() {
currentPage = 1;
const tag = document.getElementById('tagInput').value.toLowerCase();
decideWhichTextToLoad();
} ## Teraz znając logikę wczytującą tekst utwóż logikę wyświetlania tego tekstu z podziałem na strony, tak jak wyświetla się książkę, każde słowo musi być klikalne // Funkcja pobierająca i wyświetlająca wybrany tekst
function fetchAndLoadText(textName) {
selectedWords = [];
wordCount = {};
code
// 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;} // if exist actionBubble in html remove from html ## kliknięcie każdego słowa powinno wywołać funkcję: updateBubble(event); która aktywuje dymek function updateBubble(event, finalizePosition = false) {
const firstSelectedWord = document.querySelector('.selected');
if (selectedWords.length > 0 && firstSelectedWord) {
const rect = firstSelectedWord.getBoundingClientRect();
const x = rect.left;
const y = rect.top - 40;
if (!actionBubble) {
createActionBubble();
}
updateBubblePosition(x, y);
}
} przyjmij że implementacje funkcji obsługujących dymek są gotowe i nie trzeba ich implementować, zajmij się implementacją logiki wyświetlania książki z podziałem na strony i klikalnymi słowami uruchamiającymi dymek, zaimplementuj logikę javascript, odnieś się w uzupełniającym kodzie do funkcji które już Tobie pokazałem, pokaż logikę html w której będzie upuszczany wczytywany tekst
Certainly! Based on your existing code and requirements, here's how you can implement the logic to display the loaded text divided into pages, with each word being clickable and triggering the updateBubble(event) function.
HTML Structure:
First, ensure you have the necessary HTML elements where the text and pagination controls will be displayed:
html
<!-- Text Container where the paginated text will be displayed -->
<div id="textContainer"></div>
<!-- Pagination Controls -->
<div id="paginationControls">
<button id="prevTextPage" onclick="prevTextPage()">Previous</button>
<span id="currentPageIndicator">Page 1 of 1</span>
<button id="nextTextPage" onclick="nextTextPage()">Next</button>
</div>
JavaScript Implementation:
Now, here's the JavaScript logic to fetch the text, paginate it, and render it with clickable words:
javascript
let actionBubble = null;
let selectedTextName = "";
let selectedWords = [];
let wordCount = "";
let alertShown = false;
let currentPage = 1; // For text list pagination
let currentTextPage = 1; // For text content pagination
let totalTextPages = 1;
let textPages = [];
let allTexts = [];
let totalPages = 1;
// Function to fetch and load the selected text
function fetchAndLoadText(textName) {
selectedWords = [];
wordCount = {};
// Remove highlighting from the previously active item
const previousActiveItem = document.querySelector('.list-group-item.active-text');
if (previousActiveItem) {
previousActiveItem.classList.remove('active-text');
}
// Find the clicked list item based on text name and add highlighting class
const activeItem = document.querySelector(`li[data-name="${textName}"]`);
if (activeItem) {
activeItem.classList.add('active-text');
}
// Remove existing action bubble if present
if (actionBubble != null) {
document.body.removeChild(actionBubble);
actionBubble = null;
}
// Fetch text content from the server
fetch(`/user/get_text_by_name?name=${encodeURIComponent(textName)}`)
.then(response => response.json())
.then(data => {
const textContent = data.text_content;
selectedTextName = textName;
loadTextContent(textContent);
showAlert('Text loaded successfully!', 'success');
})
.catch(error => {
console.error('Error loading text:', error);
showAlert('Error loading text.', 'danger');
});
}
// Function to load and paginate the text content
function loadTextContent(textContent) {
// Split text into words
const words = textContent.split(/\s+/);
// Determine how many words per page
const wordsPerPage = 200; // Adjust this number as needed
// Split words into pages
textPages = [];
for (let i = 0; i < words.length; i += wordsPerPage) {
const pageWords = words.slice(i, i + wordsPerPage);
textPages.push(pageWords);
}
totalTextPages = textPages.length;
currentTextPage = 1;
// Display the first page
displayTextPage(currentTextPage);
updateTextPaginationControls();
}
// Function to display a specific page of text
function displayTextPage(pageNumber) {
const textContainer = document.getElementById('textContainer');
textContainer.innerHTML = ''; // Clear previous content
if (pageNumber < 1 || pageNumber > totalTextPages) {
return;
}
const pageWords = textPages[pageNumber - 1];
// Create a document fragment to improve performance
const fragment = document.createDocumentFragment();
pageWords.forEach((word, index) => {
const wordSpan = document.createElement('span');
wordSpan.innerText = word + ' ';
wordSpan.classList.add('word'); // Optional class for styling
// Event listener for word click
wordSpan.addEventListener('click', (event) => {
updateBubble(event);
});
fragment.appendChild(wordSpan);
});
textContainer.appendChild(fragment);
// Update current page indicator
const pageIndicator = document.getElementById('currentPageIndicator');
pageIndicator.innerText = `Page ${currentTextPage} of ${totalTextPages}`;
}
// Function to go to the next page
function nextTextPage() {
if (currentTextPage < totalTextPages) {
currentTextPage++;
displayTextPage(currentTextPage);
updateTextPaginationControls();
}
}
// Function to go to the previous page
function prevTextPage() {
if (currentTextPage > 1) {
currentTextPage--;
displayTextPage(currentTextPage);
updateTextPaginationControls();
}
}
// Function to update pagination controls
function updateTextPaginationControls() {
const nextPageBtn = document.getElementById('nextTextPage');
const prevPageBtn = document.getElementById('prevTextPage');
nextPageBtn.disabled = currentTextPage >= totalTextPages;
prevPageBtn.disabled = currentTextPage <= 1;
}
// ... (rest of your existing code) ...
Explanation:
fetchAndLoadText(textName):
Fetches the selected text from the server.
Calls loadTextContent(textContent) to process the text.
loadTextContent(textContent):
Splits the text into individual words.
Divides the words into pages based on the specified wordsPerPage.
Initializes pagination variables and displays the first page using displayTextPage(currentTextPage).
displayTextPage(pageNumber):
Clears the current content in textContainer.
Validates the page number.
Creates word elements (<span>) for each word on the page.
Adds an event listener to each word to trigger updateBubble(event) when clicked.
Updates the current page indicator.
Pagination Functions:
nextTextPage() and prevTextPage() handle moving between pages.
updateTextPaginationControls() enables or disables pagination buttons based on the current page.
Notes:
Clickable Words:
Each word is wrapped in a <span> element with an event listener for the click event.
When a word is clicked, it triggers the updateBubble(event) function.
The updateBubble function is assumed to be implemented already, as per your instruction.
Pagination:
You can adjust the wordsPerPage variable to control how many words appear on each page.
The total number of pages is calculated, and the current page is tracked.
HTML Elements:
The textContainer div is where the text content is displayed.
The paginationControls div contains the next and previous buttons, as well as the current page indicator.
Styling:
Optional CSS classes (like .word) can be added to style the words.
Existing Functions:
This implementation relates to the functions you've already provided, such as showAlert and the initial setup in fetchAndLoadText(textName). It extends the logic to include paginating the text and making words clickable.
Assumptions:
Functions like updateBubble(event) and showAlert(message, type) are already implemented.
The server endpoints /user/get_text_by_name and /user/get_texts_for_insert_words_to_text are functional and return the expected data.
With this setup, users can navigate through the text as if reading a book, with pages they can flip through. Clicking on any word will trigger the updateBubble(event) function, allowing for interaction such as showing a contextual menu or performing some action related to the word.
Make sure to integrate this code with your existing codebase carefully, ensuring that variable names and function calls are consistent throughout your application.