New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More ā†’
Socket
Sign inDemoInstall
Socket

@yaireo/tagify

Package Overview
Dependencies
Maintainers
1
Versions
270
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@yaireo/tagify

lightweight, efficient Tags input component in Vanilla JS / React / Angular [super customizable, tiny size & top performance]

  • 3.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
86K
decreased by-5.5%
Maintainers
1
Weekly downloads
Ā 
Created
Source



Tagify - lightweight input "tags" script

Transforms an input field or a textarea into a Tags Componen, in an easy, customizable way, with great performance and tiny code footprint, exploded with features.
Vanilla āš” React āš” Angular

šŸ‘‰ See Demos šŸ‘ˆ

See Demos

Table of Contents

Installation

npm i @yaireo/tagify --save

usage (in your bundle):

import Tagify from '@yaireo/tagify'

var tagify = new Tagify(...)

Don't forget to include tagify.css file in your project. CSS location: @yaireo/tagify/dist/tagify.css SCSS location: @yaireo/tagify/src/tagify.scss See SCSS usecase & example

Selling points

  • JS minified ~30kb (~9kb GZIP)
  • CSS minified ~8kb (~2kb GZIP) - generated from SCSS with variables
  • Easily customized, plenty of settings for common scenarios
  • Your input/textarea node values kept in sync with Tagify
  • ARIA accessibility support
  • Many useful custom events
  • Easily change direction to RTL (via the SCSS file)
  • Internet Explorer - A polyfill script can be used: tagify.polyfills.min.js in /dist

What can Tagify do

  • Can be applied on input & textarea elements
  • Supports mix content (text and tags together)
  • Supports single-value mode (like <select>)
  • Supports whitelist
  • Supports blacklists
  • Supports Templates for customized markup: wrapper, tag item & suggestion item
  • Shows suggestions selectbox (flexiable settings & styling) at full width or next to the typed texted (caret)
  • Allows setting suggestions' aliases for easier fuzzy-searching
  • Auto-suggest input as-you-type with ability to auto-complete
  • Can paste in multiple values: tag 1, tag 2, tag 3 or even newline-separated tags
  • Tags can be created by Regex delimiter or by pressing the "Enter" key / focusing of the input
  • Validate tags by Regex pattern
  • Tags are editable
  • Supports read-only mode to the whole componenet or per-tag
  • Each tag can have any properties desired (class, data-whatever, readonly...)
  • Automatically disallow duplicate tags (vis "settings" object)
  • Has built-in CSS loader, if needed (Ex. AJAX whitelist pulling)
  • Tags can be trimmed via hellip by giving max-width to the tag element in your CSS

Building the project

Simply run gulp in your terminal, from the project's path (Gulp should be installed first).

Source files are this path: /src/

Output files, which are automatically generated using Gulp, are in: /dist/

The rest of the files are most likely irrelevant.

Adding tags dynamically

var tagify = new Tagify(...);

tagify.addTags(["banana", "orange", "apple"])

// or add tags with pre-defined propeties

tagify.addTags([{value:"banana", color:"yellow"}, {value:"apple", color:"red"}, {value:"watermelon", color:"green"}])

output value

There are two possible ways to get the value of the tags:

  1. Access the tagify's instance's value prop: tagify.value (Array of tags)
  2. Access the original input's value: inputElm.value (Stringified Array of tags)

Ajax whitelist

Dynamically-loaded suggestions list (whitelist) from the server (as the user types) is a frequent need to many.

Tagify comes with its own loading animation, which is a very lightweight CSS-only code, and the loading state is controlled by the method tagify.loading which accepts true or false as arguments.

Below is a basic example using the fetch API. I advise to abort the last request on any input before starting a new request.

var input = document.querySelector('input'),
    tagify = new Tagify(input, {whitelist:[]}),
    controller; // for aborting the call

// listen to any keystrokes which modify tagify's input
tagify.on('input', onInput)

function onInput( e ){
  var value = e.detail.value;
  tagify.settings.whitelist.length = 0; // reset the whitelist

  // https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort
  controller && controller.abort();
  controller = new AbortController();

  // show loading animation and hide the suggestions dropdown
  tagify.loading(true).dropdown.hide.call(tagify)

  fetch('http://get_suggestions.com?value=' + value, {signal:controller.signal})
    .then(RES => RES.json())
    .then(function(whitelist){
      // update inwhitelist Array in-place
      tagify.settings.whitelist.splice(0, whitelist.length, ...whitelist)
      tagify.loading(false).dropdown.show.call(tagify, value); // render the suggestions dropdown
    })
}

