coveo-search-ui
Version:
Coveo JavaScript Search Framework
1,002 lines (974 loc) • 169 kB
JavaScript
webpackJsonpCoveo__temporary([12,19,32,40,42],{
/***/ 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;
/***/ }),
/***/ 125:
/***/ (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 underscore_1 = __webpack_require__(0);
var GlobalExports_1 = __webpack_require__(3);
var Assert_1 = __webpack_require__(5);
var Strings_1 = __webpack_require__(6);
var AccessibleButton_1 = __webpack_require__(15);
var DateUtils_1 = __webpack_require__(33);
var Dom_1 = __webpack_require__(1);
var StringUtils_1 = __webpack_require__(22);
var Utils_1 = __webpack_require__(4);
var AnalyticsActionListMeta_1 = __webpack_require__(10);
var Component_1 = __webpack_require__(7);
var ComponentOptions_1 = __webpack_require__(8);
var Initialization_1 = __webpack_require__(2);
var FacetUtils_1 = __webpack_require__(40);
var TemplateFieldsEvaluator_1 = __webpack_require__(137);
var TemplateHelpers_1 = __webpack_require__(122);
var IFieldValueCompatibleFacet_1 = __webpack_require__(540);
var ComponentsTypes_1 = __webpack_require__(47);
function showOnlyWithHelper(helpers, options) {
if (options == null) {
options = {};
}
options.helpers = helpers;
return options;
}
/**
* The FieldValue component displays the value of a field associated to its parent search result. It is normally usable
* within a {@link FieldTable}.
*
* This component is a result template component (see [Result Templates](https://docs.coveo.com/en/413/)).
*
* A common use of this component is to display a specific field value which also happens to be an existing
* {@link Facet.options.field}. When the user clicks on the FieldValue component, it activates the corresponding Facet.
*/
var FieldValue = /** @class */ (function (_super) {
__extends(FieldValue, _super);
/**
* Creates a new FieldValue.
* @param element The HTMLElement on which to instantiate the component.
* @param options The options for the FieldValue 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).
* @param result The result to associate the component with.
*/
function FieldValue(element, options, bindings, result, fieldValueClassId) {
if (fieldValueClassId === void 0) { fieldValueClassId = FieldValue.ID; }
var _this = _super.call(this, element, fieldValueClassId, bindings) || this;
_this.element = element;
_this.options = options;
_this.result = result;
_this.options = ComponentOptions_1.ComponentOptions.initOptions(element, FieldValue.simpleOptions, options, FieldValue.ID);
if (_this.options.helper != null) {
_this.normalizeHelperAndOptions();
}
_this.result = _this.result || _this.resolveResult();
Assert_1.Assert.exists(_this.result);
if (TemplateFieldsEvaluator_1.TemplateFieldsEvaluator.evaluateFieldsToMatch(_this.options.conditions, _this.result) && !Utils_1.Utils.isNullOrUndefined(_this.getValue())) {
_this.initialize();
}
else if (_this.element.parentElement != null) {
_this.element.parentElement.removeChild(_this.element);
}
return _this;
}
FieldValue.prototype.initialize = function () {
var loadedValueFromComponent = this.getValue();
var values;
if (underscore_1.isArray(loadedValueFromComponent)) {
values = loadedValueFromComponent;
}
else if (this.options.splitValues) {
if (underscore_1.isString(loadedValueFromComponent)) {
values = underscore_1.map(loadedValueFromComponent.split(this.options.separator), function (v) {
return v.trim();
});
}
}
else {
loadedValueFromComponent = loadedValueFromComponent.toString();
values = [loadedValueFromComponent];
}
if (values.length > 1 && this.isValueHierarchical) {
values = values.slice(-1);
}
this.appendValuesToDom(values);
if (this.options.textCaption != null) {
this.prependTextCaptionToDom();
}
};
/**
* Gets the current FieldValue from the current {@link IQueryResult}.
*
* @returns {any} The current FieldValue or `null` if value is and `Object`.
*/
FieldValue.prototype.getValue = function () {
var value = Utils_1.Utils.getFieldValue(this.result, this.options.field);
if (!underscore_1.isArray(value) && underscore_1.isObject(value)) {
value = null;
}
return value;
};
/**
* Renders a value to HTML using all of the current FieldValue component options.
* @param value The value to render.
* @returns {HTMLElement} The element containing the rendered value.
*/
FieldValue.prototype.renderOneValue = function (value) {
var element = Dom_1.$$('span').el;
var toRender = this.getCaption(value);
if (this.options.helper) {
// Try to resolve and execute version 2 of each helper function if available
var helper = TemplateHelpers_1.TemplateHelpers.getHelper(this.options.helper + "v2") || TemplateHelpers_1.TemplateHelpers.getHelper("" + this.options.helper);
if (Utils_1.Utils.exists(helper)) {
toRender = helper.call(this, value, this.getHelperOptions(), this.result);
}
else {
this.logger.warn("Helper " + this.options.helper + " is not found in available helpers. The list of supported helpers is :", underscore_1.keys(TemplateHelpers_1.TemplateHelpers.getHelpers()));
}
var fullDateStr = this.getFullDate(value, this.options.helper);
if (fullDateStr) {
element.setAttribute('title', fullDateStr);
}
if (this.options.helper == 'date' || this.options.helper == 'dateTime' || this.options.helper == 'emailDateTime') {
toRender = StringUtils_1.StringUtils.capitalizeFirstLetter(toRender);
}
}
if (this.options.htmlValue) {
element.innerHTML = toRender;
}
else {
element.appendChild(document.createTextNode(toRender));
}
this.bindEventOnValue(element, value, toRender);
return element;
};
FieldValue.prototype.getValueContainer = function () {
return this.element;
};
FieldValue.prototype.normalizeHelperAndOptions = function () {
var _this = this;
this.options = ComponentOptions_1.ComponentOptions.initOptions(this.element, FieldValue.helperOptions, this.options, FieldValue.ID);
var toFilter = underscore_1.keys(FieldValue.options.helperOptions['subOptions']);
var toKeep = underscore_1.filter(toFilter, function (optionKey) {
var optionDefinition = FieldValue.options.helperOptions['subOptions'][optionKey];
if (optionDefinition) {
var helpers = optionDefinition.helpers;
return helpers != null && underscore_1.contains(helpers, _this.options.helper);
}
return false;
});
this.options.helperOptions = underscore_1.omit(this.options.helperOptions, function (value, key) {
return !underscore_1.contains(toKeep, key);
});
};
FieldValue.prototype.getHelperOptions = function () {
var inlineOptions = ComponentOptions_1.ComponentOptions.loadStringOption(this.element, 'helperOptions', {});
if (Utils_1.Utils.isNonEmptyString(inlineOptions)) {
return underscore_1.extend({}, this.options.helperOptions, eval('(' + inlineOptions + ')'));
}
return this.options.helperOptions;
};
FieldValue.prototype.getFullDate = function (date, helper) {
var fullDateOptions = {
useLongDateFormat: true,
useTodayYesterdayAndTomorrow: false,
useWeekdayIfThisWeek: false,
omitYearIfCurrentOne: false
};
if (helper == 'date') {
return DateUtils_1.DateUtils.dateToString(new Date(parseInt(date)), fullDateOptions);
}
else if (helper == 'dateTime' || helper == 'emailDateTime') {
return DateUtils_1.DateUtils.dateTimeToString(new Date(parseInt(date)), fullDateOptions);
}
return '';
};
FieldValue.prototype.appendValuesToDom = function (values) {
var _this = this;
underscore_1.each(values, function (value, index) {
if (value != undefined) {
_this.getValueContainer().appendChild(_this.renderOneValue(value));
if (index !== values.length - 1) {
_this.getValueContainer().appendChild(document.createTextNode(_this.options.displaySeparator));
}
}
});
};
FieldValue.prototype.renderTextCaption = function () {
var element = Dom_1.$$('span', { className: 'coveo-field-caption' }, underscore_1.escape(this.options.textCaption));
return element.el;
};
FieldValue.prototype.prependTextCaptionToDom = function () {
var elem = this.getValueContainer();
Dom_1.$$(elem).prepend(this.renderTextCaption());
// Add a class to the container so the value and the caption wrap together.
Dom_1.$$(elem).addClass('coveo-with-label');
};
FieldValue.prototype.bindEventOnValue = function (element, originalFacetValue, renderedFacetValue) {
this.bindFacets(element, originalFacetValue, renderedFacetValue);
};
FieldValue.prototype.getCaption = function (value) {
for (var _i = 0, _a = this.getFacets(); _i < _a.length; _i++) {
var facet = _a[_i];
var caption = facet.getCaptionForStringValue(value);
if (caption) {
return caption;
}
}
return FacetUtils_1.FacetUtils.tryToGetTranslatedCaption(this.options.field, value);
};
FieldValue.prototype.getFacets = function () {
var _this = this;
var facets = ComponentsTypes_1.ComponentsTypes.getAllFacetsFromSearchInterface(this.searchInterface)
.filter(IFieldValueCompatibleFacet_1.isFacetFieldValueCompatible)
.filter(function (facet) { return !facet.disabled; });
var facetsWithMatchingId = facets.filter(function (facet) { return facet.options.id === _this.options.facet; });
if (facetsWithMatchingId.length) {
return facetsWithMatchingId;
}
return facets.filter(function (facet) { return facet.options.field === _this.options.field; });
};
Object.defineProperty(FieldValue.prototype, "isValueHierarchical", {
get: function () {
for (var _i = 0, _a = this.getFacets(); _i < _a.length; _i++) {
var facet = _a[_i];
if (facet.isFieldValueHierarchical) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
FieldValue.prototype.bindFacets = function (element, originalFacetValue, renderedFacetValue) {
var _this = this;
var facets = this.getFacets();
if (!facets.length) {
return;
}
var isValueSelected = !!underscore_1.find(facets, function (facet) { return facet.hasSelectedValue(originalFacetValue); });
var selectAction = function () { return _this.handleFacetSelection(isValueSelected, facets, originalFacetValue); };
this.buildClickableElement(element, isValueSelected, renderedFacetValue, selectAction);
};
FieldValue.prototype.buildClickableElement = function (element, isSelected, value, selectAction) {
var label = isSelected ? Strings_1.l('RemoveFilterOn', value) : Strings_1.l('FilterOn', value);
new AccessibleButton_1.AccessibleButton().withTitle(label).withElement(element).withSelectAction(selectAction).build();
if (isSelected) {
Dom_1.$$(element).addClass('coveo-selected');
}
Dom_1.$$(element).addClass('coveo-clickable');
};
FieldValue.prototype.handleFacetSelection = function (isValueSelected, facets, value) {
facets.forEach(function (facet) {
isValueSelected ? facet.deselectValue(value) : facet.selectValue(value);
});
this.executeQuery(value);
};
FieldValue.prototype.executeQuery = function (value) {
var _this = this;
this.queryController.deferExecuteQuery({
beforeExecuteQuery: function () {
return _this.usageAnalytics.logSearchEvent(AnalyticsActionListMeta_1.analyticsActionCauseList.documentField, {
facetId: _this.options.facet,
facetField: _this.options.field.toString(),
facetValue: value.toLowerCase()
});
}
});
};
FieldValue.ID = 'FieldValue';
FieldValue.doExport = function () {
GlobalExports_1.exportGlobally({
FieldValue: FieldValue
});
};
/**
* The options for the component
* @componentOptions
*/
FieldValue.options = {
/**
* Specifies the field that the FieldValue should display.
*
* Specifying a value for this parameter is required in order for the FieldValue component to work.
*/
field: ComponentOptions_1.ComponentOptions.buildFieldOption({ defaultValue: '@field', required: true }),
/**
* Specifies the {@link Facet} component to toggle when the end user clicks the FieldValue.
*
* Default value is the value of {@link FieldValue.options.field}.
*
* **Note:**
* > If the target {@link Facet.options.id} is is not the same as its {@link Facet.options.field}), you must specify
* > this option manually in order to link to the correct Facet.
*/
facet: ComponentOptions_1.ComponentOptions.buildStringOption({ postProcessing: function (value, options) { return value || options.field; } }),
/**
* Specifies whether the content to display is an HTML element.
*
* Default value is `false`.
*/
htmlValue: ComponentOptions_1.ComponentOptions.buildBooleanOption({ defaultValue: false }),
/**
* Specifies whether to split the FieldValue at each {@link FieldValue.options.separator}.
*
* This is useful for splitting groups using a {@link Facet.options.field}.
*
* When this option is `true`, the displayed values are split by the {@link FieldValue.options.displaySeparator}.
*
* Default value is `false`.
*/
splitValues: ComponentOptions_1.ComponentOptions.buildBooleanOption({ defaultValue: false }),
/**
* If {@link FieldValue.options.splitValues} is `true`, specifies the separator string which separates multi-value
* fields in the index.
*
* See {@link FieldValue.options.displaySeparator}.
*
* Default value is `";"`.
*/
separator: ComponentOptions_1.ComponentOptions.buildStringOption({ depend: 'splitValues', defaultValue: ';' }),
/**
* If {@link FieldValue.options.splitValues} is `true`, specifies the string to use when displaying multi-value
* fields in the UI.
*
* The component will insert this string between each value it displays from a multi-value field.
*
* See also {@link FieldValue.options.separator}.
*
* Default value is `", "`.
*/
displaySeparator: ComponentOptions_1.ComponentOptions.buildStringOption({ depend: 'splitValues', defaultValue: ', ' }),
/**
* Specifies the helper that the FieldValue should use to display its content.
*
* While several helpers exist by default (see {@link ICoreHelpers}), it is also possible for you to create your own
* custom helpers (see {@link TemplateHelpers}).
*/
helper: ComponentOptions_1.ComponentOptions.buildHelperOption(),
/**
* Specifies the options to call on the specified helper.
*/
helperOptions: ComponentOptions_1.ComponentOptions.buildObjectOption({
subOptions: {
text: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['anchor'])),
target: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['anchor'])),
class: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['anchor'])),
format: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['number'])),
decimals: ComponentOptions_1.ComponentOptions.buildNumberOption(showOnlyWithHelper(['currency'], { min: 0 })),
symbol: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['currency'])),
useTodayYesterdayAndTomorrow: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['date', 'dateTime', 'emailDateTime', 'time'], { defaultValue: true })),
useWeekdayIfThisWeek: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['date', 'dateTime', 'emailDateTime', 'time'], { defaultValue: true })),
omitYearIfCurrentOne: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['date', 'dateTime', 'emailDateTime', 'time'], { defaultValue: true })),
useLongDateFormat: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['date', 'dateTime', 'emailDateTime', 'time'], { defaultValue: false })),
includeTimeIfToday: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['date', 'dateTime', 'emailDateTime', 'time'], { defaultValue: true })),
includeTimeIfThisWeek: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['date', 'dateTime', 'emailDateTime', 'time'], { defaultValue: true })),
alwaysIncludeTime: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['date', 'dateTime', 'emailDateTime', 'time'], { defaultValue: false })),
predefinedFormat: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['date', 'dateTime', 'emailDateTime', 'time'])),
companyDomain: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['email'])),
me: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['email'])),
lengthLimit: ComponentOptions_1.ComponentOptions.buildNumberOption(showOnlyWithHelper(['email'], { min: 1 })),
truncateName: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['email'])),
alt: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['image'])),
height: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['image'])),
width: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['image'])),
srcTemplate: ComponentOptions_1.ComponentOptions.buildStringOption(showOnlyWithHelper(['image'])),
precision: ComponentOptions_1.ComponentOptions.buildNumberOption(showOnlyWithHelper(['size'], { min: 0, defaultValue: 2 })),
base: ComponentOptions_1.ComponentOptions.buildNumberOption(showOnlyWithHelper(['size'], { min: 0, defaultValue: 0 })),
isMilliseconds: ComponentOptions_1.ComponentOptions.buildBooleanOption(showOnlyWithHelper(['timeSpan'])),
length: ComponentOptions_1.ComponentOptions.buildNumberOption(showOnlyWithHelper(['shorten', 'shortenPath', 'shortenUri'], { defaultValue: 200 }))
}
}),
/**
* Specifies a caption to display before the value.
*
* Default value is `undefined`.
*
* @availablesince [January 2017 Release (v1.1865.9)](https://docs.coveo.com/en/396/#january-2017-release-v118659)
*/
textCaption: ComponentOptions_1.ComponentOptions.buildLocalizedStringOption(),
/**
* A field-based condition that must be satisfied by the query result item for the component to be rendered.
*
* Note: This option uses a distinctive markup configuration syntax allowing multiple conditions to be expressed. Its underlying logic is the same as that of the field value conditions mechanism used by result templates.
*
* **Examples:**
* Render the component if the query result item's @documenttype field value is Article or Documentation.
* ```html
* <div class="CoveoFieldValue" data-field="@author" data-condition-field-documenttype="Article, Documentation"></div>
* ```
* Render the component if the query result item's @documenttype field value is anything but Case.
* ```html
* <div class="CoveoFieldValue" data-field="@author" data-condition-field-not-documenttype="Case"></div>
* ```
* Render the component if the query result item's @documenttype field value is Article, and if its @author field value is anything but Anonymous.
* ```html
* <div class="CoveoFieldValue" data-field="@author" data-condition-field-documenttype="Article" data-condition-field-not-author="Anonymous"></div>
* ```
* Default value is `undefined`.
*/
conditions: ComponentOptions_1.ComponentOptions.buildFieldConditionOption()
};
FieldValue.simpleOptions = underscore_1.omit(FieldValue.options, 'helperOptions');
FieldValue.helperOptions = {
helperOptions: FieldValue.options.helperOptions
};
return FieldValue;
}(Component_1.Component));
exports.FieldValue = FieldValue;
Initialization_1.Initialization.registerAutoCreateComponent(FieldValue);
/***/ }),
/***/ 197:
/***/ (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 Core_1 = __webpack_require__(20);
var GlobalExports_1 = __webpack_require__(3);
var ComponentOptions_1 = __webpack_require__(8);
var FieldValue_1 = __webpack_require__(125);
/**
* This component renders an image from a URL retrieved in a given [`field`]{@link ImageFieldValue.options.field}.
*
* A typical use case of this component is to display product images in the context of commerce.
*
* @isresulttemplatecomponent
* @availablesince [September 2019 Release (v2.7023)](https://docs.coveo.com/en/2990/)
*/
var ImageFieldValue = /** @class */ (function (_super) {
__extends(ImageFieldValue, _super);
/**
* Creates a new ImageFieldValue.
* @param element The HTMLElement on which to instantiate the component.
* @param options The options for the ImageFieldValue 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).
* @param result The result to associate the component with.
*/
function ImageFieldValue(element, options, bindings, result) {
var _this = _super.call(this, element, ImageFieldValue.ID, bindings) || this;
_this.element = element;
_this.options = options;
_this.result = result;
_this.options = ComponentOptions_1.ComponentOptions.initComponentOptions(element, ImageFieldValue, options);
var fieldValueOption = {
field: _this.options.field,
helper: 'image',
htmlValue: true,
helperOptions: {
height: _this.options.height,
width: _this.options.width,
alt: result.title,
srcTemplate: _this.options.srcTemplate
}
};
new FieldValue_1.FieldValue(element, fieldValueOption, bindings, result);
return _this;
}
ImageFieldValue.ID = 'ImageFieldValue';
ImageFieldValue.doExport = function () {
GlobalExports_1.exportGlobally({
ImageFieldValue: ImageFieldValue
});
};
/**
* The options for the component
* @componentOptions
*/
ImageFieldValue.options = {
/**
* **Required**. The name of a field whose value is the URL of the image to display.
*
* **Note:** The component uses the value of this field to set the `src` attribute of the [`img`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) HTML tag it generates.
*/
field: ComponentOptions_1.ComponentOptions.buildFieldOption({ required: true }),
/**
* The width of the image (in pixels).
*
* **Note:** The component uses this value to set the `width` attribute of the [`img`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) HTML tag it generates.
*/
width: ComponentOptions_1.ComponentOptions.buildNumberOption(),
/**
* The height of the image (in pixels).
*
* **Note:** The component uses this value to set the `height` attribute of the [`img`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) HTML tag it generates.
*/
height: ComponentOptions_1.ComponentOptions.buildNumberOption(),
/**
* A [template literal](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals)
* from which to generate the `img` tag's `src` attribute value.
*
* This option overrides the [`field`]{@link ImageFieldValue.options.field} option value.
*
* The template literal can reference any number of fields from the parent result. It can also reference global
* scope properties.
*
* **Examples:**
*
* - The following markup generates an `src` value such as `http://uri.com?id=itemTitle`:
*
* ```html
* <a class='CoveoImageFieldValue' data-src-template='${clickUri}?id=${raw.title}'></a>
* ```
*
* - The following markup generates an `src` value such as `localhost/fooBar`:
*
* ```html
* <a class='CoveoImageFieldValue' data-src-template='${window.location.hostname}/{Foo.Bar}'></a>
* ```
*
* Default value is `undefined`.
*/
srcTemplate: ComponentOptions_1.ComponentOptions.buildStringOption()
};
return ImageFieldValue;
}(Core_1.Component));
exports.ImageFieldValue = ImageFieldValue;
Core_1.Initialization.registerAutoCreateComponent(ImageFieldValue);
/***/ }),
/***/ 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;
/***/ }),
/***/ 296:
/***/ (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 __());
};
})();
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;
};
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 GlobalExports_1 = __webpack_require__(3);
var Core_1 = __webpack_require__(20);
__webpack_require__(703);
var TemplateComponentOptions_1 = __webpack_require__(63);
var TemplateToHtml_1 = __webpack_require__(473);
var ResultLink_1 = __webpack_require__(71);
var ImageFieldValue_1 = __webpack_require__(197);
var ResultPreviewsManagerEvents_1 = __webpack_require__(510);
/**
* This component renders previews of the top query results matching the currently focused query suggestion in the search box.
*
* As such, this component only works when the search interface can
* [provide Coveo Machine Learning query suggestions](https://docs.coveo.com/en/340/#providing-coveo-machine-learning-query-suggestions).
*
* This component should be initialized on a `div` which can be nested anywhere inside the root element of your search interface.
*
* See [Rendering Query Suggestion Result Previews](https://docs.coveo.com/en/340/#rendering-query-suggestion-result-previews).
*
* @availablesince [December 2019 Release (v2.7610)](https://docs.coveo.com/en/3142/)
*/
var QuerySuggestPreview = /** @class */ (function (_super) {
__extends(QuerySuggestPreview, _super);
/**
* Creates a new QuerySuggestPreview component.
* @param element The HTMLElement on which to instantiate the component.
* @param options The options for the QuerySuggestPreview 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 QuerySuggestPreview(element, options, bindings) {
var _this = _super.call(this, element, QuerySuggestPreview.ID, bindings) || this;
_this.element = element;
_this.options = options;
_this.bindings = bindings;
_this.options = Core_1.ComponentOptions.initComponentOptions(element, QuerySuggestPreview, options);
if (!_this.options.resultTemplate) {
_this.logger.warn("No template was provided for " + QuerySuggestPreview.ID + ", a default template was used instead.");
_this.options.resultTemplate = _this.buildDefaultSearchResultPreviewTemplate();
}
_this.bind.onRootElement(ResultPreviewsManagerEvents_1.ResultPreviewsManagerEvents.updateResultPreviewsManagerOptions, function (args) {
return (args.displayAfterDuration = Math.max(args.displayAfterDuration || 0, _this.options.executeQueryDelay));
});
_this.bind.onRootElement(ResultPreviewsManagerEvents_1.ResultPreviewsManagerEvents.populateSearchResultPreviews, function (args) {
return _this.populateSearchResultPreviews(args);
});
return _this;
}
QuerySuggestPreview.prototype.buildDefaultSearchResultPreviewTemplate = function () {
return Core_1.HtmlTemplate.create(Core_1.$$('div', { className: 'result-template' }, Core_1.$$('div', { className: 'coveo-result-frame coveo-default-result-preview' }, Core_1.$$('div', { className: Core_1.Component.computeCssClassName(ImageFieldValue_1.ImageFieldValue), 'data-field': '@image' }), Core_1.$$('a', { className: Core_1.Component.computeCssClassName(ResultLink_1.ResultLink) }))).el);
};
Object.defineProperty(QuerySuggestPreview.prototype, "templateToHtml", {
get: function () {
var templateToHtmlArgs = {
searchInterface: this.searchInterface,
queryStateModel: this.queryStateModel,
resultTemplate: this.options.resultTemplate
};
return new TemplateToHtml_1.TemplateToHtml(templateToHtmlArgs);
},
enumerable: true,
configurable: true
});
QuerySuggestPreview.prototype.populateSearchResultPreviews = function (args) {
args.previewsQueries.push(this.fetchSearchResultPreviews(args.suggestion));
};
QuerySuggestPreview.prototype.fetchSearchResultPreviews = function (suggestion) {
return __awaiter(this, void 0, void 0, function () {
var query, results;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
query = this.buildQuery(suggestion);
return [4 /*yield*/, this.queryController.getEndpoint().search(query)];
case 1:
results = _a.sent();
if (!results) {
return [2 /*return*/, []];
}
return [2 /*return*/, this.buildResultsPreview(suggestion, results)];
}
});
});
};
QuerySuggestPreview.prototype.buildQuery = function (suggestion) {
var query = this.buildDefaultQuery(suggestion);
Core_1.$$(this.root).trigger(ResultPreviewsManagerEvents_1.ResultPreviewsManagerEvents.buildingResultPreviewsQuery, { query: query });
return query;
};
QuerySuggestPreview.prototype.buildDefaultQuery = function (suggestion) {
var _a = this.queryController.getLastQuery(), searchHub = _a.searchHub, pipeline = _a.pipeline, tab = _a.tab, locale = _a.locale, timezone = _a.timezone, context = _a.context, cq = _a.cq;
return __assign({ firstResult: 0, searchHub: searchHub,
pipeline: pipeline,
tab: tab,
locale: locale,
timezone: timezone,
context: context,
cq: cq, numberOfResults: this.options.numberOfPreviewResults, q: suggestion.text || suggestion.dom.innerText }, (suggestion.advancedQuery && { aq: suggestion.advancedQuery }));
};
QuerySuggestPreview.prototype.buildResultsPreview = function (suggestion, results) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
var buildResults;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.templateToHtml.buildResults(results, 'preview', [])];
case 1:
buildResults = _a.sent();
if (!(buildResults.length > 0)) {
return [2 /*return*/, []];
}
return [2 /*return*/, buildResults.map(function (element, index) { return _this.buildResultPreview(suggestion, element, index); })];
}
});
});
};
QuerySuggestPreview.prototype.buildResultPreview = function (suggestion, element, rank) {
var _this = this;
element.classList.add('coveo-preview-selectable');
var resultLink = element.querySelector(Core_1.Component.computeSelectorForType(ResultLink_1.ResultLink.ID));
if (resultLink) {
element.setAttribute('aria-label', resultLink.textContent);
resultLink.setAttribute('role', 'link');
resultLink.removeAttribute('aria-level');
}
return {
element: element,
onSelect: function () { return _this.handleSelect(suggestion, element, rank); }
};
};
QuerySuggestPreview.prototype.handleSelect = function (suggestion, element, rank) {
var link = Core_1.$$(element).find("." + Core_1.Component.computeCssClassNameForType('ResultLink'));
if (link) {
var resultLink = Core_1.Component.get(link);
resultLink.openLinkAsConfigured();
resultLink.openLink();
}
};
QuerySuggestPreview.ID = 'QuerySuggestPreview';
QuerySuggestPreview.doExport = function () {
GlobalExports_1.exportGlobally({
QuerySuggestPreview: QuerySuggestPreview
});
};
/**
* The options for the component
* @componentOptions
*/
QuerySuggestPreview.options = {
/**
* The HTML `id` attribute value, or CSS selector of the previously registered
* [result template](https://docs.coveo.com/413/) to apply when rendering the
* query suggestion result previews.
*
* **Examples**
* * Specifying the `id` attribute of the target result template:
* ```html
* <div class="CoveoQuerySuggestPreview" data-result-template-id="myTemplateId"></div>
* ```
* * Specifying an equivalent CSS selector:
* ```html
* <div class="CoveoQuerySuggestPreview" data-result-template-selector="#myTemplateId"></div>
* ```
*
* If you specify no previously registered template through this option, the component uses its default template.
*/
resultTemplate: TemplateComponentOptions_1.TemplateComponentOptions.buildTemplateOption(),
/**
* The maximum number of query results to render in the preview.
*/
numberOfPreviewResults: Core_1.ComponentOptions.buildNumberOption({
defaultValue: 4,
min: 1,
max: 6
}),
/**
* The amount of focus time (in milliseconds) required on a query suggestion before requesting a preview of its top results.
*/
executeQueryDelay: Core_1.ComponentOptions.buildNumberOption({ defaultValue: 200 })
};
return QuerySuggestPreview;
}(Core_1.Component));
exports.QuerySuggestPreview = QuerySuggestPreview;
Core_1.Initialization.registerAutoCreateComponent(QuerySuggestPreview);
/***/ }),
/***/ 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 wh