Giter Club home page Giter Club logo

digitalfortress-tech / typeahead-standalone Goto Github PK

View Code? Open in Web Editor NEW
24.0 4.0 6.0 3.83 MB

A fast fully-featured standalone autocomplete library

Home Page: https://typeahead.digitalfortress.tech/

License: MIT License

JavaScript 74.03% Makefile 0.47% TypeScript 24.80% Less 0.69%
typeahead autocomplete autocomplete-suggestions autosuggest twitter-type twitter-typeahead search search-input searchbox select suggestions typeahead-standalone

typeahead-standalone's Introduction

Typeahead-standalone.js

npm version Build Status code style CDN Hits Downloads maintained License speed blazing Donate


A fast fully-featured standalone autocomplete library

๐ŸŒŸ Highlights ๐ŸŒŸ

  • ๐Ÿš€ Blazing fast suggestions and autocompletion
  • ๐Ÿ“ฆ Has 0 DEPENDENCIES! Written in pure JS (typescript)
  • ๐ŸŽ€ Framework agnostic! Usable with any framework (React, Vue, Svelte, etc)
  • ๐Ÿ’ก Highly customizable and light-weight <5kb minzipped
  • โšœ๏ธ In-built support for multiple data sources - Local, Prefetch and Remote (requests rate-limited by default)
  • โšก๏ธ Suggestions calculated via a very efficient algorithm based on trie data structure
  • โ™ฟ๏ธ WAI-ARIA compliant design pattern with support for language diacritics
  • ๐ŸŒ Supports every major browser!

๐Ÿ”ฅ Demo/Docs

Find here detailed Docs with Live Demos for typeahead-standalone.js.

Preview of a basic example:

Basic example

# you can install typeahead with npm
$ npm install --save typeahead-standalone

# Alternatively you can use Yarn
$ yarn add typeahead-standalone

Then include the library in your App/Page.

As a module,

// using ES6 modules
import typeahead from 'typeahead-standalone'; // imports library (js)
import 'typeahead-standalone/dist/basic.css'; // imports basic styles (css)

// using CommonJS modules
const typeahead = require('typeahead-standalone');
require('typeahead-standalone/dist/basic.css');

In the browser context,

<!-- Include the basic styles & the library -->
<link rel="stylesheet" href="./node_modules/typeahead-standalone/dist/basic.css" />
<script src="./node_modules/typeahead-standalone/dist/typeahead-standalone.umd.js"></script>

<!-- Alternatively, you can use a CDN. For example, use jsdelivr to get the latest version -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeahead-standalone/dist/basic.css" />
<script src="https://cdn.jsdelivr.net/npm/typeahead-standalone"></script>

<!-- or use unpkg.com to get a specific version -->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/basic.css" />
<script src="https://unpkg.com/[email protected]/dist/typeahead-standalone.umd.js"></script>

The library will be available as a global object at window.typeahead

๐ŸŒฑ Usage

Typeahead requires an input Element to attach itself to, and a Data source (local/remote) to display suggestions.

Here is a very basic example (See demo for advanced examples)

Html

<!-- include the library -->
<script src="..." async></script>

<!-- Html markup -->
<input type="search" id="searchInput" autocomplete="off" placeholder="Search...">

Javascript

// local Data
const colors = ['Grey', 'Brown', 'Black', 'Blue'];

// input element to attach to
const inputElement = document.getElementById("searchInput");

typeahead({
    input: inputElement,
    source: {
      local: colors,
      // prefetch: {...}
      // remote: {...}
    }
});

You can pass the following config options to typeahead-standalone:

Parameter Description Default
input DOM input element must be passed with this parameter and typeahead will attach itself to this field. - (Required)
source This is the source of Data from which suggestions will be calculated. The source can be local, prefetched or retrieved from a remote endpoint. Details - (Required)
minLength Specify the minimum length, when suggestions should appear on the screen. 1
limit Specify the maximum number of suggestions that should be displayed. 5
highlight If set to true, the matched letters are highlighted in the list of suggestions. A class tt-highlight is added to facilitate styling undefined
autoSelect If set to true, pre-selects the first displayed suggestion false
hint Updates the input placeholder to be equal to the first matched suggestion. A class tt-hint is added to facilitate styling true
diacritics Flag to enable/disable language diacritics supported search (i.e. search by converting accented characters into their non-accented counterparts) undefined
className The typeahead-standalone container will have this class name (in addition to the default class typeahead-standalone) @deprecated. Will be removed in v5.0. Use classNames config option undefined
classNames: Object The classNames object can be used to set custom classes for every html element that is injected in the DOM. Details undefined
templates An object containing templates for header, footer, suggestion, group and notFound state. See templates section for clarification undefined
debounceRemote Delays execution of making Ajax requests (in milliseconds) 100
preventSubmit If your input element is used inside a form element, this flag allows to prevent the default submit action when the ENTER key is pressed. false
onSubmit(event, selectedItem?) When you want to use typeahead outside a form element, this handler can be used to process/submit the input value. Gets triggered on hitting the ENTER key. First parameter is the keyboard Event and the 2nd parameter is the selected item or undefined if no item was selected undefined
display(selectedItem, event?) => string This callback is executed when the user selects an item from the suggestions. The current suggestion/item is passed as a parameter and it must return a string which is set as the input's value. The 2nd optional parameter event is a Mouse/Keyboard event which can be used to track user interaction or for analytics. It defaults to null. Returns the string representation of the selected item

