FreeDatas2HTML/src/SortingField.ts

76 lines
2.7 KiB
TypeScript

const { compare }=require('natural-orderby');
const errors=require("./errors.js");
import { SortingFields } from "./interfaces";
import { FreeDatas2HTML } from "./FreeDatas2HTML";
export class SortingField implements SortingFields
{
_converter: FreeDatas2HTML;
_fieldsDOMSelector: string;
_datasFieldNb: number;
_order: "asc"|"desc"|undefined=undefined;
// Injection de la classe principale, mais uniquement si les noms des champs ont été importés et affichés correctement.
// Attention le numéro de champ concerne les champs effectivement affichés et non ceux issus du parseur.
constructor(converter: FreeDatas2HTML, datasFieldNb: number, fieldsDOMSelector: string="th")
{
if(converter.fields.length === 0)
throw new Error(errors.sortingFieldNeedDatas);
else if(! converter.checkField2Rend(datasFieldNb))
throw new Error(errors.sortingFieldNotFound);
else
{
const fields=document.querySelectorAll(fieldsDOMSelector);
if(fields === undefined)
throw new Error(errors.sortingFieldsNotInHTML);
else if(fields.length !== converter.realFields2Rend().length)
throw new Error(errors.sortingFieldsNbFail);
else
{
this._converter=converter;
this._datasFieldNb=datasFieldNb;
this._fieldsDOMSelector=fieldsDOMSelector;
}
}
}
get converter() : FreeDatas2HTML
{
return this._converter;
}
get fieldsDOMSelector() : string
{
return this._fieldsDOMSelector;
}
get datasFieldNb() : number
{
return this._datasFieldNb;
}
get order() : "asc"|"desc"|undefined
{
return this._order;
}
public field2HTML() : void
{
const fields=document.querySelectorAll(this._fieldsDOMSelector);
let htmlContent=fields[this._datasFieldNb].innerHTML;
htmlContent="<a href='#freeDatas2HTMLSorting"+this._datasFieldNb+"' id='freeDatas2HTMLSorting"+this._datasFieldNb+"'>"+htmlContent+"</a>";
fields[this._datasFieldNb].innerHTML=htmlContent;
const sortingElement=document.getElementById("freeDatas2HTMLSorting"+this._datasFieldNb), field=this;
sortingElement!.addEventListener("click", function(e) // "!" car je sais que sortingElement existe, puisque je viens de le créer !
{
e.preventDefault();
let order=field._order ;
if(order === undefined || order === "desc")
field._order="asc";
else
field._order="desc";
field._converter.datasSortedField=field;
field._converter.refreshView();
});
}
}