2018-11-13 17:25:59 +08:00
import server from "./server.js" ;
/ * *
* @ param $el - element on which to init autocomplete
2018-11-13 17:42:55 +08:00
* @ param attributeType - "relation" or "label" or callback providing one of those values as a type of autocompleted attributes
2018-11-13 17:25:59 +08:00
* @ param open - should the autocomplete be opened after init ?
* /
2018-11-13 17:42:55 +08:00
function initAttributeNameAutocomplete ( { $el , attributeType , open } ) {
2018-11-13 17:25:59 +08:00
if ( ! $el . hasClass ( "aa-input" ) ) {
$el . autocomplete ( {
appendTo : document . querySelector ( 'body' ) ,
hint : false ,
openOnFocus : true ,
2018-11-27 20:13:06 +08:00
minLength : 0 ,
tabAutocomplete : false
2018-11-13 17:25:59 +08:00
} , [ {
displayKey : 'name' ,
2018-11-20 05:17:08 +08:00
// disabling cache is important here because otherwise cache can stay intact when switching between attribute type which will lead to autocomplete displaying attribute names for incorrect attribute type
cache : false ,
2018-11-13 17:25:59 +08:00
source : async ( term , cb ) => {
2018-11-13 17:42:55 +08:00
const type = typeof attributeType === "function" ? attributeType ( ) : attributeType ;
const names = await server . get ( ` attributes/names/?type= ${ type } &query= ${ encodeURIComponent ( term ) } ` ) ;
2020-02-29 05:07:08 +08:00
const result = names . map ( name => ( { name } ) ) ;
2018-11-13 17:25:59 +08:00
cb ( result ) ;
}
} ] ) ;
}
if ( open ) {
$el . autocomplete ( "open" ) ;
}
}
async function initLabelValueAutocomplete ( { $el , open } ) {
if ( ! $el . hasClass ( "aa-input" ) ) {
const attributeName = $el . parent ( ) . parent ( ) . find ( '.attribute-name' ) . val ( ) ;
if ( attributeName . trim ( ) === "" ) {
return ;
}
const attributeValues = ( await server . get ( 'attributes/values/' + encodeURIComponent ( attributeName ) ) )
2020-02-29 05:07:08 +08:00
. map ( attribute => ( { value : attribute } ) ) ;
2018-11-13 17:25:59 +08:00
if ( attributeValues . length === 0 ) {
return ;
}
$el . autocomplete ( {
appendTo : document . querySelector ( 'body' ) ,
hint : false ,
openOnFocus : true ,
2018-11-27 20:13:06 +08:00
minLength : 0 ,
tabAutocomplete : false
2018-11-13 17:25:59 +08:00
} , [ {
displayKey : 'value' ,
source : function ( term , cb ) {
term = term . toLowerCase ( ) ;
const filtered = attributeValues . filter ( attr => attr . value . toLowerCase ( ) . includes ( term ) ) ;
cb ( filtered ) ;
}
} ] ) ;
}
if ( open ) {
$el . autocomplete ( "open" ) ;
}
}
export default {
initAttributeNameAutocomplete ,
initLabelValueAutocomplete
}