This is the source of data from which suggestions will be provided. This is the expected format of the source object.

source: {
  local: [],
  remote: {
    url: 'https://remoteapi.com/%QUERY', // OR "url: (inputQuery: string) => `https://remoteapi.com/${inputQuery}`"
    wildcard: '%QUERY',
    requestOptions: {}        // optional, default => undefined
  },
  prefetch: {
    url: 'https://remoteapi.com/load-suggestions', // OR `url: () => string`
    when: 'onFocus',          // optional, default => 'onInit'
    done: false,              // optional, default => false
    process: (items) => void, // optional, default => undefined
    requestOptions: {}        // optional, default => undefined
  },
  identifier: '...',          // optional (required when source => Object[])
  identity: (item) => string, // optional (determines uniqueness of each suggestion)
  dataTokens: ['...'],        // optional
  groupIdentifier: '...',     // optional, default => undefined
  transform: function (data) {
    // modify received data if needed & return it
    return data;
  }
}
  • Local: The local data source is used when you want to provide suggestions from a local source like a variable.
  • Prefetch: The prefetch data source is used when you want to preload suggestions from a remote endpoint in advance. You must provide the url parameter that points to the endpoint that will return suggestions. You can provide an optional when parameter which defines when the prefetch request should occur. It defaults to onInit meaning that suggestions will be preloaded as soon as typeahead gets initialized. You can set it to onFocus which will cause suggestions to be preloaded only when the user focuses the search input box. The done flag is optional & can be used to disable the prefetch request programmatically. Its default value is false. It gets set to true automatically when data is prefetched for the first time (to prevent multiple network requests). By setting done: true, the prefetch request will not occur. An example use-case to do this is when you are using localStorage to store suggestions but the localStorage already had stored suggestions previously thereby eliminating the need to prefetch data again. The process(suggestions) callback is optional. It gets executed after the prefetch request occurs. It receives the transformed suggestions as a parameter & as an example can be used to store the received suggestions in localStorage to be used later.
  • Remote: The remote data source is used when you want to interrogate a remote endpoint to fetch data.
  • Wildcard: While using the remote data source, you must set the url and the wildcard options. wildcard will be replaced with the search string while executing the request.
  • RequestOptions: The fetch API is used to query remote endpoints. You may provide an object of requestOptions to customize the outgoing request. By default the query type is GET.
  • Transform: You can provide an optional transform() function which gets called immediately after the prefetch/remote endpoint returns a response. You can modify the response before it gets processed by typeahead.
  • Identifier: An identifier is required when the data source is an array of objects. An identifier is used to identify which property of the object should be used as the text for displaying the suggestions. For example, lets say the data source is something like this:
/* Example Data source */
[
  { id: 1, color: "Yellow", colorCode: "YW" },
  { id: 2, color: "Green", colorCode: "GN", shade: "Greenish" },
  { id: 3, color: "Olive", colorCode: "OV", shade: "Greenish" },
  ...
]

Now if we wish to use the the text defined in the color property to appear as the suggestions, then the identifier must be set to color. (i.e. identifier: "color")

  • dataTokens: dataTokens: string[] is an optional property. It accepts an array of strings which represent the properties of the source object that should be added to the search index. This can be best understood with an example. Lets take the same example data source as shown above. What if you wanted to search colors by another property(colorCode) and not just by its identifier(color) ? That's exactly where dataTokens comes in. Set dataTokens: ["colorCode"]. If you now search for "YW", the suggestion "Yellow" pops up as expected.
  • groupIdentifier: If you wish to group your suggestions, set the groupIdentifier property. This is an optional property. Again, going with the same example data source as above, when you set groupIdentifier: "shade", suggestions will be grouped by the property "shade". In this example, the colors Green and Olive will appear under the group "Greenish" (shade) whereas the color Yellow will have no group.
  • identity: The identity() function is used to determine uniqueness of each suggestion. It receives the suggestion as a parameter and must return a string unique to the given suggestion. This is an optional property and it defaults to returning the identifier. However, the default value might not work everytime. For example, consider the following code -
