JavaScript modules
In the JavaScript of Pages and Search templates, it is possible to import
JavaScript modules. After the import, the module is available in a variable named the same as the import.
The following example uses the querystring_storage
module to store a named data serialized as json in the query-string parameter test-data
.
import "querystring_storage";
var storage = querystring_storage.create("test-data");
storage.put('sort_by', 'price')
storage.put('filter', 'brand:Nike')
Below follows documentation for the available modules
hash_storage
Provides an API for storing and reading data in the fragment (hash) part of a URL, allowing data to persist across page reloads and be included in links.
To use hash_storage
, create an instance with a specified namespace, enabling multiple hash_storage
instances to coexist. This is useful when both Pages and Search are used on the same site. Data added to hash_storage
instances is serialized as JSON and stored in the URL fragment, with each namespace as its property. The library also detects changes to the URL made by other sources. It is designed to be compatible with other storage libraries like local_storage
and querystring_storage
.
Module level methods
create(namespace, options)
Creates a new instance of the module
Argument | Description |
---|---|
namespace | The key in the root level object used to store the data. All instances using the same namespace will see each others data. |
options | An optional dictionary containing options changing the behaviour of the object. The only currently available option is clear_history_state . Setting this to true will make the library set the data part to null in the replaceState call from the history api. |
Instance level methods
put(key, value)
Saves value
in the storage under key
.
get(key)
Returns the value stored under key
. Returns undefined
if there is no stored value.
get_or_default(key, default_value)
Returns the value stored under key
. If there is no stored value it returns the value in default_value
.
keys()
Returns a list of all defined keys in the storage.
clear()
Deletes everything in the storage.
Example
import "hash_storage";
var storage = querystring_storage.create("test-data");
storage.put('filter', 'brand:Nike')
var filter = storage.get('filter')
local_storage
Provides an API for storing and reading data in window.localStorage
, allowing data to persist across page reloads.
To use local_storage
, create an instance with a specified namespace, enabling multiple local_storage
instances to coexist. This is useful when both Pages and Search are used on the same site. The library is designed to be compatible with other storage libraries like hash_storage
and querystring_storage
.
Module level methods
create(namespace)
Creates a new instance of the module.
Argument | Description |
---|---|
namespace | The key in the root level object used to store the data. All instances using the same namespace will see each others data. |
Instance level methods
put(key, value)
Saves value
in the storage under key
.
get(key)
Returns the value stored under key
. Returns undefined
if there is no stored value.
get_or_default(key, default_value)
Returns the value stored under key
. If there is no stored value it returns the value in default_value
.
keys()
Returns a list of all defined keys in the storage.
clear()
Deletes everything in the storage.
Example
import "local_storage";
var storage = querystring_storage.create("test-data");
storage.put('filter', 'brand:Nike')
var filter = storage.get('filter')
querystring_storage
Provides an API for storing and reading data in a query-string variable in the URL, allowing data to persist across reloads and be included in links.
To use querystring_storage
, create an instance with a specified namespace, enabling multiple querystring_storage
instances to coexist. This is useful when both Pages and Search are used on the same site. The data is serialized as JSON and stored in a query-string variable named after the namespace. The library also detects changes to the URL made by other sources and is designed to be compatible with other storage libraries like hash_storage
and local_storage
.
Module level methods
create(namespace, options)
Creates a new instance of the module
Argument | Description |
---|---|
namespace | The name of the query-string variable the data will be saved in. All instances using the same namespace will see each others data. |
options | An optional dictionary containing options changing the behaviour of the object. The only currently available option is clear_history_state . Setting this to true will make the library set the data part to null in the replaceState or pushState` call from the history api. |
Instance level methods
put(key, value, push)
Saves value
in the storage under key
. The push
variable determines if the data should be added to the url by calling pushState
or replaceState
. The default is to use replaceState
(push = false
).
get(key)
Returns the value stored under key
or undefined
if there is no stored value.
get_or_default(key, default_value)
Returns the value stored under key
. If there is no stored value it returns the value in default_value
.
keys()
Returns a list of all defined keys in the storage.
clear(push)
Deletes everything in the storage. The push
variable determines if the data should be added to the url by calling pushState
or replaceState
. The default is to use replaceState
(push = false
).
Example
import "querystring_storage";
var storage = querystring_storage.create("test-data");
storage.put('filter', 'brand:Nike')
var filter = storage.get('filter')
style_loader
Library that can be used to load external style sheets. Given a URL pointing to a style sheet it will be loaded and injected into the page. The style_loader will keep track of any loaded style sheets and will automatically unload them if the reload
method is called in helloretail.js
Module level methods
load(url)
Loads and injects a stylesheet.
Arguments:
url
: URL to a stylesheet.
Example
import "style_loader";
style_loader.load("https://shop.example.org/styles/style.css");
ui_overlay_vanilla
A library for creating UIs with full screen overlays. The library will automatically handle opening multiple overlays on top of each other.
Module level methods
create(options)
Returns a new overlay object. It accepts an options object. The object can have two properties, show
which can be a function that is called when the overlay has been opened, and hide
which is called when the overlay is closed.
The returned object is a DOM node that you can add content to. The returned object also has some extra methods for showing and hiding the overlay.
Instance level methods
open(callback)
Makes the overlay visible. Accepts a callback
parameter that can be a function that is called once the overlay has been opened.
close()
Hides the overlay.
destroy()
Hides the overlay and removes it from the DOM. After calling this the overlay cannot be opened again.
Example
import "ui_overlay_vanilla";
var overlay = ui_overlay_vanilla.create();
var content = document.createElement("div");
content.innerHTML = '<h1>Welcome</h1>';
overlay.append(content);
overlay.show();
ui_tabs_vanilla
A helper library for creating a tabbed UI. Given HTML document with a element containing a number of tab navigation links and another element containing the actual tab content, this library will make it possible to click the tab links to switch between the tabs.
Module level methods
create(root, options)
Activate a tabbed UI, inside DOM element passed in root
.
Options is an object that contains the following properties:
Property | Description |
---|---|
header_area | A CSS selector for finding the container holding the tab navigation links. Each direct child of this element will be used as navigation links. Each element must contain a data-tab attribute identifying the tab that should be activated by this element. |
content_area | A CSS selector for finding the container holding the actual tab data. Each tab must contain a data-tab attribute identifyting the tab. The identifiers must be identical to the ones in the header area. |
on_change | A callback that is called when the tab changes. The callback will be passed two arguments, the DOM element from the content_area that was activated, and a boolean indicating if the tab was activated by a user click. |
on_scroll | A callback that is called when the content of a tab is scrolled. |
Example
Given the following HTML
<div id="tab-area">
<div id="tabs">
<li data-tab="A">Show A</li>
<li data-tab="B">Show B</li>
</div>
<div id="tab-content">
<div data-tab="A">
<h1>This is A</h1>
</div>
<div data-tab="B">
<h1>This is B</h1>
</div>
</div>
</div>
import "ui_tabs_vanilla";
ui_tabs_vanilla.create(
document.getElementById("tab-area"),
{
header_area: "#tabs",
content_area: "#tab-content",
on_change: function(tab, is_user_click) {
console.log("Activated tab", tab);
}
}
)
ui_utility_vanilla
A collection of helper methods.
Module level methods
show(dom_elements)
Make the provided list of DOM elements (or single DOM element) visible by making them display: block
Example:
import "ui_utility_vanilla";
ui_utility_vanilla.show(document.querySelectorAll("p"));
hide(dom_elements)
Make the provided list of DOM elements (or single DOM element) hidden by making them display: none
Example:
import "ui_utility_vanilla";
ui_utility_vanilla.hide(document.querySelectorAll("p"));
isVisible(dom_element)
Check if the provided DOM element is visible, i.e. not display: none
Example:
import "ui_utility_vanilla";
ui_utility_vanilla.isVisible(document.querySelector("#login-button"));
fix_links(content, prefix)
URLs returned from the various Hello Retail APIs have tracking codes links appended to them. This function will look for tracking links with the prefix prefix
and remove them from the link, and instead add a click handler that tracks a click on the tracking code before following the link. This makes the URLs the customers are seeing and clicking prettier, while maintaining the tracking. The available prefixes are:
Prefix | Feature |
---|---|
ps | Search |
pb | Recoms |
pa | Pages |
nc | Newsletter Content |
te | Triggered Emails |
Example:
import "ui_utility_vanilla";
ui_utility_vanilla.fix_links(document.querySelector("#my-recom"), "pb");
debounce(callback, wait)
Helper for debouncing calls to a function. Returns a new function that when called will call the callback function with the same arguments, but it will make sure that the underlying function is only called one there has been a break in calls of at least the number of milliseconds given in wait
Example:
import "ui_utility_vanilla";
function log(messaage) {
console.log(message);
}
var debounced_logger = ui_utility_vanilla.debounce(log, 200);
log("test 1");
debounced_logger("test 2");
debounced_logger("test 3");
setTimeout(function() {
debounced_logger("test 4");
}, 300);
test 1
test 3
test 4
The debounce function is useful for limiting the rate of event handlers that can fire rapidly (e.g., scroll, resize, mousemove).
throttle(callback, wait, options)
Helper for throttling function calls to ensure it's invoked at most once per specified wait period. It returns a new function that, when called, will execute the original function with the same arguments. Options allow control over execution at the beginning (leading) and/or at the end (trailing) of the wait period. By default, both options are set to true, meaning the function will run immediately on the first call and once more at the end of the wait period if additional calls occur during this time.
Notice that setting both leading
and trailing
to false will make the callback never be called.
Example:
import "ui_utility_vanilla";
function log(messaage) {
console.log(message);
}
var throttled_logger = ui_utility_vanilla.throttle(log, 200, {leading: true, trailing: true});
log("test 1");
throttled_logger("test 2");
throttled_logger("test 3");
setTimeout(function() {
throttled_logger("test 4");
}, 100);
setTimeout(function() {
throttled_logger("test 5");
}, 300);
test 1
test 2
test 4
test 5
The throttle function is useful for limiting the rate of event handlers that can fire rapidly (e.g., scroll, resize, mousemove).
window_size()
Returns and object with width
and height
of the current window.
Example:
import "ui_utility_vanilla";
const size = ui_utility_vanilla.window_size();
register_filter(filter, callback, searcher, optionals)
Utility for activating "interactivity" on filtering and sorting UI generated by the specialized liquid filters available in search and pages templates. The function expects certain class names and DOM layout that is generated by these filters. Read more about the filters in the Search template guide.
Arguments | Description |
---|---|
filter | The DOM element containing the filter, generated by the liquid helper. |
callback | A callback that will be called when the selected filter value changes. |
searcher | Searcher instance being used to perform the searching. |
optionals | Object containing optional parameters. Currently only rangeSliderDecimals is supported. It determines how may decimals should be shown in the range slider output from range filters. |
Example:
import "ui_utility_vanilla";
var filters = overlay.querySelectorAll(".aw-filter__single-wrapper");
filters.forEach(function(filter) {
ui_utility_vanilla.register_filter(filter, function() {
load_more_results();
}, searcher);
});
search_instance
A module for managing calls to the Search API. It helps with pagination, handling both product and content results, and with filtering and sorting search results. Actual searches are triggered by calling the yield_template
or the initial_render
methods.
Module level methods
create(options)
Create a new searcher. Some initial options can be set in the options object.
Option | Description |
---|---|
return_filters | a boolean indicating if the next search should include available filters in the result. |
search_key | The key of the search config to use. |
id | Id of the version of the search config to use. This is only used when testing draft versions of a search config. |
Instance level properties
filters
A property that can be used to get the currently applied filters and to set new filters. When the filters are modified the search instance will reset its internal pagination and the next request to get results will start from offset zero.
sorting
A property that can be used to get the currently applied sorting and to set new sorting. When the sorting is modified the search instance will reset its internal pagination and the next request to get results will start from offset zero.
search_term
The search therm that will be used on the next search request. When the search term is modified the search instance will reset its internal pagination and the next request to get results will start from offset zero. Notice that modifying the search term also resets/removes any sorting and filters applied.
offsets
Get the current offsets (pagination information) for each of the search engines, product and enabled content types.
Instance level methods
initial_render(callback)
Sends a search request that fetches available filters, if return_filters
is true. It will also return any configured initial content. The callback
is called when the results are ready. It is passed one argument which is a function that can be called with a CSS selector to get some part of the HTML response.
yield_template(callback)
Sends a search request that fetches the next page of search results, for all configured search engines that still have more results. It is passed one argument which is a function that can be called with a CSS selector to get some part of the HTML response.