bitfront-library
Version:
Angular CLI project with components and classes used by other Angular projects of the BIT foundation.
323 lines • 16.9 kB
JavaScript
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseFormComponent = void 0;
var core_1 = require("@angular/core");
var router_1 = require("@angular/router");
var rxjs_1 = require("rxjs");
var base_component_1 = require("./base.component");
var global_constants_1 = require("../../shared/global.constants");
var bit_toolbar_component_1 = require("../../shared/component/bit-toolbar.component");
var bitmessage_1 = require("../../shared/data/bitmessage");
var error_1 = require("../../shared/data/error");
var custom_validators_service_1 = require("../../shared/service/custom-validators.service");
var general_utils_service_1 = require("../../shared/service/general-utils.service");
var message_service_1 = require("../../shared/service/message.service");
var toolbar_service_1 = require("../../shared/service/toolbar.service");
var i0 = require("@angular/core");
var i1 = require("@angular/router");
var i2 = require("../../shared/service/message.service");
var i3 = require("../../shared/service/toolbar.service");
/**
* Clase base para implementar formularios de elementos. Provee el 95% de la funcionalidad necesaria.
*/
var BaseFormComponent = /** @class */ (function (_super) {
__extends(BaseFormComponent, _super);
/**
* Constructor de la Clase.
* @param dataService: Servicio que implementa la interface BaseCRUDServiceInterface.
* @param router: Objeto de tipo Router para poder navegar (p. ej., al listado).
* @param activateRoute: Objeto de tipo ActivatedRoute que permite acceder a los parámetros de la URL con los que
* hemos accedido a este componente o para navegar.
* @param notificationService: Objeto de tipo NotificationService para poder mostrar diálogos al usuario.
*/
function BaseFormComponent(dataService, router, activatedRoute, messageService, toolbarService, componentId) {
var _this = _super.call(this, messageService, toolbarService, componentId) || this;
_this.breadcrumb = []; // contiene la miga de pan de nuestro componente
_this.onSave = new core_1.EventEmitter(); // envía el objeto actualizado cada vez que se inserta/actualiza
_this.myTabs = {}; // pestañas definidas en el componente (ver registerTab() e initTabs())
_this.loadedTab = {}; // pestañas con datos cargados (todas se cargan de forma perezosa)
_this.dataService = dataService;
_this.router = router;
_this.activatedRoute = activatedRoute;
_this.toolbar = {
//mínimos toolbar de un formulario
save: { visible: true, enable: true },
delete: { visible: false, enable: true },
print: { visible: true, enable: true }
};
// mensajes para el footer
_this.messages = new Map();
_this.messages.set(global_constants_1.PageStatus.Init, "Premi el botó Desa per actualitzar les dades");
_this.messages.set(global_constants_1.PageStatus.Searching, "Enviant la sol·licitud...");
_this.messages.set(global_constants_1.PageStatus.FinishSearch, "Dades actualitzades satisfactòriament");
_this.messages.set(global_constants_1.PageStatus.ReadOnly, "Formulari no editable");
return _this;
}
BaseFormComponent.prototype.ngOnDestroy = function () {
_super.prototype.ngOnDestroy.call(this);
};
BaseFormComponent.prototype.ngAfterContentInit = function () {
var _this = this;
console.log("ngAfterContentInit base-form.component");
this.reset &&
this.reset.subscribe(function (x) {
_this.object = null;
_this.myForm && _this.myForm.markAsPristine(); // el formulario vuelve a estar sincronizado con el servidor
_this.myForm && _this.myForm.markAsUntouched(); // idem
_this.init();
});
this.initTabs();
};
/**
* Inicializa el formulario.
* 1. Identifica si el formulario se carga para insertar un nuevo elemento o consultar/actualizar uno existente.
* 2. En este segundo caso, lee el elemento con el identificador indicado por parámetro desde el servidor.
* 3. Una vez cargado el elemento, invoca el método postInit con el resultado devuelto por el servidor.
* @param id: Identificador del elemento. En el caso de una inserción, puede ser cero o undefined.
*/
BaseFormComponent.prototype.init = function (id) {
var _this = this;
console.log("init base-form.component");
this.formType = global_constants_1.FormType.Insert;
this.status = global_constants_1.PageStatus.Init;
if (id) {
// algunos proyectos utilizan identificadores negativos para datos del sistema!
this.dataService.get(id, this.paramsDataService).subscribe(function (result) { return _this.postInit(result); }, function (error) { return _this.messages.set(global_constants_1.PageStatus.Error, error); });
}
else {
this.postInit();
}
};
/** Cuando se pulsa un botón del toolbar. */
BaseFormComponent.prototype.onToolbarButtonPressed = function (button) {
console.log("Button pressed:" + button);
if (button === bit_toolbar_component_1.BitToolbarComponent.SAVE_BUTTON) {
this.save();
}
else if (button === bit_toolbar_component_1.BitToolbarComponent.DELETE_BUTTON) {
this.delete();
}
else if (button === bit_toolbar_component_1.BitToolbarComponent.PRINT_BUTTON) {
this.handlePrint();
}
else if (button === bit_toolbar_component_1.BitToolbarComponent.HELP_BUTTON) {
this.help();
}
else {
this.otherAction(button);
}
};
/**
* Inserta o actualiza el registro en el servidor.
* Una vez insertado o actualizado, se invoca al método postSave con el resultado de la operación.
*/
BaseFormComponent.prototype.save = function () {
var _this = this;
if (!this.myForm.valid) {
var errores = custom_validators_service_1.CustomValidators.validateForm(this.myForm);
this.messageService.sendError(new error_1.Error(null, "Error al formulari", "Error en el formulari", null, null, true, "", errores));
}
else {
if (this.preSave()) {
//console.log('save', this.object);
this.dataService.save(this.object, this.formType, this.paramsDataService).subscribe(function (result) { return _this.postSave(result); }, function (error) {
_this.status = global_constants_1.PageStatus.Error;
});
}
}
};
/** Elimina el registro en el servidor. Una vez eliminado, se invoca al método postDelete. */
BaseFormComponent.prototype.delete = function () {
var p = this.messageService.confirm("Està segur que vol eliminar aquest registre? Aquesta acciò no es podrà desfer?");
var local = this;
p.then(function (confirmacion) {
if (confirmacion) {
local.dataService.delete(local.object.id, local.paramsDataService).subscribe(function (result) {
local.postDelete();
}, function (error) {
local.status = global_constants_1.PageStatus.Error;
});
}
});
};
/** Muestra la ayuda asociada a la pantalla. */
BaseFormComponent.prototype.help = function () { };
BaseFormComponent.prototype.handlePrint = function () {
window.print();
};
/** Cualquier otra accion que no sea la típica de guardar o eliminar */
BaseFormComponent.prototype.otherAction = function (action) {
console.warn("otherAction " + action + " pressed");
};
/** Limpia el formulario, estableciendo los valores como si hubieramos entrado por primera vez. */
BaseFormComponent.prototype.cleanForm = function () {
//¿¿Algo que hacer??
};
Object.defineProperty(BaseFormComponent.prototype, "isEditMode", {
/** Devuelve true si el formulario edita un elemento existente, o false si inserta un nuevo elemento. */
get: function () {
return this.formType === global_constants_1.FormType.Update;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BaseFormComponent.prototype, "isDataChanged", {
/**
* Devuelve true si hay algún valor cambiado en la ficha.
* Puede ser por un campo del formulario (this.myForm.dirty) o por modificaciones en elementos relacionados.
*/
get: function () {
return this.myForm.dirty;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BaseFormComponent.prototype, "isFormValid", {
/** Devuelve true si el formulario es válido (campos validados automáticamente, elementos relacionados, etc.). */
get: function () {
//console.log('isFormValid', this.myForm.valid, this.myForm);
return this.myForm.valid;
},
enumerable: false,
configurable: true
});
/** Evalúa si el usuario puede desactivar/cerrar el componente sin perder cambios todavía no guardados. */
BaseFormComponent.prototype.canDeactivate = function () {
if (this.isDataChanged) {
//si hay cambios, mostramos la ventana de diálogo
var p = this.messageService.confirm("Hi ha canvis pendents de desar. Està segur de que vol sortir de la plana i perdre-los?");
var o = rxjs_1.from(p);
return o;
}
else {
// si no hay cambios, no la mostramos
return true;
}
};
BaseFormComponent.prototype.unloadWithUnsavedChanges = function ($event) {
var msg = "Hi ha canvis pendents de desar. Està segur de que vol sortir de la plana i perdre-los?";
if (this.isDataChanged) {
($event || window.event).returnValue = msg;
return msg;
}
return undefined;
};
/** Método que se ejecuta después de la lectura de los datos desde el servidor. */
BaseFormComponent.prototype.postInit = function (result) {
result = result || this.object;
this.object = result;
this.formType = result && result.id ? global_constants_1.FormType.Update : global_constants_1.FormType.Insert;
if (this.toolbar[bit_toolbar_component_1.BitToolbarComponent.DELETE_BUTTON])
this.toolbar[bit_toolbar_component_1.BitToolbarComponent.DELETE_BUTTON].visible = this.formType == global_constants_1.FormType.Update && !this.dialogMode; // no permitimos borrar en modo diálogo
if (this.toolbar[bit_toolbar_component_1.BitToolbarComponent.SAVE_BUTTON])
this.toolbar[bit_toolbar_component_1.BitToolbarComponent.SAVE_BUTTON].enable = true; //this.isFormValid; //si el form es valido activamos el botón
this.updateToolbar();
};
/** Método que se ejecuta antes de la inserción/modificación de los datos en el servidor. */
BaseFormComponent.prototype.preSave = function () {
// recuperamos los datos del formulario y los mapeamos en el object interno
Object.assign(this.object, this.myForm.value);
// por ejemplo, limpiar objetos anidados que no tengan ID (workaround para formularios)
return true;
};
/** Método que se ejecuta después de la inserción/modificación de los datos en el servidor. */
BaseFormComponent.prototype.postSave = function (result, avoidMessage) {
this.object = result;
avoidMessage ||
this.messageService.sendNotification(new bitmessage_1.BitMessage("Informació", "Les dades s'han desat correctament."));
// tras un guardado, marcamos el formulario como virgen para que no nos avise si intentamos abandonar la pantalla
this.myForm.markAsPristine(); // el formulario vuelve a estar sincronizado con el servidor
this.myForm.markAsUntouched(); // idem
if (this.formType == global_constants_1.FormType.Insert) {
// navegamos a la ficha en modo edición. Esto permite que se sustituya la URL y evitamos efectos colaterales
!this.dialogMode &&
this.router.navigate([general_utils_service_1.GeneralUtils.getPathFromURL(this.activatedRoute.snapshot.url), result.id], {
relativeTo: this.activatedRoute.parent
});
// si estamos en modo diálogo, hacemos un nuevo init con la entidad insertada
this.dialogMode && this.init(result.id);
}
this.onSave && this.onSave.emit(this.object);
};
/** Método que se ejecuta después de la eliminación del elemento en el servidor. */
BaseFormComponent.prototype.postDelete = function () {
this.messageService.sendNotification(new bitmessage_1.BitMessage("Informació", "Les dades s'han eliminat correctament."));
!this.dialogMode && this.goBack();
};
Object.defineProperty(BaseFormComponent.prototype, "safeBreadcrumb", {
/* Devuelve el breadcrumb solo si procede (por ejemplo, en modo diálogo no queremos breadcrumb). */
get: function () {
return !this.dialogMode && this.breadcrumb;
},
enumerable: false,
configurable: true
});
// Métodos relacionados con pestañas (tabs) //
/** Registra una pestaña de visualización de información. */
BaseFormComponent.prototype.registerTab = function (index, id) {
this.myTabs[id] = index;
};
// inicialización de pestañas (si hay)
BaseFormComponent.prototype.initTabs = function () {
this.currentTab = 0;
this.initialTab = this.activatedRoute.snapshot.params["tab"];
for (var tab in this.myTabs) {
var isInitial = this.isInitialTab(tab);
this.loadedTab[tab] = isInitial;
if (isInitial) {
this.currentTab = this.myTabs[tab];
}
}
};
/** Indica si la pestaña correspondiente es la inicial. */
BaseFormComponent.prototype.isInitialTab = function (tab) {
return this.initialTab === tab;
};
/** Indica si la pestaña correspondiente está cargada. */
BaseFormComponent.prototype.isLoadedTab = function (tab) {
return this.loadedTab[tab];
};
/** Controla cuando el usuario cambia de tab. */
BaseFormComponent.prototype.changeTab = function (e) {
console.log("change tab to number {}", e.index);
this.currentTab = e.index;
for (var tab in this.myTabs) {
this.loadedTab[tab] = this.loadedTab[tab] || e.index == this.myTabs[tab];
}
};
BaseFormComponent.prototype.isPreserveQueryParams = function () {
return true;
};
BaseFormComponent.ɵfac = function BaseFormComponent_Factory(t) { i0.ɵɵinvalidFactory(); };
BaseFormComponent.ɵdir = i0.ɵɵdefineDirective({ type: BaseFormComponent, hostBindings: function BaseFormComponent_HostBindings(rf, ctx) { if (rf & 1) {
i0.ɵɵlistener("beforeunload", function BaseFormComponent_beforeunload_HostBindingHandler() { return ctx.unloadWithUnsavedChanges(); }, false, i0.ɵɵresolveWindow);
} }, inputs: { dialogMode: "dialogMode", reset: "reset" }, outputs: { onSave: "onSave" }, features: [i0.ɵɵInheritDefinitionFeature] });
return BaseFormComponent;
}(base_component_1.BaseComponent));
exports.BaseFormComponent = BaseFormComponent;
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(BaseFormComponent, [{
type: core_1.Directive
}], function () { return [{ type: undefined }, { type: i1.Router }, { type: i1.ActivatedRoute }, { type: i2.MessageService }, { type: i3.ToolbarService }, { type: undefined }]; }, { onSave: [{
type: core_1.Output
}], dialogMode: [{
type: core_1.Input
}], reset: [{
type: core_1.Input
}], unloadWithUnsavedChanges: [{
type: core_1.HostListener,
args: ["window:beforeunload"]
}] }); })();
//# sourceMappingURL=base-form.component.js.map