/* Example Data source of Songs */
[
  { title: "God is Good", artist: "Don Moen" },
  { title: "God is Good", artist: "Paul Wilbur" },
  { title: "God is Good", artist: "Micheal Smith" },
  { title: "El Shaddai", artist: "Amy Grant" },
  ...
]

Lets assume the identifier is set to title. By default the identity() function uses the identifier property (i.e. the title) to determine uniqueness. So if you search for God, you will find only 1 suggestion displayed since there are 3 songs with the exact same title property. In order to show all 3 suggestions with different artists, you need to set the identity property such that it returns a unique string -

identity(item) => `${item.title}${item.artist}`;

It is highly recommended to use the identity() property to return a unique string when your data source is an array of Objects.

Checkout the Live Examples for further clarification.


๐ŸŽจ Styling (css)

Some basic styling is provided with typeahead. The UI is completely upto you and is customizable to the very pixel. You can use the following classes to add/override styles.

  • The entire html is wrapped in a container with a class typeahead-standalone.
  • The input element has a tt-input class.
  • The hint element has a tt-hint class.
  • The list of suggestions is wrapped in a container with a tt-list class. (A class tt-hide is added when no suggestions are available)
  • Each suggestion has a class tt-suggestion and if the suggestion is selected, then it has a tt-selected class additionally.
  • If the highlight config option is set to true, every highlighted text block has a tt-highlight class.
Styling upto version 3.x.x

You can add your own styles by targetting the parent selector .typeahead-standalone. For example, we can update the background color of every suggestion as seen below -

/* set background color for each suggestion */
.typeahead-standalone .tt-list .tt-suggestion {
  background-color: green;
}

To override default styling, set the config option className and use it as a selector. Lets say you set className: "my-typeahead", then to override style on hovering/selecting a suggestion, you could use:

/* override styles */
.typeahead-standalone.my-typeahead .tt-list .tt-suggestion:hover,
.typeahead-standalone.my-typeahead .tt-list .tt-suggestion.tt-selected {
 color: black;
 background-color: white;
}
Styling for version 4.x.x and above

Starting with v4.0, the JS and CSS has been separated allowing greater control over the style. The entire css can be retrieved either from the CDN or from below and be copied directly into your project allowing you to discard/override any styles as necessary.

/***** basic styles *****/
.typeahead-standalone {
  position: relative;
  text-align: left;
  color: #000;
}
.typeahead-standalone .tt-input {
  z-index: 1;
  background: transparent;
  position: relative;
}
.typeahead-standalone .tt-hint {
  position: absolute;
  left: 0;
  cursor: default;
  user-select: none;
  background: #fff;
  color: silver;
  z-index: 0;
}
.typeahead-standalone .tt-list {
  background: #fff;
  z-index: 1000;
  box-sizing: border-box;
  overflow: auto;
  border: 1px solid rgba(50, 50, 50, 0.6);
}
.typeahead-standalone .tt-list.tt-hide {
  display: none;
}
.typeahead-standalone .tt-list div[class^="tt-"] {
  padding: 0 4px;
}
.typeahead-standalone .tt-list .tt-suggestion:hover,
.typeahead-standalone .tt-list .tt-suggestion.tt-selected {
  background: #55acee;
  cursor: pointer;
}
.typeahead-standalone .tt-list .tt-suggestion .tt-highlight {
  font-weight: 900;
}
.typeahead-standalone .tt-list .tt-group {
  background: #eee;
}

You can also use templates to add a header, footer and further style each suggestion.

๐Ÿ’ซ Templates

Templates can be used to customize the rendering of the List. Their usage is completely optional. Currently, there are 7 templates available -

templates: {
  header: (resultSet) => '<h1>List of Countries</h1>', /* Rendered at the top of the dataset */
  footer: (resultSet) => '<div>See more</div>', /* Rendered at the bottom of the dataset */
  suggestion: (item, resultSet) => {   /* Used to render a single suggestion */
    return `<div class="custom-suggestion">${item.label}</div>`;
  },
  group: (groupName, resultSet) => {   /* Used to render a group */
    return `<div class="custom-group">${groupName}</div>`;
  },
  empty: (resultSet) => {   /* Rendered when the input query is empty */
    return `<div>Search for Colors...</div>`;
    // OR (to display some suggestions by default)
    return resultSet.defaultItems = [{title: "France"}, {title: "Spain"}];
  }
  loader: () => 'Loading...', /* Rendered while awaiting data from a remote source */
  notFound: (resultSet) => '<span>Nothing Found</span>', /* Rendered if no suggestions are available */
}

