projects/app-base-library/src/lib/angular/components/svg-template.component.ts
providers |
ReplaceAllPipe
BetweenPipe
|
selector | svg-template |
template |
|
Properties |
|
Methods |
Inputs |
Outputs |
constructor(baseService: BaseService, elementRef: ElementRef, http: Http, renderer: Renderer, _sanitizer: DomSanitizer, replaceAll: ReplaceAllPipe, betweenPipe: BetweenPipe)
|
||||||||||||||||||||||||
Parameters :
|
data
|
Type:
Default value: |
src
|
Type: |
loaded
|
$event type: EventEmitter<any>
|
centerSketchUIText |
centerSketchUIText()
|
Returns :
void
|
initSvg | ||||
initSvg(svgElement: )
|
||||
Parameters :
Returns :
void
|
loadSvg |
loadSvg()
|
Returns :
void
|
ngOnChanges | ||||
ngOnChanges(changes: )
|
||||
Parameters :
Returns :
void
|
ngOnInit |
ngOnInit()
|
Returns :
void
|
prepareLoadedSvg | ||||||
prepareLoadedSvg(svgResult: string)
|
||||||
Parameters :
Returns :
void
|
renderData |
renderData()
|
Returns :
void
|
renderSvg |
renderSvg()
|
Returns :
void
|
renderTemplateData |
renderTemplateData()
|
Returns :
void
|
svgCalculateSize | ||||
svgCalculateSize(svg: )
|
||||
Parameters :
Returns :
{ width: any; height: any; }
|
trustAsHtml | ||||
trustAsHtml(content: )
|
||||
Parameters :
Returns :
any
|
Private _containerElements |
_containerElements:
|
Type : any
|
Default value : {}
|
Private _dataCurrent |
_dataCurrent:
|
Type : any
|
Private _dataNew |
_dataNew:
|
Type : any
|
Private _src |
_src:
|
Type : string
|
Public _svg |
_svg:
|
Type : any
|
Private _svgElement |
_svgElement:
|
Type : any
|
Public el |
el:
|
Type : HTMLElement
|
Public elementRef |
elementRef:
|
Type : ElementRef
|
Private settings |
settings:
|
Public type |
type:
|
Type : string
|
import { Component, ElementRef, EventEmitter, Renderer, Input, Output, OnChanges } from '@angular/core';
import { Http, Response } from '@angular/http';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { BetweenPipe, ReplaceAllPipe } from '../pipes/index';
import { BaseService } from '../services/base.service';
declare var _: any;
declare var $: any;
@Component({
selector: 'svg-template',
template: `<div *ngIf="_svg" [innerHTML]="trustAsHtml(_svg)" class="svg-container embedded"></div>`,
providers: [ReplaceAllPipe, BetweenPipe]
})
export class SvgTemplateComponent implements OnChanges {
@Input() private src: string;
@Input() private data: any = {};
@Output() public loaded: EventEmitter<any> = new EventEmitter();
private settings;
public _svg: any;
private _svgElement: any;
private _dataCurrent: any;
private _dataNew: any;
private _containerElements: any = {};
private _src: string;
public el: HTMLElement;
public type: string;
constructor(private baseService: BaseService, public elementRef: ElementRef, private http: Http, private renderer: Renderer, private _sanitizer: DomSanitizer, private replaceAll: ReplaceAllPipe, private betweenPipe: BetweenPipe) {
// super(baseService)
}
ngOnInit() {
this.settings = this.baseService.settings;
this.el = this.elementRef.nativeElement;
this.type = 'template';
this._src = this.src;
this.loadSvg();
}
ngOnChanges(changes) {
this._dataNew = this._dataCurrent = this.data;
// console.log(changes);
// if (changes.data) {
// console.log('ngOnChanges',changes.data);
// if (!this._dataCurrent) {
// this._dataCurrent = JSON.parse(JSON.stringify(changes.data.currentValue));
// }
// this._dataNew = JSON.parse(JSON.stringify(changes.data.currentValue));
// for(let k in this._dataNew){
// this.data[k]=this._dataNew[k];
// }
// this._dataNew = this._dataCurrent = this.data;
// console.log(this._dataNew.title);
// if (this.type === 'template') {
// this.renderData();
// this.renderTemplateData();
// } else {
// this.renderData();
// }
// }
}
initSvg(svgElement) {
this._svgElement = svgElement;
}
renderTemplateData() {
// type: svg-template
const self = this;
const obj: any = this.data;
if (self._dataNew) {
const objNew = self._dataNew;
Object.keys(objNew).forEach(function (keyNew) {
const newValue = obj[keyNew];
const objCurrent = self._dataCurrent;
Object.keys(objCurrent).forEach(function (keyCurrent) {
const currentValue = objCurrent[keyCurrent];
if (keyNew === keyCurrent) {
self._svg = self.replaceAll.transform(self._svg, '<!--data-->' + currentValue + '<!--end:data-->', '<!--data-->' + newValue + '<!--end:data-->');
}
});
// set new data properties
self._svg = self.replaceAll.transform(self._svg, '{{' + keyNew + '}}', '<!--data-->' + newValue + '<!--end:data-->');
});
this._dataCurrent = this._dataNew;
}
setTimeout(() => {
this.centerSketchUIText();
}, 100);
// todo: hide empty
// console.log(self.betweenPipe.transform(self._svg, '{{','}}'));
}
renderData() {
// type: svg-app
const self = this;
if (!this.data) {
return;
}
Object.keys(this.data).forEach(function (key) {
self[key] = self.data[key];
});
}
renderSvg() {
const self = this;
const $svg = this._svgElement;
const responsive = !(this.el.className.indexOf('img-responsive') === -1) ;
let viewBox;
if ($svg.getAttribute('viewBox')) {
viewBox = $svg.getAttribute('viewBox');
}
// console.log('--------------');
// console.log('svg: type=' + this.type);
// console.log('responsive=' + responsive);
let w, h;
// fixme ??
if (viewBox) {
w = viewBox.split(' ')[2];
h = viewBox.split(' ')[3];
if (responsive === false) {
// 100%
this.el.style.width = w + 'px';
this.el.style.maxWidth = w + 'px';
this.el.style.height = h + 'px';
this.el.style.maxHeight = h + 'px';
$svg.style.width = w + 'px';
$svg.style.maxWidth = w + 'px';
$svg.style.height = h + 'px';
$svg.style.maxHeight = h + 'px';
let att;
att = document.createAttribute('width');
att.value = w;
// att.value = w+'px';
$svg.setAttributeNode(att);
att = document.createAttribute('height');
att.value = h;
// att.value = h+'px';
$svg.setAttributeNode(att);
}
// console.log($svg.getAttribute('width'));
// console.log($svg.getAttribute('height'));
}
// replace Illustrator fonts: fixme: check + remove jQuery dependency
if (this.settings.font_replace_map && (<any>window)['$']) {
_.each(this.settings.font_replace_map, function(obj){
_.each(obj, function(v, k){
// presentation export:
$(self.el).find('svg text').each(function(){
if ($(this).attr('font-family')) {
if ($(this).attr('font-family').match(k)) {
// console.log('v',v);
// console.log('k',k);
$(this).attr('font-family', $(this).attr('font-family').replace(k, v));
$(this).css('font-family:' + v);
}
}
});
// styles export:
$(self.el).find('svg style').each(function(){
$(this).text($(this).text().replace(k, v));
});
});
});
}
}
prepareLoadedSvg(svgResult: string) {
if (this.type === 'template') {
// fixes Illustrator weird character display bug.
svgResult = svgResult.replace(']>', '');
// remove whitespaces around data properties
svgResult = this.replaceAll.transform(svgResult, '{{ ', '{{');
svgResult = this.replaceAll.transform(svgResult, '{{ ', '{{');
svgResult = this.replaceAll.transform(svgResult, '{{ ', '{{');
svgResult = this.replaceAll.transform(svgResult, ' }}', '}}');
svgResult = this.replaceAll.transform(svgResult, ' }}', '}}');
svgResult = this.replaceAll.transform(svgResult, ' }}', '}}');
this._svg = svgResult;
const timer = setInterval(() => {
if (this.el.querySelector('svg')) {
this.initSvg(this.el.querySelector('svg'));
this.renderSvg();
if (this.type === 'template') {
if (this.loaded) {
this.loaded.emit('svg-loaded');
}
this.renderTemplateData();
}
if (this.type === 'embedded') {
// fix to hide xml tag display ??
this.el.style.fontSize = '0';
// let positionCorrection = 0 - this._svgElement.getBoundingClientRect().left + this.el.getBoundingClientRect().left;
// this.el.style.marginLeft = positionCorrection+'px';
// this.el.style.overflowX = 'hidden';
if (this.loaded) {
this.loaded.emit('svg-loaded');
}
}
clearInterval(timer);
}
}, 50);
return;
}
}
loadSvg() {
if (this.src) {
this.http.get(this.src)
.subscribe(
(res: Response) => {
this.prepareLoadedSvg(res.text());
},
err => {
console.error(err);
}
);
}
}
// fixme: cannot change svg attributes
centerSketchUIText() {
const self = this;
if (!this._svg && !this.data) {
return;
}
if (!this.el.querySelectorAll("[id*='UI']").length) {
return;
}
// let $el;
// $el = this.el;
//
// Object.keys(this.data).forEach((key) => {
// // const value = this.data[key];
// let idSelector = '{{-'+key+'-}}';
// let query = "[id*='"+idSelector+"']";
// let containerElements = [];
// // if (self.el.querySelectorAll(query).length){
// if ($el.querySelectorAll(query).length){
// if(!self._containerElements[query]){
// self._containerElements[query] = [];
// }
// self._containerElements[query] = $el.querySelectorAll(query);
//
// console.log(query);
// console.log('matches='+$el.querySelectorAll(query).length);
//
// if(self._containerElements[query].length){
// _.each(self._containerElements[query],(container)=>{
// let el = container;
//
// let BG = container.querySelectorAll("[id*='BG']")[0];
// let BGAttrs = {id:''};
// let BGBox = BG.getBBox()
// Object.keys(BG.attributes).forEach((key) => {
// BGAttrs[BG.attributes[key].name]=BG.attributes[key].value;
// });
// console.log('---------');
// console.log('BG.BGAttrs',BGAttrs);
// console.log('BG.getBBox',BGBox);
//
// let text = container.querySelectorAll("text")[0];
// let textAttrs = {id:''};
// let textBBox = text.getBBox()
// Object.keys(text.attributes).forEach((key) => {
// textAttrs[text.attributes[key].name]=text.attributes[key].value;
// });
// console.log('---------');
// console.log('text',textAttrs);
// console.log('text.getBBox',textBBox);
//
// let tspan = container.querySelectorAll("tspan")[0];
// let tspanAttrs = {};
// let tspanBBox = tspan.getBBox()
// Object.keys(tspan.attributes).forEach((key) => {
// tspanAttrs[tspan.attributes[key].name]=tspan.attributes[key].value;
// });
// console.log('---------');
// console.log('tspan',tspanAttrs);
// console.log('tspan.getBBox',tspanBBox);
//
// console.log('===============');
// console.log('BG',self.svgCalculateSize(BG));
// console.log('text',self.svgCalculateSize(text));
// console.log('tspan'+self.svgCalculateSize(tspan));
//
// setTimeout(()=>{
// // fixme:
// console.log('fixme:----- set ------');
// console.log($(tspan).attr('x'));
// console.log($(tspan).attr('y'));
// // console.log(tspan);
// tspan.setAttribute("x", "0");
// tspan.setAttribute("y", "0");
// console.log($(tspan).attr('x'));
// console.log($(tspan).attr('y'));
// console.log(tspan.attributes);
// },1000)
//
// // tspanAttrs['x']=0;
// // console.log(tspanAttrs);
// // console.log('x',tspan.x.animVal[0].value);
// // console.log('x',tspan.x.animVal[0].valueAsString);
// // console.log('y',tspan.y);
// // console.log('textLength',tspan.textLength);
// // console.log(tspan.offsetWidth);
// // console.log(tspan.offsetHeight);
// // tspan
//
// });
// // console.log(containerElements);
// }
//
// };
// });
//
// console.log(self);
// console.log(self._containerElements);
}
svgCalculateSize(svg) {
// svg.style.display='block';
// svg.style.display='none';
let svgWidth = svg.clientWidth || window.getComputedStyle(svg).width;
let svgHeight = svg.clientHeight || window.getComputedStyle(svg).height;
// let svgWidth = $(svg).width();
// let svgHeight =$(svg).height();
return({width: svgWidth, height: svgHeight});
// let heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'];
// let widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];
//
// let gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
// bounds = {
// width: 0,
// height: 0
// };
//
// heightComponents.forEach(function (css) {
// bounds.height += parseFloat(gCS[css]);
// });
// widthComponents.forEach(function (css) {
// bounds.width += parseFloat(gCS[css]);
// });
// return bounds;
};
trustAsHtml(content) {
return this._sanitizer.bypassSecurityTrustHtml(content) as SafeHtml;
};
}