coveo-search-ui
Version:
Coveo JavaScript Search Framework
1,054 lines (1,016 loc) • 122 kB
JavaScript
webpackJsonpCoveo__temporary([16,19],{
/***/ 118:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Component_1 = __webpack_require__(7);
var ResultList_1 = __webpack_require__(93);
var Dom_1 = __webpack_require__(1);
var underscore_1 = __webpack_require__(0);
var Logger_1 = __webpack_require__(9);
var ResultListUtils = /** @class */ (function () {
function ResultListUtils() {
}
ResultListUtils.hideIfInfiniteScrollEnabled = function (cmp) {
var infiniteScrollEnabled = ResultListUtils.isInfiniteScrollEnabled(cmp.searchInterface.element);
if (infiniteScrollEnabled) {
cmp.disable();
Dom_1.$$(cmp.element).hide();
ResultListUtils.warnIfComponentNotNeeded(cmp);
}
else {
cmp.enable();
Dom_1.$$(cmp.element).unhide();
}
};
ResultListUtils.isInfiniteScrollEnabled = function (root) {
var resultList = ResultListUtils.getMainResultList(root);
return resultList ? !!resultList.options.enableInfiniteScroll : false;
};
ResultListUtils.scrollToTop = function (root) {
var resultList = ResultListUtils.getMainResultList(root);
if (!resultList) {
new Logger_1.Logger(this).warn('No active ResultList, scrolling to the top of the Window');
return window.scrollTo(0, 0);
}
var searchInterfacePosition = resultList.searchInterface.element.getBoundingClientRect().top;
if (searchInterfacePosition > 0) {
return;
}
window.scrollTo(0, window.pageYOffset + searchInterfacePosition);
};
ResultListUtils.getMainResultList = function (root) {
var resultLists = ResultListUtils.getResultLists(root);
return underscore_1.find(resultLists, function (resultList) {
var isRecInterface = resultList.searchInterface.element.classList.contains('CoveoRecommendation');
return !resultList.disabled && !isRecInterface;
});
};
ResultListUtils.getResultLists = function (root) {
return Dom_1.$$(root)
.findAll("." + ResultListUtils.cssClass())
.map(function (el) { return Component_1.Component.get(el, ResultList_1.ResultList); });
};
ResultListUtils.cssClass = function () {
return Component_1.Component.computeCssClassName(ResultList_1.ResultList);
};
ResultListUtils.warnIfComponentNotNeeded = function (cmp) {
var root = cmp.searchInterface.root;
var allListsUseInfiniteScroll = ResultListUtils.allResultListsUseInfiniteScroll(root);
allListsUseInfiniteScroll && ResultListUtils.notNeededComponentWarning(cmp);
};
ResultListUtils.allResultListsUseInfiniteScroll = function (root) {
var listsWithInfiniteScrollDisabled = ResultListUtils.getResultLists(root).filter(function (resultList) { return !resultList.options.enableInfiniteScroll; });
return listsWithInfiniteScrollDisabled.length === 0;
};
ResultListUtils.notNeededComponentWarning = function (cmp) {
var cmpCssClass = Component_1.Component.computeCssClassNameForType(cmp.type);
var message = "The " + cmpCssClass + " component is not needed because all " + ResultListUtils.cssClass() + " components have enableInfiniteScroll set to 'true'.\n For the best performance, remove the " + cmpCssClass + " component from your search page.";
new Logger_1.Logger(cmp).warn(message);
};
return ResultListUtils;
}());
exports.ResultListUtils = ResultListUtils;
/***/ }),
/***/ 215:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Component_1 = __webpack_require__(7);
var _ = __webpack_require__(0);
var ResultListRenderer = /** @class */ (function () {
function ResultListRenderer(resultListOptions, autoCreateComponentsFn) {
this.resultListOptions = resultListOptions;
this.autoCreateComponentsFn = autoCreateComponentsFn;
}
ResultListRenderer.prototype.renderResults = function (resultElements, append, resultDisplayedCallback) {
var _this = this;
if (append === void 0) { append = false; }
return Promise.all([this.getStartFragment(resultElements, append), this.getEndFragment(resultElements, append)]).then(function (_a) {
var startFrag = _a[0], endFrag = _a[1];
var resultsFragment = document.createDocumentFragment();
if (startFrag) {
resultsFragment.appendChild(startFrag);
}
_.each(resultElements, function (resultElement) {
resultsFragment.appendChild(resultElement);
resultDisplayedCallback(Component_1.Component.getResult(resultElement), resultElement);
});
if (endFrag) {
resultsFragment.appendChild(endFrag);
}
_this.resultListOptions.resultsContainer.appendChild(resultsFragment);
});
};
ResultListRenderer.prototype.getStartFragment = function (resultElements, append) {
return Promise.resolve(document.createDocumentFragment());
};
ResultListRenderer.prototype.getEndFragment = function (resultElements, append) {
return Promise.resolve(document.createDocumentFragment());
};
return ResultListRenderer;
}());
exports.ResultListRenderer = ResultListRenderer;
/***/ }),
/***/ 264:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(638);
var QueryEvents_1 = __webpack_require__(11);
var ResultListEvents_1 = __webpack_require__(29);
var GlobalExports_1 = __webpack_require__(3);
var Assert_1 = __webpack_require__(5);
var Model_1 = __webpack_require__(18);
var QueryStateModel_1 = __webpack_require__(13);
var Strings_1 = __webpack_require__(6);
var AccessibleButton_1 = __webpack_require__(15);
var DeviceUtils_1 = __webpack_require__(24);
var Dom_1 = __webpack_require__(1);
var ResultListUtils_1 = __webpack_require__(118);
var SVGDom_1 = __webpack_require__(16);
var SVGIcons_1 = __webpack_require__(12);
var AnalyticsActionListMeta_1 = __webpack_require__(10);
var Component_1 = __webpack_require__(7);
var ComponentOptions_1 = __webpack_require__(8);
var Initialization_1 = __webpack_require__(2);
/**
* The Pager component attaches itself to a `div` element and renders widgets that allow the end user to navigate
* through the different result pages.
*
* This component takes care of triggering a query with the correct result range whenever the end user selects a page or
* uses the navigation buttons (**Previous** and **Next**).
*/
var Pager = /** @class */ (function (_super) {
__extends(Pager, _super);
/**
* Creates a new Pager. Binds multiple query events ({@link QueryEvents.newQuery}, {@link QueryEvents.buildingQuery},
* {@link QueryEvents.querySuccess}, {@link QueryEvents.queryError} and {@link QueryEvents.noResults}. Renders itself
* on every query success.
* @param element The HTMLElement on which to instantiate the component (normally a `div`).
* @param options The options for the Pager component.
* @param bindings The bindings that the component requires to function normally. If not set, these will be
* automatically resolved (with a slower execution time).
*/
function Pager(element, options, bindings) {
var _this = _super.call(this, element, Pager.ID, bindings) || this;
_this.element = element;
_this.options = options;
_this.listenToQueryStateChange = true;
_this.ignoreNextQuerySuccess = false;
// The normal behavior of this component is to reset to page 1 when a new
// query is performed by other components (i.e. not pagers).
//
// This behavior is overridden when the 'first' state is
// programmatically modified.
_this.needToReset = true;
_this.options = ComponentOptions_1.ComponentOptions.initComponentOptions(element, Pager, options);
_this.currentPage = 1;
_this.bind.onRootElement(QueryEvents_1.QueryEvents.newQuery, function (args) { return _this.handleNewQuery(args); });
_this.bind.onRootElement(QueryEvents_1.QueryEvents.buildingQuery, function (args) { return _this.handleBuildingQuery(args); });
_this.bind.onRootElement(QueryEvents_1.QueryEvents.querySuccess, function (args) { return _this.handleQuerySuccess(args); });
_this.bind.onRootElement(QueryEvents_1.QueryEvents.queryError, function () { return _this.handleQueryError(); });
_this.bind.onRootElement(QueryEvents_1.QueryEvents.noResults, function (args) { return _this.handleNoResults(args); });
_this.bind.onQueryState(Model_1.MODEL_EVENTS.CHANGE_ONE, QueryStateModel_1.QUERY_STATE_ATTRIBUTES.FIRST, function (data) {
return _this.handleQueryStateFirstResultChanged(data);
});
_this.bind.onQueryState(Model_1.MODEL_EVENTS.CHANGE_ONE, QueryStateModel_1.QUERY_STATE_ATTRIBUTES.NUMBER_OF_RESULTS, function (data) {
return _this.handleQueryStateNumberOfResultsPerPageChanged(data);
});
_this.addAlwaysActiveListeners();
_this.addAccessibilityAttributes();
_this.list = Dom_1.$$('ul', {
className: 'coveo-pager-list'
}).el;
element.appendChild(_this.list);
return _this;
}
Object.defineProperty(Pager.prototype, "currentPage", {
/**
* The current page (1-based index).
*/
get: function () {
return this._currentPage;
},
set: function (value) {
var sanitizedValue = value;
if (isNaN(value)) {
this.logger.warn("Unable to set pager current page to an invalid value: " + value + ". Resetting to 1.");
sanitizedValue = 1;
}
sanitizedValue = Math.max(Math.min(sanitizedValue, this.getMaxNumberOfPagesForCurrentResultsPerPage()), 1);
sanitizedValue = Math.floor(sanitizedValue);
this._currentPage = sanitizedValue;
},
enumerable: true,
configurable: true
});
/**
* Sets the current page, then executes a query.
*
* Also logs an event in the usage analytics (`pageNumber` by default) with the new current page number as meta data.
*
* @param pageNumber The page number to navigate to.
* @param analyticCause The event to log in the usage analytics.
*/
Pager.prototype.setPage = function (pageNumber, analyticCause) {
if (analyticCause === void 0) { analyticCause = AnalyticsActionListMeta_1.analyticsActionCauseList.pagerNumber; }
Assert_1.Assert.exists(pageNumber);
this.currentPage = pageNumber;
this.updateQueryStateModel(this.getFirstResultNumber(this.currentPage));
this.usageAnalytics.logCustomEvent(analyticCause, { pagerNumber: this.currentPage }, this.element);
this.queryController.executeQuery({
ignoreWarningSearchEvent: true,
keepLastSearchUid: true,
origin: this
});
};
/**
* Navigates to the previous page, then executes a query.
*
* Also logs the `pagePrevious` event in the usage analytics with the new current page number as meta data.
*/
Pager.prototype.previousPage = function () {
this.setPage(this.currentPage - 1, AnalyticsActionListMeta_1.analyticsActionCauseList.pagerPrevious);
};
/**
* Navigates to the next page, then executes a query.
*
* Also logs the `pageNext` event in the usage analytics with the new current page number as meta data.
*/
Pager.prototype.nextPage = function () {
this.setPage(this.currentPage + 1, AnalyticsActionListMeta_1.analyticsActionCauseList.pagerNext);
};
Pager.prototype.addAccessibilityAttributes = function () {
if (!this.element.getAttribute('role')) {
this.element.setAttribute('role', 'navigation');
}
if (!this.element.hasAttribute('aria-label')) {
this.element.setAttribute('aria-label', Strings_1.l('Pagination'));
}
};
Pager.prototype.addAlwaysActiveListeners = function () {
var _this = this;
this.searchInterface.element.addEventListener(ResultListEvents_1.ResultListEvents.newResultsDisplayed, function () {
return ResultListUtils_1.ResultListUtils.hideIfInfiniteScrollEnabled(_this);
});
};
Pager.prototype.getMaxNumberOfPagesForCurrentResultsPerPage = function () {
return Math.ceil(this.options.maximumNumberOfResultsFromIndex / this.searchInterface.resultsPerPage);
};
Pager.prototype.handleNewQuery = function (data) {
var triggeredByPagerOrDebugMode = data && data.origin && (data.origin.type == Pager.ID || data.origin.type == 'Debug');
if (this.needToReset && !triggeredByPagerOrDebugMode) {
this.currentPage = 1;
this.updateQueryStateModel(this.getFirstResultNumber(this.currentPage));
}
this.needToReset = true;
};
Pager.prototype.updateQueryStateModel = function (attrValue) {
this.listenToQueryStateChange = false;
this.queryStateModel.set(QueryStateModel_1.QueryStateModel.attributesEnum.first, attrValue);
this.listenToQueryStateChange = true;
};
Pager.prototype.handleQueryError = function () {
this.reset();
};
Pager.prototype.handleQuerySuccess = function (data) {
var _this = this;
this.reset();
if (this.ignoreNextQuerySuccess) {
this.ignoreNextQuerySuccess = false;
}
else {
Assert_1.Assert.isNotUndefined(data);
var firstResult = data.query.firstResult;
var count = data.results.totalCountFiltered;
var pagerBoundary = this.computePagerBoundary(firstResult, count);
this.currentPage = pagerBoundary.currentPage;
if (pagerBoundary.end - pagerBoundary.start > 0) {
var _loop_1 = function (i) {
var page = i;
var isCurrentPage = page === this_1.currentPage;
var button = Dom_1.$$('span', {
className: 'coveo-pager-list-item-text coveo-pager-anchor',
tabindex: 0,
ariaPressed: "" + isCurrentPage
}, i.toString(10)).el;
var listItem = Dom_1.$$('li', {
className: 'coveo-pager-list-item'
}).el;
if (isCurrentPage) {
Dom_1.$$(listItem).addClass('coveo-active');
button.setAttribute('aria-current', 'page');
}
var clickAction = function (e) {
e.stopPropagation();
_this.handleClickPage(page);
};
new AccessibleButton_1.AccessibleButton()
.withElement(button)
.withLabel(Strings_1.l('PageNumber', i.toString(10)))
.withClickAction(clickAction)
.withEnterKeyboardAction(clickAction)
.build();
Dom_1.$$(listItem).on('click', function (e) { return clickAction(e); });
listItem.appendChild(button);
this_1.list.appendChild(listItem);
};
var this_1 = this;
for (var i = pagerBoundary.start; i <= pagerBoundary.end; i++) {
_loop_1(i);
}
if (this.options.enableNavigationButton && pagerBoundary.lastResultPage > 1) {
this.renderNavigationButton(pagerBoundary);
}
}
}
};
Pager.prototype.handleNoResults = function (data) {
var lastValidPage;
if (data.results.totalCount > 0) {
// First scenario : The index returned less results than expected (because of folding).
// Recalculate the last valid page, and change to that new page.
var possibleValidPage = this.computePagerBoundary(data.results.totalCountFiltered, data.results.totalCount).lastResultPage;
if (this.currentPage > possibleValidPage) {
lastValidPage = possibleValidPage;
}
}
else if (this.currentPage > this.getMaxNumberOfPagesForCurrentResultsPerPage()) {
// Second scenario : Someone tried to access a non-valid page by the URL for example, which is higher than the current possible with the number of
// possible results. The last valid page will be the maximum number of results avaiable from the index.
lastValidPage = this.getMaxNumberOfPagesForCurrentResultsPerPage();
}
// This needs to be deferred because we still want all the "querySuccess" callbacks the complete their execution
// before triggering/queuing the next query;
// if we cannot find a lastValidPage to go to, do nothing : this means it's a query that simply return nothing.
if (lastValidPage != null) {
this.currentPage = lastValidPage;
data.retryTheQuery = true;
this.needToReset = false;
this.ignoreNextQuerySuccess = false;
this.updateQueryStateModel(this.getFirstResultNumber(this.currentPage));
}
};
Pager.prototype.reset = function () {
Dom_1.$$(this.list).empty();
};
Pager.prototype.handleBuildingQuery = function (data) {
Assert_1.Assert.exists(data);
var eventArgs = this.getQueryEventArgs();
data.queryBuilder.firstResult = eventArgs.first;
// Set the number of results only if it was not already set by external code
// Most of the time this will be set by either : the SearchInterface with the resultsPerPage option
// Or by the ResultsPerPage component (so the end user decides).
// Pager will realistically never set this value itself.
if (data.queryBuilder.numberOfResults == null) {
data.queryBuilder.numberOfResults = eventArgs.count;
}
var maxResultNumber = data.queryBuilder.firstResult + data.queryBuilder.numberOfResults;
var numOfExcessResults = Math.max(0, maxResultNumber - this.options.maximumNumberOfResultsFromIndex);
data.queryBuilder.numberOfResults -= numOfExcessResults;
};
Pager.prototype.computePagerBoundary = function (firstResult, totalCount) {
var resultPerPage = this.searchInterface.resultsPerPage;
var currentPage = Math.floor(firstResult / resultPerPage) + 1;
var lastPageNumber = Math.max(Math.min(Math.ceil(totalCount / resultPerPage), this.getMaxNumberOfPagesForCurrentResultsPerPage()), 1);
var halfLength = Math.floor(this.options.numberOfPages / 2);
var firstPageNumber = Math.max(Math.min(currentPage - halfLength, lastPageNumber - this.options.numberOfPages + 1), 1);
var endPageNumber = Math.min(firstPageNumber + this.options.numberOfPages - 1, lastPageNumber);
return {
start: firstPageNumber,
end: endPageNumber,
lastResultPage: lastPageNumber,
currentPage: currentPage
};
};
Pager.prototype.renderNavigationButton = function (pagerBoundary) {
if (this.currentPage > 1) {
var previous = this.renderPreviousButton();
this.list.insertBefore(previous.el, this.list.firstChild);
}
if (this.currentPage < pagerBoundary.lastResultPage) {
var next = this.renderNextButton();
this.list.appendChild(next.el);
}
};
Pager.prototype.renderPreviousButton = function () {
var _this = this;
var previousListItem = Dom_1.$$('li', {
className: 'coveo-pager-previous coveo-pager-anchor coveo-pager-list-item'
});
var previousButton = Dom_1.$$('span', {
title: Strings_1.l('Previous'),
tabindex: 0
});
var previousIcon = Dom_1.$$('span', {
className: 'coveo-pager-previous-icon'
}, SVGIcons_1.SVGIcons.icons.pagerLeftArrow);
SVGDom_1.SVGDom.addClassToSVGInContainer(previousIcon.el, 'coveo-pager-previous-icon-svg');
previousButton.append(previousIcon.el);
previousListItem.append(previousButton.el);
new AccessibleButton_1.AccessibleButton()
.withElement(previousButton)
.withLabel(Strings_1.l('Previous'))
.withSelectAction(function () { return _this.handleClickPrevious(); })
.build();
return previousListItem;
};
Pager.prototype.renderNextButton = function () {
var _this = this;
var nextListItem = Dom_1.$$('li', {
className: 'coveo-pager-next coveo-pager-anchor coveo-pager-list-item'
});
var nextButton = Dom_1.$$('span', {
title: Strings_1.l('Next'),
tabindex: 0
});
var nextIcon = Dom_1.$$('span', {
className: 'coveo-pager-next-icon'
}, SVGIcons_1.SVGIcons.icons.pagerRightArrow);
SVGDom_1.SVGDom.addClassToSVGInContainer(nextIcon.el, 'coveo-pager-next-icon-svg');
nextButton.append(nextIcon.el);
nextListItem.append(nextButton.el);
new AccessibleButton_1.AccessibleButton()
.withElement(nextButton)
.withLabel(Strings_1.l('Next'))
.withSelectAction(function () { return _this.handleClickNext(); })
.build();
return nextListItem;
};
Pager.prototype.handleQueryStateFirstResultChanged = function (data) {
if (!this.listenToQueryStateChange) {
return;
}
Assert_1.Assert.exists(data);
this.needToReset = false;
var firstResult = data.value;
this.currentPage = this.fromFirstResultsToPageNumber(firstResult);
};
Pager.prototype.handleQueryStateNumberOfResultsPerPageChanged = function (data) {
var firstResult = this.queryStateModel.get(QueryStateModel_1.QUERY_STATE_ATTRIBUTES.FIRST);
this.searchInterface.resultsPerPage = data.value;
this.currentPage = this.fromFirstResultsToPageNumber(firstResult);
};
Pager.prototype.handleClickPage = function (pageNumber) {
Assert_1.Assert.exists(pageNumber);
this.setPage(pageNumber);
};
Pager.prototype.handleClickPrevious = function () {
this.previousPage();
};
Pager.prototype.handleClickNext = function () {
this.nextPage();
};
Pager.prototype.fromFirstResultsToPageNumber = function (firstResult) {
return firstResult / this.searchInterface.resultsPerPage + 1;
};
Pager.prototype.getFirstResultNumber = function (pageNumber) {
if (pageNumber === void 0) { pageNumber = this.currentPage; }
return (pageNumber - 1) * this.searchInterface.resultsPerPage;
};
Pager.prototype.getQueryEventArgs = function () {
return {
count: this.searchInterface.resultsPerPage,
first: this.getFirstResultNumber()
};
};
Pager.ID = 'Pager';
Pager.doExport = function () {
GlobalExports_1.exportGlobally({
Pager: Pager
});
};
/**
* The options for the Pager
* @componentOptions
*/
Pager.options = {
/**
* Specifies how many page links to display in the pager.
*
* Default value is `5` on a desktop computers and `3` on a mobile device. Minimum value is `1`.
*/
numberOfPages: ComponentOptions_1.ComponentOptions.buildNumberOption({
defaultFunction: function () {
if (DeviceUtils_1.DeviceUtils.isMobileDevice()) {
return 3;
}
else {
return 5;
}
},
min: 1
}),
/**
* Specifies whether the **Previous** and **Next** buttons should appear at each end of the pager when appropriate.
*
* The default value is `true`.
*/
enableNavigationButton: ComponentOptions_1.ComponentOptions.buildBooleanOption({ defaultValue: true }),
/**
* Specifies the maximum number of pages to display if enough results are available.
*
* This property is typically set when the default number of accessible results from the index has been changed from its default value of `1000` (10 results per page X 100 `maxNumberOfPages`).
* Default value is `100`
*
* @deprecated This is a deprecated option. The `Pager` now automatically adapts itself on each new query, so you no longer need to specify a value for this option. However, if the default maximum number of accessible results value was changed on your Coveo index, you should use the [`maximumNumberOfResultsFromIndex`]{@link Pager.options.maximumNumberOfResultsFromIndex} option to specify the new value.
*/
maxNumberOfPages: ComponentOptions_1.ComponentOptions.buildNumberOption({
defaultValue: undefined,
deprecated: 'This is a deprecated option. The pager will automatically adapt itself on each new query. You no longer need to specify this option. Use maximumNumberOfResultsFromIndex instead.'
}),
/**
* Specifies the maximum number of results that the index can return for any query.
*
* Default value is `1000` in a Coveo index.
*
* If this value was modified in your Coveo index, you must specify the new value in this option for the Pager component to work properly
*/
maximumNumberOfResultsFromIndex: ComponentOptions_1.ComponentOptions.buildNumberOption({
defaultValue: 1000
})
};
return Pager;
}(Component_1.Component));
exports.Pager = Pager;
Initialization_1.Initialization.registerAutoCreateComponent(Pager);
/***/ }),
/***/ 40:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/// <reference path='Facet.ts' />
var StringUtils_1 = __webpack_require__(22);
var QueryUtils_1 = __webpack_require__(21);
var FileTypes_1 = __webpack_require__(121);
var DateUtils_1 = __webpack_require__(33);
var Utils_1 = __webpack_require__(4);
var Dom_1 = __webpack_require__(1);
var _ = __webpack_require__(0);
var Strings_1 = __webpack_require__(6);
var FacetUtils = /** @class */ (function () {
function FacetUtils() {
}
FacetUtils.getRegexToUseForFacetSearch = function (value, ignoreAccent) {
return new RegExp(StringUtils_1.StringUtils.stringToRegex(value, ignoreAccent), 'i');
};
FacetUtils.getDisplayValueFromValueCaption = function (value, field, valueCaption) {
var returnValue = this.tryToGetTranslatedCaption(field, value, false);
return valueCaption[value] || returnValue;
};
FacetUtils.getValuesToUseForSearchInFacet = function (original, facet) {
var ret = [original];
var regex = this.getRegexToUseForFacetSearch(original, facet.options.facetSearchIgnoreAccents);
if (facet.options.valueCaption) {
_.chain(facet.options.valueCaption)
.pairs()
.filter(function (pair) {
return regex.test(pair[1]);
})
.each(function (match) {
ret.push(match[0]);
});
if (QueryUtils_1.QueryUtils.isStratusAgnosticField(facet.options.field, '@objecttype') ||
QueryUtils_1.QueryUtils.isStratusAgnosticField(facet.options.field, '@filetype')) {
_.each(FileTypes_1.FileTypes.getFileTypeCaptions(), function (value, key) {
if (!(key in facet.options.valueCaption) && regex.test(value)) {
ret.push(key);
}
});
}
}
else if (QueryUtils_1.QueryUtils.isStratusAgnosticField(facet.options.field, '@objecttype') ||
QueryUtils_1.QueryUtils.isStratusAgnosticField(facet.options.field, '@filetype')) {
_.each(_.filter(_.pairs(FileTypes_1.FileTypes.getFileTypeCaptions()), function (pair) {
return regex.test(pair[1]);
}), function (match) {
ret.push(match[0]);
});
}
else if (QueryUtils_1.QueryUtils.isStratusAgnosticField(facet.options.field, '@month')) {
_.each(_.range(1, 13), function (month) {
if (regex.test(DateUtils_1.DateUtils.monthToString(month - 1))) {
ret.push(('0' + month.toString()).substr(-2));
}
});
}
return ret;
};
FacetUtils.buildFacetSearchPattern = function (values) {
values = _.map(values, function (value) {
return Utils_1.Utils.escapeRegexCharacter(value);
});
values[0] = '.*' + values[0] + '.*';
return values.join('|');
};
FacetUtils.needAnotherFacetSearch = function (currentSearchLength, newSearchLength, oldSearchLength, desiredSearchLength) {
// Something was removed (currentSearch < newSearch)
// && we might want to display more facet search result(currentSearch < desiredSearch)
// && the new query returned more stuff than the old one so there's still more results(currentSearchLength > oldLength)
return currentSearchLength < newSearchLength && currentSearchLength < desiredSearchLength && currentSearchLength > oldSearchLength;
};
FacetUtils.addNoStateCssClassToFacetValues = function (facet, container) {
// This takes care of adding the correct css class on each facet value checkbox (empty white box) if at least one value is selected in that facet
if (facet.values.getSelected().length != 0) {
var noStates = Dom_1.$$(container).findAll('li:not(.coveo-selected)');
_.each(noStates, function (noState) {
Dom_1.$$(noState).addClass('coveo-no-state');
});
}
};
FacetUtils.tryToGetTranslatedCaption = function (field, value, fallbackOnLocalization) {
if (fallbackOnLocalization === void 0) { fallbackOnLocalization = true; }
var found;
if (QueryUtils_1.QueryUtils.isStratusAgnosticField(field.toLowerCase(), '@filetype')) {
found = FileTypes_1.FileTypes.getFileType(value, fallbackOnLocalization).caption;
}
else if (QueryUtils_1.QueryUtils.isStratusAgnosticField(field.toLowerCase(), '@objecttype')) {
found = FileTypes_1.FileTypes.getObjectType(value, fallbackOnLocalization).caption;
}
else if (FacetUtils.isMonthFieldValue(field, value)) {
var month = parseInt(value, 10);
found = DateUtils_1.DateUtils.monthToString(month - 1);
}
else if (fallbackOnLocalization) {
found = Strings_1.l(value);
}
return found != undefined && Utils_1.Utils.isNonEmptyString(found) ? found : value;
};
FacetUtils.isMonthFieldValue = function (field, value) {
if (!QueryUtils_1.QueryUtils.isStratusAgnosticField(field.toLowerCase(), '@month')) {
return false;
}
var asInt = parseInt(value, 10);
if (isNaN(asInt)) {
return false;
}
if (asInt < 1 || asInt > 12) {
return false;
}
return true;
};
return FacetUtils;
}());
exports.FacetUtils = FacetUtils;
/***/ }),
/***/ 470:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Template_1 = __webpack_require__(27);
var TemplateList_1 = __webpack_require__(96);
var _ = __webpack_require__(0);
var TableTemplate = /** @class */ (function (_super) {
__extends(TableTemplate, _super);
function TableTemplate() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.defaultTemplate = "<td><a class=\"CoveoResultLink\"></a></td>\n <td><span class=\"CoveoExcerpt\"></span></td>\n <td><span class=\"CoveoFieldValue\" data-field=\"@date\" data-helper=\"date\"></span></td>";
_this.defaultRoledTemplates = {
'table-header': "<th style=\"width: 40%\">Link</th>\n <th>Excerpt</th>\n <th style=\"width: 20%\"\n class=\"CoveoSort coveo-table-header-sort\"\n data-sort-criteria=\"date ascending,date descending\"\n data-display-unselected-icon=\"false\">Date</th>",
'table-footer': "<th>Link</th>\n <th>Excerpt</th>\n <th>Date</th>"
};
return _this;
}
TableTemplate.prototype.instantiateRoleToString = function (role) {
var roledTemplate = _.find(this.templates, function (t) { return t.role === role; });
if (roledTemplate) {
return roledTemplate.instantiateToString(undefined, {});
}
else {
return this.defaultRoledTemplates[role];
}
};
TableTemplate.prototype.instantiateRoleToElement = function (role) {
var _this = this;
var roledTemplate = _.find(this.templates, function (t) { return t.role === role; });
if (roledTemplate) {
return roledTemplate.instantiateToElement(undefined, {});
}
else {
var tmpl = new Template_1.Template(function () { return _this.defaultRoledTemplates[role]; });
tmpl.layout = 'table';
return tmpl.instantiateToElement(undefined);
}
};
TableTemplate.prototype.getFallbackTemplate = function () {
var _this = this;
return new Template_1.Template(function () { return _this.defaultTemplate; });
};
TableTemplate.prototype.hasTemplateWithRole = function (role) {
return _.find(this.templates, function (t) { return t.role === role; });
};
return TableTemplate;
}(TemplateList_1.TemplateList));
exports.TableTemplate = TableTemplate;
/***/ }),
/***/ 472:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Template_1 = __webpack_require__(27);
var DefaultRecommendationTemplate = /** @class */ (function (_super) {
__extends(DefaultRecommendationTemplate, _super);
function DefaultRecommendationTemplate() {
return _super !== null && _super.apply(this, arguments) || this;
}
DefaultRecommendationTemplate.prototype.instantiateToString = function (object) {
var template = "<div class=\"coveo-result-frame\">\n <div class=\"coveo-result-row\">\n <div class=\"coveo-result-cell\" style=\"width:40px;text-align:center;vertical-align:middle;\">\n <span class=\"CoveoIcon\" data-small=\"true\" data-with-label=\"false\">\n </span>\n </div>\n <div class=\"coveo-result-cell\" style=\"padding:0 0 3px 5px;vertical-align:middle\">\n <div class=\"coveo-result-row\">\n <div class=\"coveo-result-cell\" style=\"font-size:10pt;\">\n <a class=\"CoveoResultLink\" style=\"display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis\">\n </a>\n </div>\n </div>\n </div>\n </div>\n </div>";
return template;
};
DefaultRecommendationTemplate.prototype.instantiateToElement = function (object) {
var _this = this;
return new Promise(function (resolve, reject) {
var div = document.createElement('div');
div.innerHTML = _this.instantiateToString(object);
resolve(div);
});
};
return DefaultRecommendationTemplate;
}(Template_1.Template));
exports.DefaultRecommendationTemplate = DefaultRecommendationTemplate;
/***/ }),
/***/ 473:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var Core_1 = __webpack_require__(20);
var ResultList_1 = __webpack_require__(93);
var underscore_1 = __webpack_require__(0);
var Dom_1 = __webpack_require__(1);
var Logger_1 = __webpack_require__(9);
var TemplateToHtml = /** @class */ (function () {
function TemplateToHtml(args) {
this.args = args;
}
TemplateToHtml.prototype.buildResults = function (results, layout, currentlyDisplayedResults) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
var res, resultsPromises;
return __generator(this, function (_a) {
res = [];
resultsPromises = underscore_1.map(results.results, function (result, index) {
return _this.buildResult(result, layout, currentlyDisplayedResults).then(function (resultElement) {
if (resultElement != null) {
res.push({ elem: resultElement, idx: index });
}
ResultList_1.ResultList.resultCurrentlyBeingRendered = null;
return resultElement;
});
});
// We need to sort by the original index order, because in lazy loading mode, it's possible that results does not gets rendered
// in the correct order returned by the index, depending on the time it takes to load all the results component for a given result template
return [2 /*return*/, Promise.all(resultsPromises).then(function () {
return underscore_1.pluck(underscore_1.sortBy(res, 'idx'), 'elem');
})];
});
});
};
TemplateToHtml.prototype.buildResult = function (result, layout, currentlyDisplayedResults) {
return __awaiter(this, void 0, void 0, function () {
var resultElement;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
Core_1.Assert.exists(result);
Core_1.QueryUtils.setStateObjectOnQueryResult(this.args.queryStateModel.get(), result);
Core_1.QueryUtils.setSearchInterfaceObjectOnQueryResult(this.args.searchInterface, result);
ResultList_1.ResultList.resultCurrentlyBeingRendered = result;
return [4 /*yield*/, this.createHtmlElement(result, layout)];
case 1:
resultElement = _a.sent();
if (resultElement != null) {
Core_1.Component.bindResultToElement(resultElement, result);
}
currentlyDisplayedResults.push(result);
return [4 /*yield*/, this.autoCreateComponentsInsideResult(resultElement, result).initResult];
case 2:
_a.sent();
this.verifyChildren(resultElement);
return [2 /*return*/, resultElement];
}
});
});
};
TemplateToHtml.prototype.autoCreateComponentsInsideResult = function (element, result) {
Core_1.Assert.exists(element);
return Core_1.Initialization.automaticallyCreateComponentsInsideResult(element, result);
};
TemplateToHtml.prototype.createHtmlElement = function (result, layout) {
return this.args.resultTemplate.instantiateToElement(result, {
wrapInDiv: true,
checkCondition: true,
currentLayout: layout,
responsiveComponents: this.args.searchInterface.responsiveComponents
});
};
TemplateToHtml.prototype.verifyChildren = function (element) {
var containsResultLink = !!Dom_1.$$(element).find('.CoveoResultLink');
if (containsResultLink) {
return;
}
var msg = "Result does not contain a \"CoveoResultLink\" component, please verify the result template";
new Logger_1.Logger(element).warn(msg, this.args.resultTemplate);
};
return TemplateToHtml;
}());
exports.TemplateToHtml = TemplateToHtml;
/***/ }),
/***/ 474:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var TemplateHelpers_1 = __webpack_require__(122);
var HighlightUtils_1 = __webpack_require__(69);
var DateUtils_1 = __webpack_require__(33);
var CurrencyUtils_1 = __webpack_require__(135);
var HtmlUtils_1 = __webpack_require__(179);
var Utils_1 = __webpack_require__(4);
var StringUtils_1 = __webpack_require__(22);
var TimeSpanUtils_1 = __webpack_require__(73);
var EmailUtils_1 = __webpack_require__(178);
var QueryUtils_1 = __webpack_require__(21);
var DeviceUtils_1 = __webpack_require__(24);
var Dom_1 = __webpack_require__(1);
var SearchEndpoint_1 = __webpack_require__(53);
var StreamHighlightUtils_1 = __webpack_require__(120);
var FacetUtils_1 = __webpack_require__(40);
var Globalize = __webpack_require__(23);
var _ = __webpack_require__(0);
var Component_1 = __webpack_require__(7);
var TemplateCache_1 = __webpack_require__(68);
var CoreHelpers = /** @class */ (function () {
function CoreHelpers() {
}
/**
* For backward compatibility reason, the "global" template helper should be available under the
* coveo namespace.
* @param scope
*/
CoreHelpers.exportAllHelpersGlobally = function (scope) {
_.each(TemplateHelpers_1.TemplateHelpers.getHelpers(), function (helper, name) {
if (scope[name] == undefined) {
scope[name] = helper;
}
});
};
return CoreHelpers;
}());
exports.CoreHelpers = CoreHelpers;
TemplateHelpers_1.TemplateHelpers.registerFieldHelper('javascriptEncode', function (value) {
return Utils_1.Utils.exists(value) ? StringUtils_1.StringUtils.javascriptEncode(value) : undefined;
});
var executeShorten = function (content, options) {
var strAndHoles = HighlightUtils_1.StringAndHoles.shortenString(content, options.length, '...');
if (Utils_1.Utils.exists(options.highlights)) {
return HighlightUtils_1.HighlightUtils.highlightString(strAndHoles.value, options.highlights, strAndHoles.holes, options.cssClass || 'highlight');
}
else {
return strAndHoles.value;
}
};
TemplateHelpers_1.TemplateHelpers.registerTemplateHelper('shorten', function (content, length, highlights, cssClass) {
return executeShorten(content, {
length: length,
highlights: highlights,
cssClass: cssClass
});
});
TemplateHelpers_1.TemplateHelpers.registerTemplateHelper('shortenv2', function (content, options) {
return executeShorten(content, options);
});
var executeShortenPath = function (content, options) {
var strAndHoles = HighlightUtils_1.StringAndHoles.shortenPath(content, options.length);
if (Utils_1.Utils.exists(options.highlights)) {
return HighlightUtils_1.HighlightUtils.highlightString(strAndHoles.value, options.highlights, strAndHoles.holes, options.cssClass || 'highlight');
}
else {
return strAndHoles.value;
}
};
TemplateHelpers_1.TemplateHelpers.registerTemplateHelper('shortenPath', function (content, length, highlights, cssClass) {
return executeShortenPath(content, {
length: length,
highlights: highlights,
cssClass: cssClass
});
});
TemplateHelpers_1.TemplateHelpers.registerFieldHelper('shortenPathv2', function (content, options) {
return executeShortenPath(content, options);
});
var executeShortenUri = function (content, options) {
var strAndHoles = HighlightUtils_1.StringAndHoles.shortenUri(content, options.length);
if (Utils_1.Utils.exists(options.highlights)) {
return HighlightUtils_1.HighlightUtils.highlightString(strAndHoles.value, options.highlights, strAndHoles.holes, options.cssClass || 'highlight');
}
else {
return strAndHoles.value;
}
};
TemplateHelpers_1.TemplateHelpers.registerTemplateHelper('shortenUri', function (content, length, highlights, cssClass) {
return executeShortenUri(content, {
length: length,
highlights: highlights,
cssClass: cssClass
});
});
TemplateHelpers_1.TemplateHelpers.registerTemplateHelper('shortenUriv2', function (content, options) {
return executeShortenUri(content, options);
});
var executeHighlight = function (content, options) {
if (Utils_1.Utils.exists(content)) {
if (Utils_1.Utils.exists(options.highlights)) {
return HighlightUtils_1.HighlightUtils.highlightString(content, options.highlights, null, options.cssClass || 'highlight');
}
else {
return content;
}
}
else {
return undefined;
}
};
TemplateHelpers_1.TemplateHelpers.registerTemplateHelper('highlight', function (content, highlights, cssClass) {
return executeHighlight(content, {
highlights: highlights,
cssClass: cssClass
});
});
TemplateHelpers_1.TemplateHelpers.registerTemplateHelper('highlightv2', function (content, options) {
return executeHighlight(content, options);
});
var executeHighlightStreamText = function (content, options) {
if (Utils_1.Utils.exists(content) && Utils_1