FreeDatas2HTML/src/freeDatas2HTMLRender.ts

65 lines
2.8 KiB
TypeScript

const errors = require("./errors.js");
import { DatasRenders, DatasRendersSettings } from "./freeDatas2HTMLInterfaces";
import { FreeDatas2HTML } from "./freeDatas2HTML";
export class Render implements DatasRenders
{
private _converter: FreeDatas2HTML;
public settings: DatasRendersSettings;
static readonly defaultSettings =
{
allBegining:"<table>",
allEnding:"</table>",
fieldsBegining:"<thead><tr>",
fieldsEnding:"</tr></thead>",
fieldDisplaying:"<th>#FIELDNAME</th>",
linesBegining:"<tbody>",
linesEnding:"</tbody>",
lineBegining:"<tr>",
lineEnding:"</tr>",
dataDisplaying:"<td>#VALUE</td>",
};
// Injection de la classe principale
constructor(converter: FreeDatas2HTML, settings:DatasRendersSettings=Render.defaultSettings)
{
this._converter=converter;
this.settings=settings;
}
// Reçoit les données à afficher et retourne le HTML correspondant.
public rend2HTML(datas: any[]) : string
{
// Il peut n'y avoir aucune donnée (filtres...), mais les noms des champs doivent être connus.
if(this._converter.parseMetas === undefined || this._converter.parseMetas.fields === undefined)
throw new Error(errors.renderNeedDatas);
else
{
let datasHTML=this.settings.allBegining;
// On ne souhaite pas nécessairement afficher les noms des champs
if(this.settings.fieldsBegining !== undefined && this.settings.fieldDisplaying !== undefined && this.settings.fieldsEnding !== undefined )
{
datasHTML+=this.settings.fieldsBegining;
for (let i in this._converter.parseMetas.fields)
datasHTML+=this.settings.fieldDisplaying.replace("#FIELDNAME", this._converter.parseMetas.fields[Number(i)]);
datasHTML+=this.settings.fieldsEnding;
}
datasHTML+=this.settings.linesBegining;
for (let row in datas)
{
datasHTML+=this.settings.lineBegining;
for(let field in datas[row])
{
// On n'affiche que les champs attendus et signale les erreurs dans la console
if(this._converter.parseMetas.fields.indexOf(field) !== -1)
datasHTML+=this.settings.dataDisplaying.replace("#VALUE" , datas[row][field]).replace("#FIELDNAME" , field);
else
console.log(errors.renderUnknownField+field);
}
datasHTML+=this.settings.lineEnding;
}
datasHTML+=this.settings.linesEnding+this.settings.allEnding;
return datasHTML;
}
}
}