define(['util', 'options', 'nwSearchFnt', 'searchHistoryItems', 'localization', 'jquery', 'jquery.highlight', 'jquery.bootpag'], function(util, options, nwSearchFnt, searchHistory, i18n, $) { /* Oxygen WebHelp Plugin Copyright (c) 1998-2020 Syncro Soft SRL, Romania. All rights reserved. */ var txt_browser_not_supported = "Your browser is not supported. Use of Mozilla Firefox is recommended."; /** * Constant with maximum search items presented for a single page. * @type {number} */ var maxItemsPerPage = 10; /** * Variable with total page number. * * @type {number} */ var totalPageNumber = -1; /** * Last displayed search results items. * @type {Array} */ var lastSearchResultItems = []; /** * Last displayed search result. * @type {Array} */ var lastSearchResult; /** * When it is true, then the score is displayed as tooltip. * * @type {boolean} */ var displayScore = false; if(typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return $.trim(this); } } $(document).ready(function () { var searchQuery = ''; try { searchQuery = util.getParameter('searchQuery'); searchQuery = decodeURIComponent(searchQuery); searchQuery = searchQuery.replace(/\+/g, " "); if (searchQuery.trim()!='' && searchQuery!==undefined && searchQuery!='undefined') { $('#textToSearch').val(searchQuery); util.debug("Execute search"); executeQuery(); util.debug("Executed search"); } } catch (e) { util.debug("#########", e); } $('.gcse-searchresults-only').attr('data-queryParameterName', 'searchQuery'); // Select page from parameter in the pages widget window.onpopstate = function(event) { if (lastSearchResultItems != null && lastSearchResult != null) { // Get the value for the 'page' parameter var pageToShow = util.getParameter("page"); // Set to 1 if it is undefined if (pageToShow == undefined || pageToShow == "undefined" || pageToShow == "") { pageToShow = 1; } else { pageToShow = parseInt(pageToShow); if (isNaN(pageToShow)) { pageToShow = 1; } } displayPageResults(pageToShow); // Update the active page $('.pagination li[class~="active"]').removeClass("active"); $('.pagination li[data-lp="' + pageToShow + '"]:not([class~="prev"]):not([class~="next"])').addClass("active"); } }; $('#searchForm').on('submit', function(event){ util.debug('submit form....'); if ($('#textToSearch').val().trim()=='') { event.preventDefault(); event.stopPropagation(); return false; } }); }); /** * @description Search using Google Search if it is available, otherwise use our search engine to execute the query * @return {boolean} Always return false */ function executeQuery() { util.debug("executeQuery"); var input = document.getElementById('textToSearch'); try { var element = google.search.cse.element.getElement('searchresults-only0'); } catch (e) { util.debug(e); } if (element != undefined) { if (input.value == '') { element.clearAllResults(); } else { element.execute(input.value); } } else { executeSearchQuery($("#textToSearch").val()); } return false; } function clearHighlights() { } /** * Execute search query with internal search engine. * * @description This function find all matches using the search term * @param {HTMLObjectElement} ditaSearch_Form The search form from WebHelp page as HTML Object */ function executeSearchQuery(query) { util.debug('SearchToc(..)'); // Check browser compatibility if (navigator.userAgent.indexOf("Konquerer") > -1) { alert(i18n.getLocalization(txt_browser_not_supported)); return; } searchAndDisplayResults(query); } function searchAndDisplayResults(query) { nwSearchFnt.performSearch(query, function(searchResult) { if (searchResult.searchExpression.trim().length > 0 || searchResult.excluded.length > 0) { displayResults(searchResult); } else { var error = searchResult.error; if (typeof error != "undefined" && error.length > 0) { displayErrors(searchResult.error); } } }); } /** * @description Display errors in HTML format * @param {string} errorMsg */ function displayErrors(errorMsg) { var searchResultHTML = $('
'); searchResultHTML.addClass('errorMessage') .html(errorMsg); $('#searchResults').html(searchResultHTML); } /** * @description Display results in HTML format * @param {SearchResult} searchResult The search result. */ function displayResults(searchResult) { preprocessSearchResult(searchResult, 'wh-responsive'); // Add search query to history searchHistory.addSearchQueryToHistory(searchResult.originalSearchExpression); var webhelpEnableSearchPagination = options.getBoolean("webhelp.search.enable.pagination"); var webhelpSearchNumberOfItems = options.getInteger("webhelp.search.page.numberOfItems"); if (webhelpEnableSearchPagination !== 'undefined' && webhelpEnableSearchPagination == false) { // WH-1470 - Search pagination is disabled maxItemsPerPage = Number.MAX_VALUE; } else if (typeof webhelpSearchNumberOfItems !== 'undefined') { // WH-1471 - Option to control the maximum numbers of items displayed for each page maxItemsPerPage = webhelpSearchNumberOfItems; } // Compute the total page number totalPageNumber = Math.ceil(lastSearchResultItems.length / maxItemsPerPage); // Get the value for the 'page' parameter var pageToShow = util.getParameter("page"); // Set to 1 if it is undefined if (pageToShow == undefined || pageToShow == "undefined" || pageToShow == "") { pageToShow = 1; } else { pageToShow = parseInt(pageToShow); if (isNaN(pageToShow)) { pageToShow = 1; } } // Display a page displayPageResults(pageToShow); if (totalPageNumber > 1) { // Add pagination widget $('#wh-search-pagination').bootpag({ total: totalPageNumber, // total pages page: pageToShow, // default page maxVisible: 10, // visible pagination leaps: false, // next/prev leaps through maxVisible next: i18n.getLocalization("next.page"), prev: i18n.getLocalization("prev.page") }).on("page", function(event, num){ util.debug("Display page with number: ", num); // Replace or add the page query var oldPage = util.getParameter("page"); var oldQuery = window.location.search; var oldHref = window.location.href; var oldLocation = oldHref.substr(0, oldHref.indexOf(oldQuery)); var newQuery = ""; if (oldPage == undefined || oldPage == "undefined" || oldPage == "") { newQuery = oldQuery + "&page=" + num; } else { var re = new RegExp("(\\?|&)page\=" + oldPage); newQuery = oldQuery.replace(re, "$1page="+num); } window.history.pushState("searchPage" + num, document.title, oldLocation + newQuery); displayPageResults(num); /*$("#content").html("Page " + num); // or some ajax content loading... // ... after content load -> change total to 10 $(this).bootpag({total: 10, maxVisible: 10});*/ }); } // make bootpag compatible with Bootstrap 4.0 $('#wh-search-pagination').find('li').addClass('page-item'); $('#wh-search-pagination').find('a').addClass('page-link'); $("#search").trigger('click'); } /** * Display search results for a specific page. * * @param pageIdx The page index. */ function displayPageResults(pageIdx) { var searchResultHTML = computeHTMLResult('wh-responsive', pageIdx, totalPageNumber, maxItemsPerPage); $('#searchResults').html(searchResultHTML); window.scrollTo(0, 0); } /*************************************************************************************** ******************************* searchCommon.js**************************************** **************************************************************************************/ /** * An object containing the search result for a single topic/HTML page. * Contains pointer to the topicID, title, short description and the list of words that were found. * * @param {string} topicID The ID of the topic. Can be used to identify unique a document in the search result. * @param {string} relativePath The relative path to the topic. * @param {string} title The topic title. * @param {string} shortDescription The topic short description. * @param {[string]} words The array with words contained by this topic. * @param {int} scoring The search scoring computed for this document. * @param {int} startsWith The number used to display 5 stars ranking. * @param {int} resultID The search result ID. * @param {int} linkID The search link ID. * @param {[TopicInfo]} breadcrumb The breadcrumb of current document. Can be []. * @constructor */ function SearchResultInfo(topicID, relativePath, title, shortDescription, words, scoring, starWidth, resultID, linkID, breadcrumb) { this.topicID = topicID; this.relativePath = relativePath; this.title = title; this.shortDescription = shortDescription; this.words = words; this.scoring = scoring; this.starWidth = starWidth; this.resultID = resultID; this.linkID = linkID; this.similarResults = []; this.breadcrumb = breadcrumb; } /** * Pre process search result to compute similar results and scoring. * The lastSearchResultItems variable will be updated. * * @param searchResult The seach result to process. * @param whDistribution The WebHelp distribution. */ function preprocessSearchResult(searchResult, whDistribution) { lastSearchResult = searchResult; lastSearchResultItems = []; var wh_mobile = (typeof whDistribution != 'undefined') && whDistribution == 'wh-mobile'; var wh_Classic = (typeof whDistribution != 'undefined') && whDistribution == 'wh-classic'; if (searchResult.documents !== undefined && searchResult.documents.length > 0) { var allPages = searchResult.documents; // WH-1943 - sort by scoring, title and short description allPages.sort(function (first, second) { var cRes = second.scoring -first.scoring; if (cRes == 0) { cRes = second.title.localeCompare(first.title); if (cRes == 0) { cRes = second.shortDescription.localeCompare(first.shortDescription); } } return cRes; }); // The score for fist item var ttScore_first = 1; if (allPages.length > 0) { ttScore_first = allPages[0].scoring; } var currentSimilarPage={}; for (var page = 0; page < allPages.length; page++) { /*debug("Page number: " + page);*/ if (allPages[page].relativePath == 'toc.html') { continue; } var starWidth = 0; var webhelpSearchRanking = options.getBoolean("webhelp.search.ranking"); if (typeof webhelpSearchRanking != "undefined" && webhelpSearchRanking) { var hundredPercent = allPages[page].scoring + 100 * allPages[page].words.length; var numberOfWords = allPages[page].words.length; /*debug("hundredPercent: " + hundredPercent + "; ttScore_first: " + ttScore_first + "; numberOfWords: " + numberOfWords);*/ var ttScore = allPages[page].scoring; // Fake value var maxNumberOfWords = allPages[page].words.length; starWidth = (ttScore * 100 / hundredPercent) / (ttScore_first / hundredPercent) * (numberOfWords / maxNumberOfWords); starWidth = starWidth < 10 ? (starWidth + 5) : starWidth; // Keep the 5 stars format if (starWidth > 85) { starWidth = 85; } } var idLink = 'foundLink' + page; var idResult = 'foundResult' + page; // topicID, relativePath, title, shortDescription, words, scoring, starWidth, resultID, linkID, similarResults util.debug("page", page); var csri = new SearchResultInfo( allPages[page].topicID, allPages[page].relativePath, allPages[page].title, allPages[page].shortDescription, allPages[page].words, allPages[page].scoring, starWidth, idResult, idLink, allPages[page].breadcrumb ); // Similar pages var similarPages = !wh_mobile && similarPage(allPages[page], allPages[page - 1]); if (!similarPages) { currentSimilarPage = csri; lastSearchResultItems.push(csri); } else { currentSimilarPage.similarResults.push(csri); } } } } /** * Compute the HTML to be displayed in the search results page. * * @param whDistribution The string with WebHelp distribution. One of wh-classic, wh-mobile or wh-responsive. * @param pageNumber The page number to display. * @param totalPageNumber The total page number. * @param itemsPerPage The number of items to display on a page. * @returns {string} The HTML to be displayed as search result. */ function computeHTMLResult(whDistribution, pageNumber, totalPageNumber, itemsPerPage) { // Empty jQuery element var results = $(); var $wh_search_results_items = $(); if (lastSearchResult.searchExpression.length > 0) { if (lastSearchResultItems.length > 0) { $wh_search_results_items = $('', { class: 'wh_search_results_items' }); // Start and end index depending on the current presented page var s = 0; var e = lastSearchResultItems.length; if (typeof pageNumber != "undefined" && typeof itemsPerPage != "undefined") { s = (pageNumber - 1) * itemsPerPage; var next = s + itemsPerPage; e = Math.min(next, lastSearchResultItems.length); } // Result for: word1 word2 var txt_results_for = "Results for:"; var $headerHTML = $('', { class: 'wh_search_results_header' }); var $whSearchResultsHeaderDocs = $('', { class: 'wh_search_results_header_docs' }).html( lastSearchResultItems.length + ' ' + i18n.getLocalization(txt_results_for) + ' ' ); var $span = $('', { class: 'wh_search_expression' }).html(lastSearchResult.originalSearchExpression); $whSearchResultsHeaderDocs.append($span); $headerHTML.append($whSearchResultsHeaderDocs); if (typeof pageNumber != "undefined" && typeof totalPageNumber != "undefined" && totalPageNumber > 1) { var $wh_search_results_header_pages = $('', { class: 'wh_search_results_header_pages' }).html(i18n.getLocalization('Page') + ' ' + pageNumber + '/' + totalPageNumber); $headerHTML.append($wh_search_results_header_pages); } $wh_search_results_items.append($headerHTML); // EXM-38967 Start numbering var start = (pageNumber - 1) * 10 + 1; var $ol = $('