Edit tags

Tags which aren't read-only can be edited by double-clicking them.

The value is saved on blur or by pressing enter key. Pressing Escape will revert the change trigger blur. ctrlz will revert the change if an edited tag was marked as not valid (perhaps duplicate or blacklisted)

DOM Templates

It's possible to control the templates for the following HTML elements tagify generates by modying the settings.templates Object with your own custom functions which should output a string.

The defaults are:

templates : {
    wrapper(input, settings){
        return `<tags class="tagify ${settings.mode ? "tagify--mix" : "" } ${input.className}" ${settings.readonly ? 'readonly' : ''}>
            <span contenteditable data-placeholder="${input.placeholder || '&#8203;'}" class="tagify__input"></span>
        </tags>`
    },

    tag(v, tagData){
        return `<tag title='${v}' contenteditable='false' spellcheck="false" class='tagify__tag ${tagData.class ? tagData.class : ""}' ${this.getAttributes(tagData)}>
            <x title='' class='tagify__tag__removeBtn'></x><div><span class='tagify__tag-text'>${v}</span></div>
        </tag>`
    },

    dropdownItem( item ){
        var sanitizedValue = (item.value || item).replace(/`|'/g, "&#39;");
        return `<div ${this.getAttributes(item)} class='tagify__dropdown__item ${item.class ? item.class : ""}'>${sanitizedValue}</div>`;
    }
}

Suggestions selectbox

The suggestions selectbox is shown is a whitelist Array of Strings or Objects was passed in the settings when the Tagify instance was created. Suggestions list will only be rendered if there are at least two matching sugegstions (case-insensetive).

The selectbox dropdown will be appended to the document's <body> element and will be rendered by default in a position below (bottom of) the Tagify element. Using the keyboard arrows up/down will highlight an option from the list, and hitting the Enter key to select.

It is possible to tweak the selectbox dropdown via 2 settings:

  • enabled - this is a numeral value which tells Tagify when to show the suggestions dropdown, when a minimum of N characters were typed.
  • maxItems - Limits the number of items the suggestions selectbox will render
var input = document.querySelector('input'),
    tagify = new Tagify(input, {
        whitelist : ['aaa', 'aaab', 'aaabb', 'aaabc', 'aaabd', 'aaabe', 'aaac', 'aaacc'],
        dropdown : {
            classname : "color-blue",
            enabled   : 3,
            maxItems  : 5
        }
    });

Will render:

<div class="tagify__dropdown" style="left: 993.5px; top: 106.375px; width: 616px;">
    <div class="tagify__dropdown__item" value="aaab">aaab</div>
    <div class="tagify__dropdown__item" value="aaabb">aaabb</div>
    <div class="tagify__dropdown__item" value="aaabc">aaabc</div>
    <div class="tagify__dropdown__item" value="aaabd">aaabd</div>
    <div class="tagify__dropdown__item" value="aaabe">aaabe</div>
</div>

By default searching the suggestions is using fuzzy-search (see settings).

If you wish to assign alias to items (in your suggestion list), add the searchBy property to whitelist items you wish to have an alias for. In the blow example, when typing any of the words from the searchBy property, the suggestion listen will match "Israel".

Example for a suggestion item alias

whitelist = [
    ...
    { value:'Israel', code:'IL', searchBy:'holy land, desert, middle east' },
    ...
]

mixed-content

To use this feature it must be toggled - see settings.

When mixing text with tags, the original textarea (or input) element will have a value as follows:

[[cartman]]ā  and [[kyle]]ā  do not know [[Homer simpson]]ā 

If the inital value of the textarea or input is formatted as the above example, tagify will try to automatically convert everything between [[ & ]] to a tag, if tag exists in the whitelist, so make sure when the Tagify instance is initialized, that it has tags with the correct value property that match the same values that appear between [[ & ]].

Applying the setting dropdown.position:"text" is encouraged for mixed-content tags, because the suggestions list will be rendered right next to the caret location and not the the bottom of the Tagify componenet, which might look weird when there is already a lot of content at multiple lines.

single-value

Similar to native <Select> element, but allows typing free text as value.

React

A Tagify React component is exported as <Tags> from react.tagify.js:

Check the live demo for a live React integration example

Angular

TagifyComponent which will be used by your template as <tagify>

Example:

<div>
  testing tagify wrapper
  <tagify [settings]="settings"
          (add)="onAdd($event)"
          (remove)="onRemove($event)">
  </tagify>
  <button (click)="clearTags()">clear</button>
  <button (click)="addTags()">add Tags</button>
</div>

TagifyService

(The tagifyService is a singletone injected by angular, do not create a new instance of it)

import {Component, OnDestroy} from '@angular/core';
import {TagifyService} from '@yaireo/tagify';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnDestroy {

  constructor(private tagifyService: TagifyService) {}
  public settings = { blacklist: ['fucking', 'shit']};

  onAdd(tagify) {
    console.log('added a tag', tagify);
  }

  onRemove(tags) {
    console.log('removed a tag', tags);
  }
  clearTags() {
    this.tagifyService.removeAll();
  }
  addTags() {
    this.tagifyService.addTags(['this', 'is', 'cool']);
  }
  ngOnDestroy() {
    this.tagifyService.destroy();
  }
}

Remember to add TagifyService to your module definition.

jQuery version

jQuery.tagify.js

A jQuery wrapper verison is also available, but I advise not using it because it's basically the exact same as the "normal" script (non-jqueryfied) and all the jQuery's wrapper does is allowing to chain the event listeners for ('add', 'remove', 'invalid')

$('[name=tags]')
    .tagify()
    .on('add', function(e, tagName){
        console.log('added', tagName)
    });

Accessing methods can be done via the .data('tagify'):

$('[name=tags]').tagify();
// get tags from the server (ajax) and add them:
$('[name=tags]').data('tagify').addTags('aaa, bbb, ccc')

FAQ

To render all the tags at the same line, without tags wrapping to new lines, add this to your .tagify CSS:

flex-wrap: nowrap;

CSS Variables (see MDN docs)

These CSS variables allow easy customization without the need to manually write CSS. If you do wish to heavily style your Tagify components, then you can use these variables within your modified styles.

For example how this can be used, see the demos page.

NameInfo
--tags-border-colorThe outer border color which surrounds tagify
--tag-bgTag background color
--tag-hoverTag background color on hover (mouse)
--tag-text-colorTag text color
--tag-text-color--editTag text color when a Tag is being edited
--tag-padTag padding, from all sides. Ex. .3em .5em
--tag--min-widthMinimum Tag width
--tag--max-widthMaximum tag width, which gets trimmed with hellip after
--tag-inset-shadow-sizeThis is the inner shadow size, which dictates the color of the Tags. It's important the size fits exactly to the tag. Change this if you change the --tag-pad or fontsize.
--tag-invalid-colorFor border color of edited tags with invalid value being typed into them
--tag-invalid-bgBackground color for invalid Tags.
--tag-remove-bgTag background color when hovering the Ɨ button.
--tag-remove-btn-bgThe remove (Ɨ) button background color
--tag-remove-btn-bg--hoverThe remove (Ɨ) button background color on hover
--loader-sizeLoading animation size. 1em is pretty big, default is a bit less.

Methods

NameParametersInfo
destroyReverts the input element back as it was before Tagify was applied
removeAllTagsRemoves all tags and resets the original input tag's value property
addTagstagsItems, clearInput, skipInvalidAccepts a String (word, single or multiple with a delimiter), an Array of Objects (see above) or Strings
removeTagNode/StringRemoves a specific tag. Argument is the tag DOM element to be removed, or value. When nothing passed, removes last tag (see source code)
loadOriginalValuesString/ArrayConverts the input's value into tags. This method gets called automatically when instansiating Tagify. Also works for mixed-tags
getTagIndexByValueStringReturns the index of a specific tag, by value
parseMixTagsStringConverts a String argument ([[foo]]ā  and [[bar]]ā  are..) into HTML with mixed tags & texts
getTagElmsReturns a DOM nodes list of all the tags
getTagElmByValueStringReturns a specific tag DOM node by value
editTagNodeGoes to edit-mode in a specific tag
replaceTagtagElm, tagDataExit a tag's edit-mode. if "tagData" exists, replace the tag element with new data and update Tagify value
loadingBooleanToogle loading state on/off (Ex. AJAX whitelist pulling)

Events

all triggered events return the instance's scope (tagify)

NameInfo
addA tag has been added
removeA tag has been removed
invalidA tag has been added but did not pass vaildation. See event detail
inputInput event, when a tag is being typed/edited. e.detail exposes value, inputElm & isValid
clickClicking a tag. Exposes the tag element, its index & data
keydownWhen tagify input has focus and a key was pressed
focusThe component currently has focus
blurThe component lost focus
edit:inputTyping inside an edited tag
edit:updatedA tag as been updated (changed view editing or by directly calling the replaceTag() method)
edit:startA tag is now in "edit mode"
edit:keydownkeydown event while an edited tag is in focus
dropdown:showSuggestions dropdown is to be rendered. The dropdown DOM node is passed in the callback, see demo.
dropdown:hideSuggestions dropdown has been removed from the DOM
dropdown:selectSuggestions dropdown item selected (by mouse/keyboard/touch)

Settings

NameTypeDefaultInfo
placeholderStringPlaceholder text. If this attribute is set on an input/textarea element it will override this setting
delimitersString,[regex string] split tags by any of these delimiters. Example: `",
patternStringnullValidate input by REGEX pattern (can also be applied on the input itself as an attribute) Ex: /[1-9]/
modeStringnullUse select for single-value dropdown-like select box. See mix as value to allow mixed-content. The 'pattern' setting must be set to some character.
mixTagsInterpolatorArray['[[', ']]']Interpolation for mix mode. Everything between these will become a tag
mixTagsAllowedAfterRegex`/,.
duplicatesBooleanfalseShould duplicate tags be allowed or not
enforceWhitelistBooleanfalseShould ONLY use tags allowed in whitelist
autocomplete.enabledBooleantrueTries to suggest the input's value while typing (match from whitelist) by adding the rest of term as grayed-out text
autocomplete.rightKeyBooleanfalseIf true, when ā†’ is pressed, use the suggested value to create a tag, else just auto-completes the input. In mixed-mode this is ignored and treated as "true"
whitelistArray[]An array of tags which only they are allowed
blacklistArray[]An array of tags which aren't allowed
addTagOnBlurBooleantrueAutomatically adds the text which was inputed as a tag when blur event happens
callbacksObject{}Exposed callbacks object to be triggered on events: 'add' / 'remove' tags
maxTagsNumberInfinityMaximum number of allowed tags. when reached, adds a class "hasMaxTags" to <Tags>
editTagsNumber2Number of clicks on a tag to enter "edit" mode. Other values than 1 or 2 are not allowed
templatesObjectwrapper, tag, dropdownItemObject consisting of functions which return template strings
transformTagFunctionundefinedTakes a tag input as argument and returns a transformed value
keepInvalidTagsBooleanfalseIf true, do not remove tags which did not pass validation
skipInvalidBooleanfalseIf true, do not add invalid, temporary, tags before automatically removing them
backspace*trueOn pressing backspace key:
true - remove last tag
edit - edit last tag
dropdown.enabledNumber2Minimum characters to input to show the suggestions list. "false" to disable
dropdown.maxItemsNumber10Maximum items to show in the suggestions list dropdown
dropdown.classnameString""Custom class name for the dropdown suggestions selectbox
dropdown.itemTemplateFunction""Returns a custom string for each list item in the dropdown suggestions selectbox
dropdown.fuzzySearchBooleantrueEnables filtering dropdown items values' by string containing and not only beginning
dropdown.positionStringnullmanual - will not render the dropdown, and you would need to do it yourself. See "events" section.
text - will place the dropdown next to the caret
all - normal, full-width design
dropdown.highlightFirstBooleanfalseWhen a suggestions list is shown, highilght the first item, and also suggest it in the input (The suggestion can be accepted with ā†’ key)
dropdown.closeOnSelectBooleanfalseclose the dropdown after selecting an item, if enabled:0 is set (which means always show dropdown on focus)

FAQs

Package last updated on 12 Dec 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with āš”ļø by Socket Inc