As seen above, each template takes a callback that must return a string which is later interpreted as HTML. The templates also receive a parameter resultSet that has a structure as shown below.

resultSet = {
  query: '...', // the input query
  items: [...], // found suggestions
  count: 0,     // the total suggestions found in the search index
  limit: 5,     // the number of suggestions to show
  container: DOMElement,  // the container DOM element
  defaultItems: [...],    // the default suggestions while using the "empty" template
}

To facilitate styling, each template is wrapped in a div element with a corresponding class. i.e.

  • header => class tt-header
  • footer => class tt-footer
  • suggestion => class tt-suggestion
  • group => class tt-group
  • loader => class tt-loader
  • empty => class tt-empty
  • notFound => class tt-notFound

The classNames configuration option simply allows you to replace the default class names as per your choice.

The default class names used within typeahead are as follows:

const classNames = {
  wrapper: '',  /* main container element */
  input: 'tt-input',
  hint: 'tt-hint',
  highlight: 'tt-highlight',
  list: 'tt-list',  /* container element for suggestions */
  hide: 'tt-hide',
  show: 'tt-show',
  selected: 'tt-selected',
  /* classes used within templates */
  header: 'tt-header',
  footer: 'tt-footer',
  loader: 'tt-loader',
  suggestion: 'tt-suggestion',
  group: 'tt-group',
  empty: 'tt-empty',
  notFound: 'tt-notFound',
};

As an example, if you want to use a different class name for the input element, you can initialize typeahead like this -

typeahead({
  input: '...',
  source: '...',
  classNames: {
    input: 'my-custom-input-class'  // this class is used instead of tt-input
  }
});

โœจ API

Resets the typeahead instance to the state it was in before any user interaction. It removes all items from the search index except those that were added via a local source. To remove absolutely all items, the function accepts an optional parameter which should be set to true. Reset() also clears cached remote requests.

const instance = typeahead({ /* options */ });
// clear search index except items added via Local source
instance.reset();

// clears entire search index
instance.reset(true);

This API is useful in situations where you need to invalidate data after a certain time has elasped.

Adds items to the search index. Intended to use after calling the reset() method. Similar to adding items via the Local source.

const instance = typeahead({ /* options */ });
instance.reset(true); // or instance.reset();
instance.addToIndex(['Blue, Baige , Black']);

Destroys the typeahead instance, clears search index, removes all event handlers and cleans up the DOM. Can be used if you wish to deactivate typeahead.

const instance = typeahead({ /* options */ });
instance.destroy();

๐Ÿ’ก Error Codes

Here is a small glossary of the possible errors codes that one may come across

Code Description
e01 Missing input DOM element
e02 Missing/Incorrect source of suggestions. You must provide atleast one of the 3 possible sources - local, prefetch or remote with the expected source format (Ref)
e03 Identifier not defined
e04 Prefetch request failed
e05 Remote request failed

๐Ÿง‘โ€๐Ÿ’ป Contribute

Interested in contributing features and fixes?

Read more on contributing.

๐Ÿ“ Changelog

See the Changelog

๐Ÿ“„ License

MIT ยฉ DigitalFortress

typeahead-standalone's People

Contributors

amritapathak89 avatar niketpathak avatar redsparr0w avatar tomhanderson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

typeahead-standalone's Issues

Typeahead import with Vite fails in production mode

Discussed in #58

Originally posted by Pfeil May 11, 2023
Hi :) (Sorry, beginner here.) I seem not to be able to use it with vite, but I am not sure what I am doing wrong. I probably have a simple vite issue, but maybe not (minimal example below). I have another webcomponent which works fine, and other dependencies in the same project also do not cause issues. So I wonder if typeahead-standalone has certain requirements? The error only occurs in production build when using it in a script tag in a HTML file (error from the example described below):

Uncaught TypeError: this is undefined
    <anonymous> typeahead-standalone.js:1
    <anonymous> typeahead-standalone.js:1
    <anonymous> typeahead-standalone.js:1
    <anonymous> typeahead-standalone.js:1
    <anonymous> typeahead-standalone.js:1
    <anonymous> some_sample-name.umd.js:370
    <anonymous> some_sample-name.umd.js:2
    <anonymous> some_sample-name.umd.js:3
typeahead-standalone.js:1:11429

Minimal example can be created like this:

  • npm create vite@latest com_mapping_input_test -- --template vanilla-ts
  • Make it a module bundle by adding a vite.config.js:
import { resolve, dirname } from "path";
import { defineConfig } from "vite";

const __dirname = dirname(__filename);

export default defineConfig({
  build: {
    sourcemap: true,
    lib: {
      entry: resolve(__dirname, "src/main.ts"),
      name: "some_sample-name",
      formats: ["es", "umd"],
      fileName: (format) => `some_sample-name.${format}.js`,
    },
    minify: false,
  },
});

  • This code in main.ts:
