At.js - Documentation

What is At.js?

At.js is a lightweight JavaScript library designed to simplify the implementation of “@” mentions (or “at” mentions) in text input fields. It provides a seamless and efficient way to detect, suggest, and insert user mentions, enhancing the user experience in applications requiring tagging or referencing capabilities, such as social media platforms, collaborative tools, and comment sections. At.js handles the complexities of user input, suggestion display, and data management, allowing developers to focus on the core functionality of their application.

Key Features and Benefits

Installation and Setup

At.js can be installed using npm or yarn:

npm install at.js
# or
yarn add at.js

Include the library in your HTML file:

<script src="path/to/at.js/dist/at.js"></script>

Alternatively, you can use a CDN link (check the At.js repository for the latest CDN link).

Basic Usage Example

This example demonstrates the basic usage of At.js with a sample data source:

<!DOCTYPE html>
<html>
<head>
  <title>At.js Example</title>
  <script src="path/to/at.js/dist/at.js"></script> </head>
<body>

<textarea id="myTextarea"></textarea>

<script>
  const at = new At({
    element: document.getElementById('myTextarea'),
    data: [
      { id: 1, name: 'John Doe', username: 'johndoe' },
      { id: 2, name: 'Jane Smith', username: 'janesmith' },
    ],
    //Further Customization (Optional):
    tpl: (item) => `<span class="mention">${item.username}</span>`, //Custom template
    callbacks: {
      mentionChosen: (mention) => {
        console.log('Mention chosen:', mention);
      },
    },
  });
</script>

</body>
</html>

This code snippet initializes At.js on a textarea with a sample dataset. Typing “@” in the textarea will trigger the suggestion list, allowing users to select a mention. The mentionChosen callback demonstrates how you can handle the selection event. Remember to replace "path/to/at.js/dist/at.js" with the actual path to the At.js library file. Refer to the API documentation for more advanced configuration options and customization.

Core Concepts

Mentioning Users

At.js’s core functionality revolves around mentioning users within a text input field. Users initiate a mention by typing the “@” symbol followed by characters. At.js then presents a list of suggestions based on the typed characters and the configured data source. Selecting a suggestion from the list inserts the corresponding mention into the input field, typically formatted as a unique identifier (e.g., username) wrapped within specific HTML tags for styling and processing. The specific formatting of the mention is customizable through templates. The library handles the complexities of managing the cursor position and updating the text content to maintain a smooth user experience.

Autocomplete Functionality

At.js leverages autocomplete functionality to provide a seamless user experience. As the user types characters after the “@” symbol, the library dynamically filters and displays a list of relevant suggestions. This list is typically presented as a dropdown or pop-up menu directly below the input field. The suggestions are ranked based on relevance, ensuring the most likely matches appear at the top of the list. The user can navigate this list using keyboard navigation (e.g., up/down arrow keys) and select a suggestion with the Enter key or mouse click.

Handling Mentions

After a user selects a mention, At.js manages the integration of the selected mention into the text input field. This typically involves inserting the mention with appropriate formatting and ensuring the cursor is positioned correctly for continued typing. The library provides callbacks that allow developers to execute custom actions whenever a mention is chosen, offering extensive control over the post-selection behavior, such as updating a related data model or triggering network requests. These callbacks offer the developer control over how the application handles the selected mention’s data.

Data Sources

At.js supports multiple data sources for user information, providing flexibility for different application architectures. The data source can be a simple JavaScript array, a JSON object, or a remote API endpoint. This versatility allows developers to easily integrate At.js with existing data models and backend infrastructure. The library’s API allows the developer to specify how and where to fetch the data, including providing customized fetching functions for remote data sources.

Customization Options

At.js offers extensive customization options to adapt to various application designs and requirements. Developers can customize the appearance of the suggestion list, the styling of mentions within the text input, the trigger character (not limited to “@”), and keyboard navigation behavior. Template functions allow developers to define the exact HTML structure used to represent mentions in the input. Callback functions provide fine-grained control over events such as suggestion selection and input changes. These customization options ensure seamless integration with existing designs and workflows.

API Reference

at.js Constructor

The At constructor initializes the At.js instance. It takes a single argument: a configuration object. This object specifies various settings to customize the behavior and appearance of At.js. The constructor returns an instance of the At class, allowing for further method calls and event handling.

const at = new At(config);

where config is an object described in the next section.

Configuration Options

The configuration object passed to the At constructor accepts the following options:

Methods

The At class exposes the following methods:

Events

At.js triggers several custom events that can be listened for using standard JavaScript event listeners (e.g., addEventListener). These events provide information about mention selection and changes to the input field. The following are some example events:

These are example events. Specific events and their details may vary depending on the version of At.js. Consult the At.js documentation for the most up-to-date list of events and their respective properties. Refer to the complete API documentation for additional details and examples.

Advanced Usage

Customizing the User Interface

At.js provides extensive customization options to seamlessly integrate with your application’s UI. Beyond the basic configuration options, you can deeply tailor the visual aspects and behavior. This includes:

Integrating with Other Libraries

At.js can be effectively integrated with other JavaScript libraries to enhance its functionality or fit into broader application architectures.

Handling Large Datasets

When dealing with large datasets of users, performance optimization is crucial. At.js offers several strategies to address this:

Performance Optimization

Beyond handling large datasets, general performance optimization strategies for At.js include:

Internationalization and Localization

Supporting multiple languages requires careful consideration of text encoding and user interface elements. At.js offers basic support for this by allowing the use of Unicode characters within the mention data and custom templates. However, for robust internationalization and localization, you would typically need to complement At.js with a dedicated internationalization library that handles translation of strings, date/time formatting, and cultural considerations in the UI. This often involves building language-specific resources or using translation APIs.

Troubleshooting

Common Issues and Solutions

This section addresses common problems encountered when using At.js and provides solutions.

Debugging Tips

Error Handling

At.js itself may not throw explicit errors in all situations. However, errors can arise due to problems with the data source (network requests failing, incorrect data formats) or within custom callback functions. Implement appropriate error handling mechanisms:

Examples

Simple Mentioning Example

This example demonstrates basic mention functionality using an inline array for user data:

<!DOCTYPE html>
<html>
<head>
  <title>At.js Simple Example</title>
  <script src="path/to/at.js/dist/at.js"></script>
</head>
<body>
<textarea id="myTextarea"></textarea>

<script>
  const at = new At({
    element: document.getElementById('myTextarea'),
    data: [
      { id: 1, name: 'Alice', username: 'alice' },
      { id: 2, name: 'Bob', username: 'bob' },
      { id: 3, name: 'Charlie', username: 'charlie' }
    ],
    callbacks: {
      mentionChosen: (mention) => {
        console.log('Mention chosen:', mention);
      }
    }
  });
</script>
</body>
</html>

This code initializes At.js on a textarea with a simple data array. Typing “@” will trigger the suggestion list, allowing you to select users. The mentionChosen callback logs the selected mention to the console.

Autocomplete with Custom Data

This example showcases autocomplete with data fetched from a remote JSON endpoint:

const at = new At({
  element: document.getElementById('myTextarea'),
  async: true,
  data: () => {
    return fetch('/api/users')
      .then(response => response.json())
      .then(data => data.users);
  },
  tpl: (item) => `<span class="mention">@${item.username} (${item.name})</span>`,
  callbacks: {
    mentionChosen: (mention) => { /* Handle mention selection */ }
  }
});

This uses async: true and provides a function that fetches user data from /api/users. The tpl function customizes the mention’s rendering. Remember to replace /api/users with your actual API endpoint.

Integration with a Chat Application

This example illustrates integration within a chat application, using a custom template and handling mention selection:

const at = new At({
  element: document.getElementById('chatInput'),
  data: chatUsers, // Assume chatUsers is an array of user objects
  tpl: (item) => `<span class="mention" data-user-id="${item.id}">@${item.username}</span>`,
  callbacks: {
    mentionChosen: (mention) => {
      // Append mention to chat message, perhaps updating a message object
      let message = document.getElementById('chatMessage');
      message.innerHTML += `<span class="mention" data-user-id="${mention.id}">@${mention.username}</span> `;
    }
  }
});

This example demonstrates how to customize the mention’s HTML using data-user-id for further processing. The mentionChosen callback updates the chatMessage element accordingly.

Building a Complex Mentioning System

For complex systems, consider these enhancements:

These examples provide a starting point for various At.js applications. Remember to adapt and extend them to meet the specific needs of your project. Remember to adjust paths and API endpoints according to your setup.