FreeDatas2HTML/src/freeDatas2HTMLSortingField.ts

77 lines
2.9 KiB
TypeScript
Raw Normal View History

const { compare }=require('natural-orderby');
const errors=require("./errors.js");
import { SortingFields } from "./freeDatas2HTMLInterfaces";
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 le nom des champs ont été importés et affichés correctement
constructor(converter: FreeDatas2HTML, datasFieldNb: number, fieldsDOMSelector: string="th")
{
if(converter.fields === undefined)
throw new Error(errors.sortingFieldNeedDatas);
else if(! converter.checkFieldExist(Number(datasFieldNb)))
throw new Error(errors.sortingFieldFieldNotFound);
else
{
const fields=document.querySelectorAll(fieldsDOMSelector);
if(fields === undefined)
throw new Error(errors.sortingFieldsNotInHTML);
else if(fields.length !== converter.fields.length)
throw new Error(errors.sortingFieldsNbFail);
else
{
this._converter=converter;
this._datasFieldNb=datasFieldNb;
this._fieldsDOMSelector=fieldsDOMSelector;
}
}
}
get fieldsDOMSelector() : string
{
return this._fieldsDOMSelector;
}
get datasFieldNb() : number
{
return this._datasFieldNb;
}
get order() : "asc"|"desc"|undefined
{
return this._order;
}
// Création du lien dans le HTML correspondant au champ de classement
public field2HTML() : void
{
if(this._converter === undefined || this._fieldsDOMSelector === "" || this._datasFieldNb === undefined)
throw new Error(errors.sortingField2HTMLFail);
else
{
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) // je sais que sortingElement existe, car 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();
});
}
}
}