import typeahead from "typeahead-standalone";

function hello() {
  console.log("hello");
  typeahead;
}
  • Then create a HTML file using the result, e.g. npm run preview and then <script src="http://localhost:4173/com_mapping-service-input.umd.js"></script>

Any ideas? Thanks!

cannot keydown through defaultItems in empty resultSet

What happened?

Upon focus into the typeahead, before typing input, templates.empty displays a resultSet of defaultItems. The suggestions from these defaultItems can be clicked upon but you cannot arrow-down through the listed suggestions.

Instead, upon arrow-down, the suggestions disappear.

this behavior is displayed in the playground 1: colors option

Affected version

Latest

Reproduction URL

https://typeahead.digitalfortress.tech/#playground

How to reproduce?

  1. focus on typeahead
  2. key down arrow

Browsers

Chrome

Relevant log output

No response

Additional context

No response

Data Not being submitted on Chrome Android

What happened?

Tested on TS 4.23.0 and 4.21.0. The site given is running 4.21.0. Issue found on Brave (Android), DDG (Android), and Chrome (Android)

Issue: When there are more than 1 input forms nearby, when submitting data(press enter key), rather than data being submitted, the input field just jumps to the second form. It affects only under certain condition.

Affected version

Latest

Reproduction URL

https://urltest.pages.dev

How to reproduce?

Issue Case

  1. Visit https://urltest.pages.dev .
  2. Type Bank, select one and submit data. You could see the alert, as well as the 2nd input form displayed.
  3. Now simply click on the second form field, or somewhere outside the first input form.
  4. Go to Form1 and type bank again and click on another suggestion and submit data.

You'll notice rather than submitting data, the pointer is now on the second form.

Another Case, but with Expected Output

  1. Repeat the first 2 steps from above.
  2. Now don't click anywhere outside the first form. Repeat step 4.

Now the data is submitted, as you'd see the alert as well as the other appropriate data.

This issue does not exist on Firefox or other FF variants.

Browsers

Chrome, Brave

Relevant log output

No response

Additional context

No response

typeahead does not respect remote data source order

What happened?

When we use remote typeahead option to get an ordered dataset from the server by input value, seems that suggestions pop up randomly whenever the input text matches the value, however, it doesn't follow dataset order to check and print matches. For example, if we have a dataset of 50 titles that starts with "tr" ordered by name from the server and after typeahead shows suggestions the first match is not equal to the first record from the dataset. It may lead to retrieving results less relevant causing a bad user experience.

Affected version

v4.17.0

Reproduction URL

https://codepen.io/stevens3/pen/WNgvrMN

How to reproduce?

  1. Get a dataset with some titles ordered by the searched input value ("tr")
  2. Click on the input
  3. Type the text you are looking for, for example, "tr"
  4. The first suggestion doesn't match the first record from the dataset

Browsers

Chrome, Brave

Relevant log output

No response

Additional context

No response

Exact match with start query with not working

Expected Behavior

When user type any query text it should be option to search start with string with exact match

Current Behavior

Its try to search anywhere in the string also not search exact query string

Possible Solution

There should be option of search where we can configure like exactmatch and search start with

Steps to Reproduce (for bugs)

  1. type any word
  2. its display list which match any charecotor of list

Context

its gives the list which not match whole exact word and start with that string

Tested on:

  • Browser Name and version:
  • Operating System and version (desktop or mobile): Any

Moving instead of cloning changes order of elements in parent element

What happened?

Fixing issue#26 introduced a new bug. Appending the input to the parent element, moves it to the end of the DOM tree of the parent element. Probably insertBefore() should be used instead of appendChild() in https://github.com/digitalfortress-tech/typeahead-standalone/blob/master/src/typeahead-standalone.ts#L100

Affected version

v4.8.0

Reproduction URL

https://jsfiddle.net/57kbLsec/

How to reproduce?

note changed order of siblings in container element.

Browsers

No response

Relevant log output

No response

Additional context

No response

Arrow key does not always select an item from the list.

What happened?

When using the arrow key to select an item from the suggestions, sometimes nothing gets selected event though there are suggestions in the list. This happens only after the initial requests (caching?) for the pressed keys.

Affected version

v4.9.0

Reproduction URL

https://codepen.io/niketpathak/pen/ZExLeEw

How to reproduce?

  1. go to the link
  2. press keys: ab
  3. press key: arrow down --> first item in list gets selected
  4. press key: c
  5. press key: arrow down --> first item in list gets selected
  6. press 3 x backspace
  7. press keys: ab
  8. press key: arrow down --> first item in list gets selected
  9. press key: c
  10. press key: arrow down --> nothing gets selected from the list anymore, even though there are items in it. Also note, that the character c gets deleted. Pressing key up will select first item in the list

