Tribute Documentation

repository·master·Indexed 24 days ago

https://github.com/zurb/tribute

Tribute is a lightweight, dependency-free cross-browser @mention engine written in ES6. It allows developers to implement autocomplete and mention functionality in inputs, textareas, and contenteditable elements. The library supports multiple collections with distinct triggers, dynamic remote data loading, custom templates for menu items and selections, and programmatic control via the tributejs package.

Tokens
3.7K
Snippets
14
Records
27
Agent score
30%

What's inside Tribute

  1. Use a dynamic lookup function in a Collection

    master

    If your data objects have multiple attributes you want to search against, you can provide a function to the lookup key instead of a string. This function receives the object and the current mention text.

    {
      lookup: function (person, mentionText) {
        return person.name + person.email;
      }
    }
  2. Access the Template Item object

    master

    The selectTemplate and menuItemTemplate functions receive an item object. This is a meta-object that wraps your original data with search metadata:

    • index: The index of the match.
    • original: The original object from your values array.
    • score: The match score.
    • string: The matched string (often containing HTML for highlighting).
  3. Configure Webpack for Tribute

    master

    When using Webpack, ensure your Babel module loader does not exclude tributejs from being compiled by updating your configuration:

    {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules\/(?!tributejs)/
    }
  4. Embed clickable links in contenteditable elements

    master

    When using selectTemplate to insert HTML into a contenteditable element, standard anchor tags (<a>) may not be clickable. To make them clickable and prevent issues with matches being modified, wrap the anchor in an element with contenteditable="false".

    var tribute = new Tribute({
      values: [
        { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" },
        { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riper@zurb.com" }
      ],
      selectTemplate: function(item) {
        return (
          '<span contenteditable="false"><a href="http://zurb.com" target="_blank" title="' +
          item.original.email +
          '">' + item.original.value +
          "</a></span>"
        );
      }
    });
  5. Load data from a remote source

    master

    For large datasets, you can implement dynamic loading by passing a function to the values configuration option. This function should accept the search text and a callback cb which you call with the retrieved data.

    {
      //..other config options
      // function retrieving an array of objects
      values: function (text, cb) {
        remoteSearch(text, users => cb(users));
      },
      lookup: 'name',
      fillAttr: 'name'
    }
    
    function remoteSearch(text, cb) {
      var URL = "YOUR DATA ENDPOINT";
      xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            var data = JSON.parse(xhr.responseText);
            cb(data);
          } else if (xhr.status === 403) {
            cb([]);
          }
        }
      };
      xhr.open("GET", URL + "?q=" + text, true);
      xhr.send();
    }
  6. Install Tribute via Ruby Gem (Rails)

    master

    To use Tribute in a Rails project:

    1. Add the gem to your Gemfile:
    gem 'tribute'
    1. Add the requirement to app/assets/javascripts/application.js:
    *= require tribute
    1. Add the requirement to app/assets/stylesheets/application.css:
    //= require tribute
  7. Configure a Tribute Collection

    master

    A Collection is a configuration object that defines how mentions behave. Key options include:

    • trigger: The string that starts the lookup (e.g., '@').
    • values: (REQUIRED) An array of objects to match or a function that returns data.
    • lookup: The column to search against (string or function).
    • fillAttr: The attribute containing the content to insert by default.
    • selectTemplate: Function called on selection to return the content to insert.
    • menuItemTemplate: Function to define how items appear in the menu.
    • requireLeadingSpace: Whether a space is required before the trigger.
    • autocompleteMode: If true, turns Tribute into an autocomplete engine.
    • menuItemLimit: Limits the number of items in the menu.
    • menuShowMinLength: Minimum characters typed before the menu appears.
  8. Attach Tribute menu to a scrollable container

    master

    By default, the Tribute menu may not scroll with its parent. To ensure the menu stays attached to a specific scrollable parent element, set the menuContainer option to that element.

    {
      //..other config options
      menuContainer: document.getElementById("wrapper");
    }
  9. Initialize Tribute with a collection

    master

    To use Tribute, instantiate the Tribute class with a configuration object. You must provide either a values array or a collection array.

    If you provide values, Tribute creates a single collection using the default settings. If you provide collection, you can define multiple distinct lookup sets (e.g., one for @users and one for #tags) with their own triggers and templates.

    Supported input types are TEXTAREA and INPUT. For contentEditable elements, Tribute will use HTML spans for mentions; for standard inputs, it will use plain text.

  10. Trigger mentions with multi-character strings

    master

    Tribute can be configured to trigger on strings longer than a single character (e.g., {{ for variable autocompletion) by setting the trigger option.

    var tribute = new Tribute({
      trigger: "{{",
      values: [
        { key: "red", value: "#FF0000" },
        { key: "green", value: "#00FF00" }
      ],
      selectTemplate: function(item) {
        return "{{" + item.original.key + "}}";
      },
      menuItemTemplate: function(item) {
        return item.original.key + " = " + item.original.value;
      }
    });