Skip to content

Instantly share code, notes, and snippets.

@HelgaListopad
Created May 20, 2020 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HelgaListopad/7c99752a80b5b15c249c5c17e2e79d10 to your computer and use it in GitHub Desktop.
Save HelgaListopad/7c99752a80b5b15c249c5c17e2e79d10 to your computer and use it in GitHub Desktop.

Searching and highlighting can be implemented as a combination of two existing features:

  • common data filtering,
  • specific template of the column (for datatable) or of the component (for list and dataview).

In short, all you need to is:

  1. Remember searched text
  2. Use it for data filtering
  3. Use it in the template to find and mark all text occurences

In this example, the UI consists of two widgets: a Text view (standalone input for filtering) and a Datatable.

First, let's setup the onTimedKeyPress handler for the Text input. Here we can get the current value of the input and use it for data filtering.

// in Text configuration:
on: {
    onTimedKeyPress: function() {
        const value = this.getValue();
        findText(value);
    }
}

Filtering and remembering the value

The findText will activate filtering and make sure the value is stored somewhere for further usage. We'll also use a RegExp to escape special characters in the stored value, if there's any:

function findText(text) {
  /* store text that should be highlighted */
  text = text || "";
  escapedSearchText = text.replace(charactersSet, "\\$&");
  
  /* filter data */
  table.filter(filteringFunction)
};

Configuring template

As we have already called filtering, the Datatable will show the results. This is the moment when the filtered data is rendered according to the related template.

view:"datatable",
columns:[{ 
      id:"title",	
      template: searchColumnTemplate
}],

We'll use another RegExp to find the searched text and add a span with a specific CSS for it:

function searchColumnTemplate(data, type, value) {
  let search = escapedSearchText;
  if (search) {
    value = addTextMark(value, search);
  }
  return value;
};

function addTextMark(value, text) {
  const checkOccurence = new RegExp("(" + text + ")", "ig");
  return value.replace(
    checkOccurence,
    "<span class='search_mark'>$1</span>"
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment