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.
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).
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.
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.
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.
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.
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.
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.
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.
The configuration object passed to the At
constructor accepts the following options:
element
(required): A DOM element (e.g., <textarea>
, <input type="text">
) where At.js will operate. This is the element where mentions will be inserted and suggestions will appear.
data
(required): An array of objects representing the data for user mentions. Each object should contain at least a unique identifier (e.g., id
or username
) and a display name (e.g., name
). For remote data fetching, this can be a function that returns a Promise resolving to the data.
tpl
(optional): A function that receives a mention data object and returns the HTML string to be used for rendering the mention. Defaults to a simple text rendering of the display name.
callbacks
(optional): An object containing callback functions for various events (see the “Events” section below).
trigger
(optional): The character(s) used to trigger the mention suggestions. Defaults to “@”.
limit
(optional): The maximum number of suggestions to display. Defaults to 10.
filter
(optional): A custom filter function used to filter the data
array based on the user’s input. It receives the input text and data array and returns a filtered array.
placeHolder
(optional): Placeholder text to show in the input field when empty.
async
(optional): A boolean value. If true, async data fetching from a remote source is used. Defaults to false.
debounce
(optional): Number of milliseconds to debounce the input event. This is useful to prevent excessive API calls during rapid typing. Defaults to 250ms.
The At
class exposes the following methods:
destroy()
: Removes At.js functionality from the associated element and cleans up event listeners.
update(newData)
: Updates the data source used by At.js. Accepts an array or a Promise resolving to an array.
showSuggestions()
: Manually forces the display of the suggestion list. Useful for scenarios where programmatic control is needed.
hideSuggestions()
: Manually hides the suggestion list. Useful for scenarios where programmatic control is needed.
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:
at.mentionChosen
: Fired when a user selects a mention from the suggestion list. The event object contains details about the chosen mention (e.g., the data object of selected mention).
at.inputChanged
: Fired whenever the content of the input field changes.
at.suggestionsShown
: Fired when the suggestion list is displayed.
at.suggestionsHidden
: Fired when the suggestion list is hidden.
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.
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:
Custom Templates: The tpl
configuration option allows you to define a custom template function to dictate how mentions are rendered in the input field. This function receives the mention data object as input and should return a string representing the HTML for the mention. This allows for rich formatting, including custom icons, colors, or highlighting.
Styling the Suggestion List: The suggestion list’s appearance can be fully customized through CSS. At.js generates specific CSS classes for the suggestion list elements which can be targeted and styled according to your design preferences.
Customizing Keyboard Navigation: While At.js offers default keyboard navigation, it can be further customized or extended to implement special behaviors depending on the application’s requirements.
At.js can be effectively integrated with other JavaScript libraries to enhance its functionality or fit into broader application architectures.
UI Frameworks: At.js works well with popular frameworks like React, Vue, and Angular. These frameworks’ component models can be utilized to create custom wrappers and integrate At.js into their component lifecycle. This enables seamless integration within complex user interfaces built using these frameworks.
Data Management Libraries: The data source for At.js can be integrated with data management libraries like Redux or Vuex. This ensures consistency and efficiency in managing mention data across the application.
Third-party APIs: If your mention data is sourced from a third-party API, At.js can be readily integrated to consume data via asynchronous requests. Error handling and loading states should be incorporated to provide a robust user experience.
When dealing with large datasets of users, performance optimization is crucial. At.js offers several strategies to address this:
Asynchronous Data Fetching: The async
option in the configuration allows for asynchronous fetching of data, preventing UI blocking. This is essential for large datasets.
Client-Side Filtering and Pagination: Implement client-side filtering to reduce the amount of data processed. Introduce pagination to the suggestion list if the number of suggestions exceeds a certain threshold, fetching only a subset of data at a time.
Data Pre-processing: Pre-process the data on the server or client-side to improve search and filtering efficiency. Techniques like indexing or creating optimized data structures can greatly improve performance.
Beyond handling large datasets, general performance optimization strategies for At.js include:
Debouncing Input Events: The debounce
configuration option controls the frequency of data filtering and suggestion updates. A higher debounce value reduces the load on the application, but may increase perceived latency. Find the optimal balance.
Efficient Data Structures: Using efficient data structures to store and manage mention data, such as optimized search trees, can improve lookup times during filtering.
Minimizing DOM Manipulation: Minimize unnecessary DOM manipulations within the callback functions to avoid performance bottlenecks. Favor efficient updates and avoid repeated rendering.
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.
This section addresses common problems encountered when using At.js and provides solutions.
data
configuration option is correctly populated with user data. Check for typos or incorrect data formatting.tpl
function (if customized) for errors in HTML generation. Ensure proper escaping of special characters.data
object’s structure and ensure it provides the necessary fields used within the tpl
function.element
in the configuration) is properly positioned and visible in the DOM.update()
, At.js behaves unexpectedly (e.g., no suggestions).update()
method is called with a valid data array or a Promise resolving to one.Browser Developer Tools: Utilize your browser’s developer tools (usually accessed by pressing F12) to inspect the HTML, CSS, and JavaScript related to At.js. The console will display error messages and warnings. Use the debugger to step through the At.js code and identify issues.
Console Logging: Strategically place console.log()
statements within the At.js configuration and callback functions to inspect data values and execution flow. This helps pinpoint the source of problems.
Simplify: Create a minimal, reproducible example to isolate the issue. Start with a basic setup and gradually add complexity to identify the point where the problem occurs.
Check the At.js documentation and source code: The official documentation and source code repository may contain useful information and examples to resolve specific issues. Look for relevant discussions or reported bugs on platforms like GitHub.
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:
Network Requests: When fetching data from a remote source, handle network errors gracefully. Display user-friendly messages (e.g., “Failed to load suggestions”) instead of letting the application crash.
Data Validation: Validate the data received from the data source to ensure it meets the expected format before using it in At.js.
Callback Functions: Include try...catch
blocks within custom callback functions to prevent errors within these functions from crashing the entire application. Log errors encountered in these functions for later debugging.
Global Error Handling: Consider implementing a global error handler (using window.onerror
or a similar mechanism) to capture any unhandled exceptions that might occur within At.js or related code. This provides a safety net to catch unexpected errors.
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.
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.
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');
.innerHTML += `<span class="mention" data-user-id="${mention.id}">@${mention.username}</span> `;
message
}
}; })
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.
For complex systems, consider these enhancements:
Multiple Mention Types: Extend At.js to support mentions of different types (e.g., users, channels, hashtags) by adjusting the data structure and tpl
function.
Mention Filtering: Use the filter
configuration option to create sophisticated filtering logic based on user input or other application-specific criteria.
Real-time Updates: Integrate with real-time data sources (e.g., WebSockets) to provide instant updates to the suggestion list as users type, reflecting changes in the available mentions.
Custom UI: Instead of relying on the default suggestion list, integrate with a custom UI framework to create a more visually appealing or application-specific suggestion display.
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.