Browsers

No response

Relevant log output

No response

Additional context

No response

using with webpack 4.46.0

What happened?

I'm triying to use typeahead-standalone in an existing webpack 4.46.0 project and get the following error when import the lib

 error  in ./node_modules/typeahead-standalone/dist/typeahead-standalone.js

Module parse failed: Unexpected token (134:38)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|               C = e.source.identity || w,
|               x = e.onSubmit || n,
>               O = e.source.dataTokens?.constructor === Array ? e.source.dataTokens : void 0,
|               L = {},
|               N = {},

Affected version

Latest

Reproduction URL

none

How to reproduce?

  1. Use webpack 4.46
  2. Import typeahead-standalone in your proyect
  3. See the error on the console output

Browsers

Chrome

Relevant log output

ERROR  Failed to compile with 1 errors                                                                                       23:23:58
 error  in ./node_modules/typeahead-standalone/dist/typeahead-standalone.js

Module parse failed: Unexpected token (134:38)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|               C = e.source.identity || w,
|               x = e.onSubmit || n,
>               O = e.source.dataTokens?.constructor === Array ? e.source.dataTokens : void 0,
|               L = {},
|               N = {},

   844 modules

Additional context

I'm using the following ES6 modules import statement according the documentation and get error

// using ES6 modules
import typeahead from 'typeahead-standalone';

Triying to import directly from dist path also fails

import typeahead from 'typeahead-standalone/dist/typeahead-standalone';

Events attached to the input element are removed

What happened?

Events added to the input element before using typeahead() are removed because the input element is cloned. Cloning does not copy events:

https://github.com/digitalfortress-tech/typeahead-standalone/blob/master/src/typeahead-standalone.ts#L93

Events added to the input field after using the typeahead() work fine.

Solution: Use event delegation on the parent span element instead of cloning the input element?

Affected version

v4.7.0

Reproduction URL

https://jsfiddle.net/r4f0h9yn/2/

How to reproduce?

  1. Open console to see output
  2. type something in the input field
  3. console log should show 'added before' and 'added after', but only shows 'added after'

Browsers

No response

Relevant log output

No response

Additional context

No response

Access `input` within url callback for remote source

Hello,

i am migrating a formular from jquery typeahead to typeahead-standalone in order to use a remote source.
Our api needs a generated signature for a request, so replacing the wildcard after the url()-callback doesn't work in our usecase.

Is there a way to get the frozenInput within the url()-callback?
Or is there an option to use the frozenInput as payload in a post request?

Regards
.nowrap

Originally posted by @nowrap in #64

Display callback is called for every item in the suggestion list instead of only once

What happened?

The display callback gets called for every item in the suggestion list instead of only once for the selected item.

Affected version

v4.10.0

Reproduction URL

https://jsfiddle.net/9xLhbzne/

How to reproduce?

  1. type g
  2. watch console, will output all items multiple times

Browsers

No response

Relevant log output

{
  label: "Gold"
}
{
  label: "Grey"
}
{
  label: "Green"
}
{
  label: "Gold"
}
{
  label: "Gold"
}
{
  label: "Gold"
}
{
  label: "Grey"
}
{
  label: "Green"
}
{
  label: "Gold"
}

Additional context

No response

With hint: false, a tt-hint input box is still generated

What happened?

Expected behavior:
Setting hint:false in the typeahead options will not produce a tt-hint input element in the output html

Actual behavior:
A tt-hint input is created anyway, just not used for hinting

I don't want hinting, and the unused, mis-sized tt-hint input box is making a mess of my search box ui. If I go into devtools and manually delete the tt-hint input element, everything looks and works correctly.

Affected version

Latest

Reproduction URL

https://jsfiddle.net/j7xL59m8/

How to reproduce?

  1. Set hint: false in the typeahead options
  2. Notice that the tt-hint input box is still generated when the page is rendered

Browsers

Firefox, Chrome

Relevant log output

No response

Additional context

No response

typeahead-standalone wont scroll result content using bootstrap 5 offcanvas component

What happened?

using typeahead-standalone within an bootstrap 5 offcanvas component wont scroll content

Affected version

Latest

Reproduction URL

https://codepen.io/C-Alonso-C-Ortega/pen/RwOzdPK

How to reproduce?

  1. create a basic example using bs5 offcanvas component together typeahead-standalone
  2. open offcanvas
  3. write a search term
  4. get results an see that scroll doesnt happen
    note. reproduce issue using this example https://codepen.io/C-Alonso-C-Ortega/pen/RwOzdPK

Browsers

Chrome

