Loosen

Install the widget

Loosen explains empty search results. When your visitor's filters return nothing (or fewer results than they want: see 5.8), the widget shows exactly which combinations of filters conflict and what to relax, and applies the change to your filters with one click.

Runnable examples of every form below: live demo (nothing to install) and github.com/sicena-com/loosen-examples (open source, 186 apartments, run locally with ./serve.sh).

There are two ways to run the analysis:

Browser modeServer mode
The analysis runsin the visitor's browseron your Loosen server (loosend)
You provideyour products as JSONa catalogue loaded in loosend (feed or API)
Good forup to a few thousand items (your licence's item limit)catalogues of any size (hundreds of thousands)
Networkone download of the dataone small request per search (debounced)
PlansStarter, Business, trialBusiness, trial

Browsers: anything with Shadow DOM, BigInt and Object.hasOwn: Chrome and Edge 93+, Firefox 92+, Safari 15.4+. The automated tests run in Chromium only; that is the support we can vouch for today.

1. Get a licence key

You receive a licence key starting with LSN1.: it says which domains it covers, which plan, how many items it allows, and until when. Start a free trial (the key comes by email) or subscribe (set your domains on your private licence page, where the key and a pre-filled install code appear).

The key is checked in the browser, offline, against the Loosen public key that is built into the widget. It cannot break your site: an invalid key only makes the widget show a small “Unlicensed copy” note, write one warning to the console and limit browser mode to 1,000 rows.

StarterBusinessTrial
“Loosen by Sicena” link (to loosen.sicena.com)alwaysnoyes
Domains151
Items50,0002,000,00050,000
Servernoyesyes

Domains: example.com is exactly that host; *.example.com is any subdomain, not example.com itself. localhost, 127.0.0.1 and *.local always work, so you can develop without a licence for your staging domain. Without a valid licence, on another domain, or after expiry, the widget still works, shows “Unlicensed copy” and refuses to analyse more than 1,000 rows in the browser.

Auto-renewing licence: licenceUrl

A renewal issues a new key. By default you paste it into your page. With licenceUrl you paste the address of your licence’s token endpoint once (it is on your private licence page), and the widget fetches the current key from it, so a renewal needs no change on your site:

Loosen.mount(el, {
  licence: "LSN1....",                                           // the key you have now: used if the address cannot be reached
  licenceUrl: "https://loosen.sicena.com/licence/<your licence reference>/token",
  ...
});

What is sent. One plain GET of that address from your visitor’s browser, once per page load however many widgets the page has: no cookies, no custom headers, no body, and nothing about the visitor, the page or your catalogue. Like any web request it shows our server the visitor’s IP address and your page’s origin. What comes back. The current key as plain text (200, Access-Control-Allow-Origin: *, cached for 5 minutes), or 404 for an unknown or withdrawn licence.

How it is used. The widget checks the fetched key exactly like the one in your page (signature, domain, expiry) and uses whichever valid key expires last, remembering it in localStorage. If the request fails or times out (3 seconds), the widget carries on with the key it has: it never breaks your page (the first analysis waits for the answer at most 3 seconds), and a visitor behind a blocker simply gets the embedded key. Who can read it. Anyone who has the address, which is in your page’s HTML; the key behind it is not a secret either, because it only works on your domains. Treat the address as you treat the key. Withdrawing a licence (a refund) makes the address answer 404.

2. Add the script

Runnable examples: examples/client-module.html (live) in the examples repository; the classic <script> form is examples/classic-script.html (live).

Load the widget with a plain script tag. It defines window.Loosen. It is about 80 KB, 26 KB gzipped, and includes the analysis engine and the texts in eight languages.

<script src="https://loosen.sicena.com/widget/v1/loosen.js"></script>

Three ways to serve it, from the simplest to the strictest:

  • From us (above): /widget/v1/loosen.js follows our compatible releases of version 1 and is cached for five minutes (then revalidated). It is served over HTTPS with CORS, so it also works with crossorigin="anonymous" and a Subresource Integrity check.
  • Pinned: an address that contains the file's hash and never changes (cached for a year), plus a Subresource Integrity check. The exact address and hash of the current file are on the downloads page. The same hash also works on the v1 address until we publish a compatible update; after that the browser refuses the script, so use the pinned address if you want to be sure which file runs.
    <!-- From us, checked with Subresource Integrity (the hash of the file served today; it stops matching after a compatible update of v1). -->
    <script src="https://loosen.sicena.com/widget/v1/loosen.js" integrity="sha384-bFHT/RF3rW5LudeoGop5Y5IOIN+qSlu+KU0ryL8lgwoawzzphe2XZC7mlVdM8S4w" crossorigin="anonymous"></script>
    <!-- Pinned: this exact file at an address that never changes (the address and hash of each file are on the downloads page). -->
    <script src="https://loosen.sicena.com/widget/v1/38ab5538ee/loosen.js" integrity="sha384-bFHT/RF3rW5LudeoGop5Y5IOIN+qSlu+KU0ryL8lgwoawzzphe2XZC7mlVdM8S4w" crossorigin="anonymous"></script>
  • Self-hosted: download the file and serve it yourself. With a Content-Security-Policy, script-src 'self' is then enough (loading it from us needs script-src https://loosen.sicena.com). The widget needs no unsafe-inline and no eval; in server mode add the server to connect-src.
    <!-- Self-hosting: copy loosen.js to your site and point the script tag at your copy.
         With a Content-Security-Policy, script-src 'self' is then enough. -->
    <script src="/assets/loosen.js"></script>

Prefer modules? Use loosen.mjs: import {mount} from "https://loosen.sicena.com/widget/v1/loosen.mjs";.

3. Declare your attributes

Tell the widget what each filterable attribute is. kind is required in browser mode:

  • numeric: numbers (and booleans as 1/0): price, rooms, “furnished”
  • text: one string per item: brand, town
  • set: several strings per item (an array): features, options

label and format (how a value reads, for example v => v + " CHF") are optional. Without format, numbers are written with your locale's separators.

4. Give it data, or a server

Runnable examples: examples/server.html (live) in the examples repository.

const base = {
  licence: "YOUR_LICENCE_KEY",
  attributes: {
    rent: {kind: "numeric", label: "Rent", format: v => v + " CHF"},
    furnished: {kind: "numeric", label: "Furnished", format: v => (v ? "yes" : "no")},
    minutesToCentre: {kind: "numeric", label: "Minutes to the centre", format: v => v + " min"},
    town: {kind: "text", label: "Town"},
    features: {kind: "set", label: "Features"},
  },
  data: "/apartments.json",     // client mode: an array of objects, as an array, a URL or an async function
};

The data is an array of plain objects, one per item, read as row[attr]; set attributes are arrays of strings; null or a missing value means “unknown” and never satisfies a constraint. data can be an array you already have, a URL, or async () => rows. Call widget.setData(rows) when it changes.

Server mode replaces data by server; attributes then only provides labels and formats:

const serverOptions = {
  server: {endpoint: "https://loosend.example.com", catalog: "apartments"},
  // ... licence, publicKey, attributes (labels only), getConstraints, applyRelaxation as below
};

How the catalogue gets into loosend

You run loosend yourself, on your own server, and you decide what it holds. The first load is a file or URL (a feed), or a call to the API. After that you choose how it stays current:

  • periodic feed re-read: the server fetches your CSV/JSON/NDJSON file or URL every few minutes (all or nothing; the previous data stays if a run fails);
  • push on each change: your back office calls the API when an item is added, changed or deleted;
  • periodic full replace: a scheduled job sends the whole catalogue, and the new one is swapped in without blocking searches.

In self-hosted mode the catalogue never reaches Sicena: it goes from your systems to your server. The widget only sends the visitor's current filters to your server, and the licence is checked offline. See feeds and the API.

The panel is an aid, not the source of truth. It explains from the catalogue loosend holds, which can lag behind your shop by one refresh interval, so it can occasionally suggest a change that gives slightly different results than your own search. Your search stays the authority on what is for sale.

Besides browser mode and the self-hosted server (binary or Docker image), some things are available on request: see options on request.

Run loosend and load your catalogue: see Run the Loosen server. The widget sends POST {endpoint}/v1/catalogs/{catalog}/explain with the constraints (at most 24 by default), waits 200 ms after the last change, aborts a request that a newer one makes obsolete, and gives up after 8 seconds. If the server is down the panel is replaced by “The explanation is unavailable right now.” and an error event is emitted; your page is unaffected.

Who may ask. The page's JavaScript is public, so explain has no password. Three things limit it: the server's CORS allow-list (which pages may read the answer); your licence's domains (the server refuses, 403 origin_not_licensed, a browser request from another domain); and an optional read key per catalogue, passed as server.key and sent in the X-Loosen-Key header:

const serverWithKey = {server: {endpoint: "https://loosend.example.com", catalog: "apartments", key: "YOUR_READ_KEY"}};

Be clear about what this protects. The read key sits in your page's source, so anyone who can open the page can read it: it is not a secret. It lets you revoke and limit access per catalogue (change the key and every copy of the old page configuration stops working at once) and keeps casual traffic away; it does not stop somebody who reads your page. The domain check relies on the Origin header, which browsers set and a program on a server can omit or fake, so it keeps other websites from using your server, not other programs. What bounds the cost of an abusive client is the per-IP rate limit, the concurrency cap, the constraint limit and the work budget. To rotate a key, set the new one on the server and deploy the page with the new server.key; the old key stops working at once.

Very hard questions. The search for explanations is exponential in the worst case (many filters that conflict in many different ways). Both engines stop after a fixed amount of work: the server answers 422 too_complex, the in-browser engine stops without freezing the page, and the widget shows “These filters are too complex to explain. Remove a few and try again.” and emits an error event with code too_complex. Fewer filters, or a smaller maxSize, make the question easy again.

5. Connect your filters

Two functions connect the widget to your filters (two more are optional: restoreConstraints gives the visitor an Undo, onPreview lets you highlight what a suggestion would change; see 5.6).

getConstraints() returns the visitor's current filters as an array of constraints:

opmeaningfield
eq, neequal, not equalvalue
le, geat most, at least (numeric)value
in, notInone of / none of these valuesvalues: [...]
allOf, anyOf, noneOffor set attributes: all / at least one / none of thesevalues: [...]

For example {attr: "rent", op: "le", value: 500} or {attr: "town", op: "in", values: ["Lausanne", "Pully"]}. At most 64; skip empty filters.

applyRelaxation(relaxation, constraints) is called when the visitor clicks a suggestion. Change your own filters (the function may be async: the widget waits for it); the widget then analyses again by itself on the next animation frame, so you do not call widget.update() here (see autoUpdate). relaxation.changes lists what to do, one entry per constraint: {index, attr, op, action: "clear" | "adapt", value, from}. clear removes that filter; adapt sets the bound to value (it was from). constraints is exactly what getConstraints() returned for this panel; index points into it. Each global suggestion also carries results, the number of items the query gives once it is applied (see 5.7).

Call widget.update() whenever the visitor changes a filter (a relaxation applied through applyRelaxation is already covered). It re-reads getConstraints(), analyses, and shows or hides the panel. It never throws; it returns a promise.

5.1 A plain HTML form: fromForm

Runnable example: examples/form-fromform.html (live) in the examples repository.

fromForm(form, fields) reads a form as constraints and applies relaxations back to it. This page is complete (replace YOUR_LICENCE_KEY and provide /apartments.json):

<!doctype html>
<meta charset="utf-8">
<title>Apartments</title>
<form id="filters">
  <label>Max rent <input type="number" name="max_rent"></label>
  <label>Max minutes to the centre <input type="number" name="max_centre"></label>
  <label><input type="checkbox" name="furnished" value="1"> Furnished</label>
  <fieldset><legend>Town</legend>
    <label><input type="checkbox" name="town" value="Lausanne"> Lausanne</label>
    <label><input type="checkbox" name="town" value="Pully"> Pully</label>
  </fieldset>
</form>
<div id="loosen"></div>
<script src="https://loosen.sicena.com/widget/v1/loosen.js"></script>
<script>
  const form = document.getElementById("filters");
  const binding = Loosen.fromForm(form, {
    max_rent: {attr: "rent", op: "le"},                  // a number field: empty = no constraint
    max_centre: {attr: "minutesToCentre", op: "le"},
    furnished: {attr: "furnished", op: "eq"},            // one checkbox: checked = constraint with value 1
    town: {attr: "town", op: "in"},                      // several checkboxes with the same name: the checked values
  });
  const widget = Loosen.mount(document.getElementById("loosen"), {
    licence: "YOUR_LICENCE_KEY",
    attributes: {
      rent: {kind: "numeric", label: "Rent", format: v => v + " CHF"},
      minutesToCentre: {kind: "numeric", label: "Minutes to the centre", format: v => v + " min"},
      furnished: {kind: "numeric", label: "Furnished", format: v => (v ? "yes" : "no")},
      town: {kind: "text", label: "Town"},
    },
    data: "/apartments.json",
    getConstraints: binding.getConstraints,
    applyRelaxation: binding.applyRelaxation,            // edits the form fields; the widget updates itself afterwards
    restoreConstraints: binding.restoreConstraints,      // optional: puts the form back as it was, for the "Undo" button
    onPreview: binding.onPreview,                        // optional: marks the fields a hovered chip would change (data-loosen-preview)
  });
  form.addEventListener("input", () => widget.update());
  widget.update();
</script>

Field rules: a number/text/select field gives value (a number if type="number", type="range" or number: true); a single checkbox gives value (default 1, or the value in the spec); radios give the checked one (see the radio notes below); several checkboxes with one name or a <select multiple> give values for the list operators. A relaxation unchecks, empties or selects the empty option, or writes the new bound into the field. It does not fire the form's own input event: the widget updates itself afterwards, but refresh your result list yourself. binding.restoreConstraints(constraints) puts the form back to a constraint list (every mapped field gets its value, the others are cleared) and binding.onPreview sets the attribute data-loosen-preview on the fields a hovered suggestion would change (style it: [data-loosen-preview] { outline: 2px solid #2563eb; }).

Radios. A radio's value is a string unless the spec says number: true, so yes/no radios with value="1" and value="0" need {attr: "furnished", op: "eq", number: true}. A radio whose value is the empty string (an “any” choice) is read as 0 (Number("")), not as “no constraint”: do not use it. Leave all radios of the group unchecked for “any” and give the visitor a button that unchecks them (a relaxation of a radio unchecks it too):

<div role="group" aria-label="Furnished">
  <label><input type="radio" name="furnished" value="1"> yes</label>
  <label><input type="radio" name="furnished" value="0"> no</label>
  <button type="button" data-clear="furnished">any</button>
</div>
<script>
  // fields: furnished: {attr: "furnished", op: "eq", number: true}
  form.querySelectorAll("[data-clear]").forEach(button => button.addEventListener("click", () => {
    form.querySelectorAll(`[name="${button.dataset.clear}"]`).forEach(radio => { radio.checked = false; });
    form.dispatchEvent(new Event("input", {bubbles: true}));   // so that widget.update() runs
  }));
</script>

5.2 Any form, by hand

Runnable example: examples/by-hand.html (live) in the examples repository.

When your markup is not a plain form, write the two functions yourself:

const form = document.getElementById("filters");

const getConstraints = () => {
  const data = new FormData(form), out = [];
  if (data.get("max_rent")) out.push({attr: "rent", op: "le", value: Number(data.get("max_rent"))});
  if (data.get("furnished")) out.push({attr: "furnished", op: "eq", value: 1});
  const towns = data.getAll("town");
  if (towns.length) out.push({attr: "town", op: "in", values: towns});
  return out;
};

const applyRelaxation = (relaxation, constraints) => {
  for (const change of relaxation.changes) {
    const attr = constraints[change.index].attr;
    if (attr === "rent") form.elements.max_rent.value = change.action === "adapt" ? change.value : "";
    if (attr === "furnished") form.elements.furnished.checked = false;
    if (attr === "town") form.querySelectorAll("[name=town]").forEach(box => { box.checked = false; });
  }
};                                                       // the widget analyses again by itself afterwards

// Optional, for "Undo": the exact inverse of getConstraints (set every filter to what the list says, clear the others)
const restoreConstraints = constraints => {
  const find = attr => constraints.find(c => c.attr === attr);
  form.elements.max_rent.value = find("rent")?.value ?? "";
  form.elements.furnished.checked = !!find("furnished");
  form.querySelectorAll("[name=town]").forEach(box => { box.checked = !!find("town")?.values.includes(box.value); });
};

const widget = mount(document.getElementById("loosen"), {...base, getConstraints, applyRelaxation, restoreConstraints});
form.addEventListener("input", () => widget.update());
widget.update();

5.3 A facet state object (Typesense, Meilisearch, Algolia and the like)

Runnable example: examples/facets-state.html (live) in the examples repository.

Search UIs keep their filters in one state object. Convert it to constraints and back; relaxedConstraints(relaxation, constraints) gives you the constraint list after the relaxation (cleared ones removed, adapted ones moved), so you write the mapping once:

const state = {
  facets: {town: ["Pully"], features: ["view"]},        // facet value lists
  ranges: {rent: {max: 400}},                           // numeric ranges
};

const toConstraints = s => [
  ...(s.ranges.rent?.max != null ? [{attr: "rent", op: "le", value: s.ranges.rent.max}] : []),
  ...(s.facets.town?.length ? [{attr: "town", op: "in", values: s.facets.town}] : []),
  ...(s.facets.features?.length ? [{attr: "features", op: "allOf", values: s.facets.features}] : []),
];

const toState = constraints => {
  const next = {facets: {}, ranges: {}};
  for (const c of constraints) {
    if (c.attr === "rent") next.ranges.rent = {max: c.value};
    if (c.attr === "town") next.facets.town = c.values;
    if (c.attr === "features") next.facets.features = c.values;
  }
  return next;
};

const widget = mount(document.getElementById("loosen"), {
  ...base,
  getConstraints: () => toConstraints(state),
  applyRelaxation: (relaxation, constraints) => {
    Object.assign(state, toState(relaxedConstraints(relaxation, constraints)));   // your own state update / re-search goes here
  },
  restoreConstraints: constraints => Object.assign(state, toState(constraints)),  // optional, for "Undo": the same mapping, fed with the previous constraints
});
widget.update();                                         // call again after every other state change (the visitor's own)

More on search engines: integrations.

5.4 React

Runnable example: examples/react.html (live) in the examples repository.

The widget owns a DOM node; create it in an effect and keep the latest filters in a ref, so getConstraints always sees them. setFilters is asynchronous: right after a click on a suggestion the widget reads getConstraints() again, and if that still returns the old filters the widget decides that the visitor changed them and drops the Undo. So write the new filters into the ref synchronously, before calling setFilters (the apply helper below), in both applyRelaxation and restoreConstraints. The effect on [filters] then calls update() once React has committed the state:

function useLoosen(containerRef, filters, setFilters) {
  const latest = React.useRef(filters);
  latest.current = filters;                              // getConstraints must read the newest filters
  const widget = React.useRef(null);
  const apply = next => { latest.current = next; setFilters(next); };   // the ref first (synchronously), then React state

  React.useEffect(() => {
    widget.current = mount(containerRef.current, {
      ...base,
      autoUpdate: false,                                 // React re-renders and the effect below calls update(): no second analysis
      getConstraints: () => toConstraints(latest.current),
      applyRelaxation: (relaxation, constraints) =>
        apply(toFilters(relaxedConstraints(relaxation, constraints))),   // without the ref write the Undo is dropped
      restoreConstraints: constraints => apply(toFilters(constraints)),  // optional, for "Undo"
    });
    return () => widget.current.destroy();
  }, []);

  React.useEffect(() => { widget.current?.update(); }, [filters]);
}

const toConstraints = f => [
  ...(f.maxRent != null ? [{attr: "rent", op: "le", value: f.maxRent}] : []),
  ...(f.towns.length ? [{attr: "town", op: "in", values: f.towns}] : []),
];
const toFilters = constraints => ({
  maxRent: constraints.find(c => c.attr === "rent")?.value ?? null,
  towns: constraints.find(c => c.attr === "town")?.values ?? [],
});

// in a component:   const ref = React.useRef(null);   useLoosen(ref, filters, setFilters);   return <div ref={ref} />;

This recipe is tested in real React 18, including the Undo, and against a minimal stand-in for the hooks whose setFilters is asynchronous like React's.

5.5 Filters in the URL (WooCommerce, Shopify and other server-rendered shops)

Runnable example: a small Go shop, cmd/shop (live), in the examples repository.

Server-rendered shops keep the visitor's filters in the URL and reload the page on every change. Then getConstraints parses the URL, applyRelaxation builds the relaxed URL and navigates to it, and the widget is mounted on the page that says “no products found”:

// the URL parameters of the shop, as constraints. WooCommerce uses max_price and filter_<attribute>;
// Shopify storefront filtering uses filter.v.price.lte and filter.v.option.<name>: adapt the table to your theme.
const PARAMS = [
  {param: "max_price", attr: "rent", op: "le", number: true},
  {param: "filter_town", attr: "town", op: "in", list: true},
];

const getConstraints = () => {
  const query = new URLSearchParams(location.search), out = [];
  for (const p of PARAMS) {
    const raw = p.list ? query.getAll(p.param).flatMap(v => v.split(",")) : query.get(p.param);
    if (p.list ? raw.length : raw) out.push(p.list ? {attr: p.attr, op: p.op, values: raw} : {attr: p.attr, op: p.op, value: p.number ? Number(raw) : raw});
  }
  return out;
};

const relaxedUrl = (relaxation, constraints) => {
  const query = new URLSearchParams(location.search);
  for (const change of relaxation.changes) {
    const p = PARAMS.find(x => x.attr === constraints[change.index].attr);
    if (change.action === "adapt") query.set(p.param, String(change.value)); else query.delete(p.param);
  }
  return `${location.pathname}?${query}`;
};

const widget = mount(document.getElementById("loosen"), {
  ...base,
  getConstraints,
  autoUpdate: false,                                     // the page is replaced: nothing to update
  applyRelaxation: (relaxation, constraints) => location.assign(relaxedUrl(relaxation, constraints)),
});
widget.update();

More on hosted shops: integrations. Do not pass restoreConstraints here: applying a relaxation replaces the page, so there is no panel left to hold the Undo button (the browser's Back button already undoes it).

5.6 Undo, and highlighting what a suggestion changes

Both are optional callbacks next to applyRelaxation; the widget does nothing extra when they are missing.

Undo: restoreConstraints(previousConstraints). Give it and, right after a suggestion is applied, the widget shows a small status line under the panel, “Applied: Rent ≤ 706 CHF”, with an Undo button (it also shows when the applied suggestion made the panel disappear, which is the usual case). previousConstraints is the exact array getConstraints() returned just before your applyRelaxation ran; put your filters back so that getConstraints() returns it again (the inverse of getConstraints: binding.restoreConstraints for fromForm, toState(constraints) for a state object). It may be async. Then the widget analyses again, the panel returns, “Filters restored” is announced to screen readers and the keyboard focus goes to the first suggestion.

  • One level only: applying another suggestion replaces the Undo of the previous one.
  • The Undo stays until it is used or until the visitor changes the filters by any other means: the widget compares the constraints of every update() with the ones read right after your applyRelaxation, so call widget.update() after the visitor's own changes.
  • Keyboard: after a click the focus moves to the Undo button, so Enter undoes it at once.
  • Event relaxation_undone (step 6). An exception or rejection from restoreConstraints becomes an error event with code restore.

Highlight: onPreview(relaxation, constraints). While a suggestion is hovered with a mouse or pen, or has keyboard focus, the widget calls onPreview(suggestion, constraints) with the same relaxation object applyRelaxation would get (relaxation.changes[].index points into constraints), and onPreview(null, constraints) when it is left (and when the panel is redrawn or the suggestion clicked, so nothing stays highlighted). Mark the filters it would change, for instance with a CSS class on their controls; fromForm does it for you (onPreview: binding.onPreview). Touch devices do not preview. The analytics event relaxation_previewed is only emitted when the suggestion stays hovered or focused for 150 ms.

5.7 What a suggestion shows: result counts and order

Result count. A global suggestion reads “Rent ≤ 706 CHF · 12 results” (1 result, 1,234 results; showResults: false hides it). It is the number of items the visitor gets if they apply it: the items that match the whole query after the change (the adapted filter at its new bound, the other filters of the suggestion removed, every other filter unchanged), so it is never smaller than minItems. The screen-reader name of the button includes it. Suggestions under “Why?” have no count: they fix one conflict, which is a sub-question about only the filters of that conflict, so a count would not say how many results the visitor gets.

Order. With order: "cost" (the default) the suggestions are listed by the price of the change, cheapest first. The price is 1 to remove a filter, and for a moved bound the distance moved as a fraction of the attribute's range in your data (largest minus smallest value), at most 1: “Rent ≤ 706 CHF” instead of 500 in a catalogue of rents from 300 to 3,000 costs 206/2,700 = 0.08; a suggestion with several changes costs the sum. Equal prices keep the canonical order (fewer filters first, then the position of the filter in your constraint list), so the list is the same on every run. limit cuts the list after sorting, so the ones kept are the cheapest. The suggestions under “Why?” are sorted the same way. order: "canonical" skips the cost and gives the canonical order.

5.8 Not only zero results: a minimum number of results

Loosen does not have to wait for an empty list. With minItems: N it explains and suggests changes whenever fewer than N items match: “show me at least 3 options”. The default is 1, the classic “no dead ends” behaviour (the panel appears only when nothing matches).

Example on the apartments catalogue: Rent ≤ 1200 CHF and Rooms ≥ 3 match exactly one apartment. With the default nothing is shown. With minItems: 3 the panel appears and offers changes that give at least 3 results:

const form = document.getElementById("filters");
const binding = Loosen.fromForm(form, {
  max_rent:  {attr: "rent",  op: "le"},
  min_rooms: {attr: "rooms", op: "ge"},
});

const widget = mount(document.getElementById("loosen"), {
  ...base,
  attributes: {...base.attributes, rooms: {kind: "numeric", label: "Rooms"}},
  minItems: 3,                 // explain and suggest when fewer than 3 items match
  userMinItems: true,          // optional: "Warn me if fewer than [3] results", remembered in the browser
  getConstraints: binding.getConstraints,
  applyRelaxation: binding.applyRelaxation,
});
form.addEventListener("input", () => widget.update());
widget.update();
Any of these changes gives at least 3 results:
  [Rent ≤ 1380 CHF · 3 results]  [Rooms ≥ 2 · 40 results]

How it behaves:

  • The numbers are guaranteed. Every suggestion is computed so that applying it gives at least minItems results, and the button says how many it gives (see 5.7). A moved bound is the N-th best value among the items that satisfy the other filters: the 3rd smallest rent of the three-room apartments is 1380, so “Rent ≤ 1380 CHF” gives 3 results: the smallest move that is enough, and never fewer than N.
  • A filter nothing can fix is not offered. If the catalogue has fewer than N items, no change could help and nothing is shown.
  • The “Why?” block follows: a conflict is a set of filters that fewer than N items satisfy together (“Fewer than 3 results with Rent ≤ 1200 CHF and Rooms ≥ 3”).
  • The visitor can choose. userMinItems: true adds “Warn me if fewer than [N] results” under the panel; the choice is kept in the browser (localStorage, see step 7) and minItems is the starting value. Or build your own input and give its value to minItems when you mount.
  • Server mode: minItems goes in the request to explain (the widget sends it for you). A minItems larger than the catalogue is refused by the server (422 cannot_explain).
  • Choosing the default. 1 for “no dead ends” (search pages where an empty list is the problem); 3 to 5 for browsing catalogues (apartments, cars, grants) where two results already feel like too few.
  • Limits. With N > 1 the search is level-wise over subsets of the filters, so maxSize (default 3) matters more than with N = 1: it keeps the analysis fast on large data and many filters. If you see “These filters are too complex to explain” with a high N, lower maxSize (in server mode the server applies 4 when minItems > 1 and you send none).

6. Events and A/B tests

Pass onEvent; the widget calls it with a plain object. This is how you measure whether the panel helps: mount the widget for one group of visitors only and compare conversion or abandonment.

typewhenfields
licenceonce, when the licence has been checkedstatus (valid/unlicensed), reason, plan, badge
panel_showna panel appears or its content changes (not on identical redraws)constraints, relaxations ([{changes: [{constraint, action, value, cost}], results, cost}], in the order shown), conflicts, mode, tookMs
relaxation_applieda suggestion was clickedkind (global or local), text, changes
relaxation_previeweda suggestion stayed hovered or focused for 150 ms (not emitted for a pass-over, so hovering across the panel is not analytics noise)kind, text, changes
relaxation_undonethe visitor used Undo (only with restoreConstraints)text, changes of the suggestion that was undone
errorsomething failed (the page keeps working)code (constraints, data, analysis, server, apply, restore, rows_limit, too_complex), message

An exception thrown by your handler is caught and logged; it cannot break the widget.

window.dataLayer = window.dataLayer || [];
const widget = mount(document.getElementById("loosen"), {
  ...base,
  getConstraints: () => [{attr: "rent", op: "le", value: 400}, {attr: "furnished", op: "eq", value: 1}, {attr: "town", op: "in", values: ["Pully"]}],
  applyRelaxation: () => {},
  onEvent: event => {
    if (event.type === "panel_shown") window.dataLayer.push({event: "loosen_panel_shown", relaxations: event.relaxations.length, conflicts: event.conflicts.length, ms: event.tookMs});
    if (event.type === "relaxation_applied") window.dataLayer.push({event: "loosen_relaxation_applied", kind: event.kind, text: event.text});
  },
});
widget.update();

7. Look, language and accessibility

Every option, event and theme variable in action: examples/playground.html (live) in the examples repository.

Isolation. The widget lives in a Shadow DOM: your page's CSS cannot restyle or break it, and its CSS cannot leak into your page. It inherits only text properties (font, color) from the element you mount it in. Style it with CSS custom properties set on the mount element or any ancestor:

PropertyDefault
--loosen-fontinheritfont shorthand
--loosen-fginherittext colour
--loosen-muted#667085secondary text, badge
--loosen-bg#fffpanel background
--loosen-border#d0d5ddpanel border
--loosen-radius8pxpanel corners
--loosen-padding12px 14pxpanel padding
--loosen-accent#2563ebsuggestion border, hover background, focus ring
--loosen-accent-fg#fffsuggestion text on hover
--loosen-chip-bg#eff4ffsuggestion background
--loosen-chip-fg#1d4ed8suggestion text
--loosen-warn#b42318the “Unlicensed copy” note

Language

The widget speaks eight languages, all bundled in the one script (no extra file to load): ca Catalan, es Spanish, en English, fr French, pt Portuguese (Brazil), zh Chinese (Simplified), ja Japanese and ar Arabic (right to left).

  • lang chooses the language: lang: "fr". A regional tag is accepted and mapped to its language (fr-CH, pt_BR, zh-Hans, upper or lower case). Default: the lang attribute of the host page (<html lang="fr">), else English. A language the widget does not have (de) falls back to English, silently: nothing is thrown and no error event is emitted. Setting lang on the page is the simplest integration and also makes the browser pick the right fonts and hyphenation for your own text.
  • locale only decides how numbers are written (counts, and values without a format). Default: the lang tag as given (fr-CH writes 1’234, fr writes 1 234), else the language. Digits are always Latin digits (0-9), also in Arabic, so a count in the panel reads like the same number in your data and in your own format functions.
  • texts overrides any text on top of the language, one key at a time (the rest stays in the language). A text is a string with {placeholders}, a function of its parameters, or, for the keys that count something, an object of plural forms. Unknown keys fail fast.
  • Plurals. The widget picks the form with Intl.PluralRules(lang), so every language gets every category its grammar needs. A counted text is a string (the same for every number) or an object keyed by CLDR plural category (zero, one, two, few, many, other). other is required; a category that is missing falls back to other. Chinese and Japanese only have other. Five keys can be plural, and the parameter that chooses the form is fixed per key: results and more by {count}; actionMin, noneMin and minAfter by {minItems} (see Texts). A function text receives the raw parameters (numbers) and does the plural itself.
  • Right to left. With Arabic the panel gets dir="rtl" (any other language gets dir="ltr", whatever direction your page has), the suggestions flow from the right, the “Why?” arrow points left, and comparisons (“≤ 706 CHF”) are isolated left-to-right runs, so the operator is not mirrored and the number stays readable. The “Loosen by Sicena” badge stays left to right. Nothing to do on your side, except dir="rtl" on your own page.
  • Chinese, Japanese and Arabic fonts. The widget sets lang on its own markup and uses your font (--loosen-font, else inherited) with the system's fallback fonts for the script, no web font. It does not letter-space Arabic.

French, with Swiss number formatting and two house-style overrides (the rest is the built-in French):

const widget = mount(document.getElementById("loosen"), {
  ...base,
  lang: "fr",
  locale: "fr-CH",
  texts: {
    clear: "Retirer {what}",
    results: {one: "{count} offre", many: "{count} d'offres", other: "{count} offres"},
  },
  getConstraints: () => [{attr: "rent", op: "le", value: 400}, {attr: "furnished", op: "eq", value: 1}, {attr: "town", op: "in", values: ["Pully"]}],
  applyRelaxation: () => {},
});
widget.update();

Arabic, taken from the page (<html lang="ar" dir="rtl">) instead of the lang option:

document.documentElement.lang = "ar";                       // normally already in your page's <html>
const widget = mount(document.getElementById("loosen"), {
  ...base,
  getConstraints: () => [{attr: "rent", op: "le", value: 400}, {attr: "furnished", op: "eq", value: 1}, {attr: "town", op: "in", values: ["Pully"]}],
  applyRelaxation: () => {},
});
widget.update();

Runnable example: examples/francais.html (live), the Lausanne apartments with a fully French page. Every page of the demo also has a language switch (Catalan, Spanish, English, French, Portuguese, Chinese, Japanese, Arabic).

Accessibility. The panel sits in a role="region" with aria-live="polite", so a screen reader announces a new explanation without stealing focus. Every suggestion is a real <button> (Tab, Enter, Space; visible focus ring). After a click, focus stays where your code leaves it, except with restoreConstraints: it moves to the Undo button (the suggestion it was on has gone), and after Undo to the first suggestion of the returned panel; the “Applied: ...” and “Filters restored” lines are in a role="status" region, so they are announced. The result count is part of the accessible name of a suggestion (“Rent ≤ 706 CHF (instead of ≤ 500 CHF), 12 results”). If your filters re-render, move focus to the control that changed.

Let the visitor choose the threshold. userMinItems: true adds “Warn me if fewer than [N] results”; the choice is kept in localStorage (under storageKey, or loosen-minItems:<id of the mount element>; if storage is blocked it lasts until the page closes). minItems is the starting value.

8. Reference

mount(element, options)

Returns {update, setData, destroy, licence, element}. Every option:

OptionTypeDefault
licencestringnoneThe licence key (LSN1....). Without a valid one the widget works but shows “Unlicensed copy”.
licenceUrlstringnoneThe address of your licence’s token endpoint (above). The widget uses the valid key that expires last among this one, the cached one and licence.
publicKeystringLoosen's keyFor development and tests: overrides the key licences are checked against (base64url or hex, 32 bytes). You normally never set it. (The widget is readable source, so the check is a courtesy; the server ignores its equivalent.)
attributesobjectrequired in browser mode{name: {kind, label, format}}, see step 3.
dataarray, URL or async functionrequired in browser modeThe items. Exclusive with server.
server{endpoint, catalog, key?}noneServer mode. Exclusive with data. key is the catalogue's read key, sent as X-Loosen-Key (optional).
getConstraintsfunctionrequiredReturns the current constraints.
applyRelaxationfunctionrequired(relaxation, constraints) => void | Promise; change your filters (the widget updates itself afterwards, see autoUpdate).
why"collapsed" | "expanded" | "hidden""collapsed"The “Why?” block, which lists the filters that cannot be satisfied together. "collapsed": a disclosure button opens it; "expanded": always shown; "hidden": left out. Presentation only: the events are the same.
original"auto" | "tooltip" | "inline" | "none""auto"Where an adapted chip (“Rent ≤ 706 CHF”) shows the bound it replaces (“was ≤ 500 CHF”): a tooltip on devices that can hover, inline on those that cannot.
showResultsbooleantrueShow the number of results each global suggestion would give: “Rent ≤ 706 CHF · 12 results” (see 5.7). false hides it.
order"cost" | "canonical""cost"The order of the suggestions: "cost" = cheapest change first (the smallest move of a bound, then clears), "canonical" = by number of filters, then by position of the filter (the same on every run, whatever the data). In server mode it is sent in the request.
restoreConstraintsfunctionnone(previousConstraints) => void | Promise: puts your filters back to that constraint list (the exact array getConstraints() returned just before the click). Giving it turns on Undo: see 5.6.
onPreviewfunctionnone(relaxation | null, constraints) => void: called when a suggestion is hovered or focused (the same relaxation object applyRelaxation receives) and with null when it is left. Use it to highlight the filters it would change: see 5.6.
minItemsinteger1Show the panel when fewer results than this match; every suggestion gives at least this many results. 1 = only when nothing matches; 3 = “at least 3 options” (see 5.8).
maxSizeinteger3Largest number of filters in one relaxation or conflict (keeps the analysis fast). 0 = no limit.
limitinteger8How many relaxations and how many conflicts to list; the rest is “and N more”.
userMinItemsbooleanfalseShow “Warn me if fewer than [N] results” so the visitor chooses the threshold (see 5.8).
storageKeystringloosen-minItems:<element id>localStorage key for the visitor's threshold.
langstring<html lang>, else "en"The language of the panel: ca, es, en, fr, pt, zh, ja or ar (a regional tag such as fr-CH is mapped to fr; any other language falls back to English). ar is laid out right to left. See Language.
localestringthe lang tagNumber formatting: counts and values without a format (always Latin digits). lang: "fr", locale: "fr-CH" writes 1’234.
textsobjectthe language'sText overrides, one key at a time, on top of the language: see Texts.
onEventfunctionnoneReceives the events of step 6.
debounceMsinteger200Server mode: wait after the last update() before asking.
timeoutMsinteger8000Server mode: give up on a request after this long.
autoUpdatebooleantrueAfter applyRelaxation returns (a returned promise is awaited), analyse again on the next animation frame. One analysis per click: it is skipped if you called update() yourself in the meantime, and several clicks before the frame count once. Set false if your framework updates the widget itself.
fetchfunctionwindow.fetchCustom fetch for data URLs and the server (for example to add a header).
hostnamestringlocation.hostnameThe host name the licence domains are checked against (previews behind a proxy).

The instance

  • update(): re-read getConstraints() and analyse. Returns a promise of "none", "panel", "error", "limit", or null if a newer update() superseded it. Never rejects.
  • setData(rows): replace the data (browser mode). Call update() after it.
  • destroy(): remove the widget and cancel pending work.
  • licence: promise of the verdict {valid, reason, plan, maxItems, badge, payload, source}; source is "embedded", "cache" or "url" (where the key that won came from, see licenceUrl).

The relaxation passed to applyRelaxation

{kind: "global" | "local", text, results, changes: [{index, attr, op, action: "clear" | "adapt", value, from}]}. A relaxation with several changes must be applied as a whole (one click). An adapt is only ever offered on le/ge constraints, with the tightest bound that gives at least minItems results. results is the number shown on a global suggestion (null for a local one, or when showResults is false).

Other exports: fromForm, relaxedConstraints, verifyLicence, domainAllowed, PRODUCTION_PUBLIC_KEY, BADGE_URL, BADGE_TEXT (“Loosen by Sicena”), OPTION_NAMES, VERSION.

Texts

Keys of texts and their English defaults ({name} marks a placeholder). The other seven languages have the same keys. A plural text lists its forms; the parameter in the last column chooses the form (see Language).

KeyEnglish defaultPlural form chosen by
regionSearch help
actionAny of these changes gives results:
actionMinone: Any of these changes gives at least {minItems} result:
other: Any of these changes gives at least {minItems} results:
{minItems}
whyWhy?
noneNo results with {list}
noneMinone: Fewer than {minItems} result with {list}
other: Fewer than {minItems} results with {list}
{minItems}
andand
oror
plus+
clearClear {what}
change{to} (instead of {from})
waswas {from}
moreand {count} more{count}
resultsone: {count} result
other: {count} results
{count}
appliedApplied: {text}
undoUndo
undoneFilters restored
eq{label} is {value}
ne{label} is not {value}
le{label} ≤ {value}
ge{label} ≥ {value}
in{label} is {values}
notIn{label} is none of {values}
allOf{label}: {values}
anyOf{label}: {values}
noneOf{label}: none of {values}
minBeforeWarn me if fewer than
minAfterone: result
other: results
{minItems}
minTitleMinimum number of results before the explanation appears
unlicensedUnlicensed copy
rowsLimitToo many rows to analyse in the browser ({rows} > {max}).
failedThe explanation is unavailable right now.
tooComplexThese filters are too complex to explain. Remove a few and try again.

Languages and the plural categories each one has to provide:

langLanguagePlural categoriesDirection
enEnglishone, otherleft to right
caCatalanone, many, otherleft to right
esSpanishone, many, otherleft to right
frFrenchone, many, otherleft to right
ptPortuguese (Brazil)one, many, otherleft to right
zhChinese (Simplified)otherleft to right
jaJapaneseotherleft to right
arArabiczero, one, two, few, many, otherright to left

The badge text (“Loosen by Sicena”) is a brand name, not a text: it cannot be overridden.

Problems? Troubleshooting.