Relevant log output

No response

Additional context

No response

Webpack build fails in 4.25.0

What happened?

Webpack results in an error in 4.25.0:

Module not found: Error: Package path ./dist/basic.css is not exported from package /home/raja/dev/typeahead-standalone-debug/node_modules/typeahead-standalone (see exports field in /home/raja/dev/typeahead-standalone-debug/node_modules/typeahead-standalone/package.json)

Affected version

v4.25.0, v4.25.1

Reproduction URL

NA -- local build

How to reproduce?

A minimal project to reproduce

  1. npm init -y
  2. npm install webpack webpack-cli typeahead-standalone css-loader style-loader --save-dev
  3. Add index.js and webpack.config.js as described below
  4. npm run build

index.js:

import typeahead from 'typeahead-standalone';
import 'typeahead-standalone/dist/basic.css';

window.typeahead=typeahead;

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  mode: 'development',
};

package.json

{
  "name": "typeahead-standalone-debug",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "css-loader": "^7.1.1",
    "style-loader": "^4.0.0",
    "typeahead-standalone": "4.25.0",
    "webpack": "^5.91.0",
    "webpack-cli": "^5.1.4"
  }
}

Browsers

No response

Relevant log output

> [email protected] build
> webpack

asset bundle.js 19.3 KiB [emitted] (name: main)
runtime modules 670 bytes 3 modules
cacheable modules 14.1 KiB
  ./src/index.js 122 bytes [built] [code generated]
  ./node_modules/typeahead-standalone/dist/typeahead-standalone.es.js 14 KiB [built] [code generated]

ERROR in ./src/index.js 2:0-45
Module not found: Error: Package path ./dist/basic.css is not exported from package /typeahead-standalone-debug/node_modules/typeahead-standalone (see exports field in /typeahead-standalone-debug/node_modules/typeahead-standalone/package.json)

webpack 5.91.0 compiled with 1 error in 162 ms

Additional context

The same process works if typeahead-standalone is fixed to 4.24.0

Conflict issue on submitting data on Firefox Mobile devices

What happened?

Tested on Firefox Mobile and Mull Browser.

Open FF mobile app(Android)

  • Visit https://url.authifyweb.com/
  • Type the the word nykaa. => 3 suggestions should appear
  • select the word Nykaa, submit.

Result:
Received different results

  • Nothing happens. the suggestions list gets closed, but nothing more.
  • The tt-input form inserts few extra letters automatically.(See attached video)
  • After submitting 3 or 4 times it works and submit the data.

Expected Output:
The word Nykaa gets selected and the a form to submit URL appears.

preventSubmit is: False

On chrome mobile it works as expected.

typeahead.error.mp4

JS code: https://github.com/authifyWeb/authifyURL/blob/main/resources/script.js
repo : https://github.com/authifyWeb/authifyURL

Affected version

Latest

Reproduction URL

https://github.com/authifyWeb/authifyURL

How to reproduce?

Open FF mobile app(Android)

  • Visit https://url.authifyweb.com/
  • Type the the word nykaa. => 3 suggestions should appear
  • select the word Nykaa, submit.

Browsers

Firefox

Relevant log output

No response

Additional context

No response

`typeahead` is not namespaced

This library is very useful for widget development where HTML is being injected into an unknown website, but the lack of namespacing of the core function threatens collisions. This library defines one global function called typeahead. I'm very concerned that should I use this library it will collide with my client's website. I'm injecting HTML directly into their pages as widgets.

So, although I do not have an example of such a collision I'm very wary about it. This is my suggested solution:

export default function digitalfortress$typeahead<T extends Dictionary>(config: typeaheadConfig<T>): typeaheadResult {

I understand such a central change to this library would necessitate a major version number and would cause a bit of documentation rewriting, but other than that I don't foresee much of a problem.

Native Input Event Not Being Triggered

What happened?

Hi there ๐Ÿ‘‹,

As of today the propagation of the native input event is currently commented as a result of a bug.

This way we are not able to react to any changes when the user selects a value from the suggestion-list. Is there already a solution how this will be handled in the future?

Affected version

Latest

Reproduction URL

https://github.com/digitalfortress-tech/typeahead-standalone/blob/70668092359607fee5cbebdde1e59bf94a2b8bc6/src/typeahead-standalone.ts#LL345C1-L346C1

How to reproduce?

  1. Attach an input event handler to the input field
  2. Type a prefix of a value and select a value from the suggestion list

Browsers

Chrome

Relevant log output

No response

Additional context

No response

error using with typescript

What happened?

using with typescript throw the following error:

Error: node_modules/typeahead-standalone/dist/index.d.cts:23:32 - error TS2304: Cannot find name 'Dictionary'.

23   function typeahead<T extends Dictionary>(config: typeaheadConfig<T>): typeaheadResult<T>;
                                  ~~~~~~~~~~


Error: node_modules/typeahead-standalone/dist/index.d.cts:23:52 - error TS2304: Cannot find name 'typeaheadConfig'.

23   function typeahead<T extends Dictionary>(config: typeaheadConfig<T>): typeaheadResult<T>;
                                                      ~~~~~~~~~~~~~~~


Error: node_modules/typeahead-standalone/dist/index.d.cts:23:73 - error TS2304: Cannot find name 'typeaheadResult'.

23   function typeahead<T extends Dictionary>(config: typeaheadConfig<T>): typeaheadResult<T>;
                                                                           ~~~~~~~~~~~~~~~


Error: node_modules/typeahead-standalone/dist/index.d.cts:24:3 - error TS2666: Exports and export assignments are not permitted in module augmentations.

24   export default typeahead;

Affected version

v4.25.1

Reproduction URL

none

How to reproduce?

  1. Use in a project with typescript
  2. Install lastest version
  3. try run project
Captura de pantalla 2024-04-30 a la(s) 22 32 48

Browsers

Chrome

Relevant log output

No response

Additional context

No response

Error when using vite in production

What happened?

Using vite v4.3.7 with vue 3.3.4. Latest version of typeahead-standalone.

Inserted the colors example into my page. Works great in dev mode but as soon as I build using vite and run in production I get this error --

Uncaught TypeError: Cannot read properties of undefined (reading 'webpackChunktypeahead')
at index-e65366ba.js:2156:108666
at index-e65366ba.js:2156:108754
at index-e65366ba.js:2156:108817
at index-e65366ba.js:2156:96746
at index-e65366ba.js:2156:96751
at index-e65366ba.js:2156:108822

Affected version

Latest

Reproduction URL

none

How to reproduce?

Use standard vue 3 example. Insert example code from typeahead-standalone. Run vite build. Deploy to web site.

Browsers

Chrome

Relevant log output

Uncaught TypeError: Cannot read properties of undefined (reading 'webpackChunktypeahead')
    at index-e65366ba.js:2156:108666
    at index-e65366ba.js:2156:108754
    at index-e65366ba.js:2156:108817
    at index-e65366ba.js:2156:96746
    at index-e65366ba.js:2156:96751
    at index-e65366ba.js:2156:108822

Additional context

No response

Not displaying suggestions within Bootstrap offcanvas on Firefox

What happened?

The component is not displayed into Firefox browser (lastest)

image

In Chrome is working well

image

Affected version

Latest

Reproduction URL

none

How to reproduce?

Use the component into Firefox browser

Browsers

Firefox

Relevant log output

No errors

Additional context

In my case the workaround is set position: unset; into .tt-list element

image

Generated HTML is not valid

What happened?

The HTML generated by the javascript is not valid. A span tag is created to wrap the original input element, a hint input is added, and then a div tag is also added into that span. It is not valid HTML to have a div tag inside a span.

Additionally, the readonly attribute is added to the hint input with the value of "true". The readonly attribute is a boolean value, but the string value of "true" is not a boolean. Boolean attributes should be set with no value at all.

On a side note, I have noticed that on pages that use Bootstrap the hidden input initially appears offset from the original input. A quick fix is to add the style "display: block" to the wrapping span (which would be needed if this were a div anyway).

One final note. The attributes of the original input are copied to the added hint input. The id attribute is not copied which is good, but if the original input has an aria-label that is copied. That attribute should not be copied.

Affected version

v4.18.0

Reproduction URL

https://codepen.io/niketpathak/pen/eYVdGNY

How to reproduce?

  1. Use this javascript library in any browser.
  2. Add bootstrap to the page.
  3. Put an aria-label on the original input.

Browsers

Firefox, Chrome

Relevant log output

No response

Additional context

The codepen is just your default codepen. I don't see the need to create a custom codepen for this. I think the issues are pretty clear as is.

onSubmit option, conflict issue when content is filled using mouse

What happened?

I haven't added anything new other than adding a onSubmit option to your existing code of accessing twitter data. onSubmit option for mouseclick and keystroke have different results.

Affected version

Latest

Reproduction URL

https://codepen.io/webVerts/pen/vYjNEGm

How to reproduce?

Go to the link.
Type in your name and complete the suggestion using mouse click and click enter.
An alert appears and click ok.
Open console log. You'll notice "SometihngSomething" messagge

Now go back and type your name again, this time complete autofilling using keystroke and click enter.
Alert appears, click ok.
Open console log. You can find the stringified data from twitter there, which wasn't available when using mouse.

Browsers

Brave

Relevant log output

No response

Additional context

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.