Project

General

Profile

1
import {
2
  Component,
3
  Inject,
4
  Input,
5
  OnDestroy,
6
  OnInit,
7
  RendererFactory2,
8
  ViewEncapsulation
9
} from '@angular/core';
10
import {Citation, CitationData} from './citation.class';
11
import {ResultLandingInfo} from "../../../utils/entities/resultLandingInfo";
12
import {DOCUMENT} from "@angular/common";
13
import {EnvProperties} from "../../../utils/properties/env-properties";
14
import {properties} from "../../../../../environments/environment";
15
import {PiwikService} from "../../../utils/piwik/piwik.service";
16

    
17
declare var Cite: any;
18
// Based on https://citation.js.org/api/tutorial-getting_started.html browser release
19
//<citeThis ></citeThis>
20
@Component({
21
  selector: 'citeThis',
22
  template: `
23
    <div class="uk-padding">
24
      <mat-form-field class="matSelectionFormField uk-width-1-1">
25
        <mat-label>Select a citation style</mat-label>
26
        <mat-select class="matSelection" id="citations" name="citeselect" [(ngModel)]="selectedStyle"
27
                    (ngModelChange)="styleChanged()"
28
                    [disableOptionCentering]="true"
29
                    panelClass="matSelectionPanel">
30
          <mat-option *ngFor=" let  style of this.citation.templates let i = index"
31
                      [value]="style">{{style}}</mat-option>
32
        </mat-select>
33
      </mat-form-field>
34
      <div *ngIf="selectedStyle" class="box-content uk-grid uk-margin-auto ">
35
        <div id="citation" class="  uk-overflow-auto uk-padding-small" [innerHTML]=citationText></div>
36
        <div class="uk-width-1-1">
37
          <button class="clipboard_btn uk-button uk-button-primary uk-button-small copy  uk-icon uk-float-right"
38
              data-clipboard-target="#citation" title="Copy to clipboard">
39
            <span class="custom-icon custom-copy-white"></span>
40
<!--            <span class="uk-margin-small-left">COPY</span>-->
41
          </button>
42
        </div>
43
      </div>
44
      <div  class="uk-margin-top">
45
        <mat-form-field class="matSelectionFormField uk-width-1-1">
46
          <mat-label>Or select file format to download</mat-label>
47
          <mat-select class="matSelection" id="fileformats" name="fileformatsSelect" [(ngModel)]="selectedFormat"
48
                      (ngModelChange)="formatChanged()"
49
                      [disableOptionCentering]="true"
50
                      panelClass="matSelectionPanel">
51
            <mat-option *ngFor=" let  format of citation.fileFormats let i = index"
52
                        [value]="format">{{format + " (" +citation.fileSuffix[i] + ")"}}</mat-option>
53
          </mat-select>
54
        </mat-form-field>
55
        <button  *ngIf="selectedFormat" class="  uk-button uk-button-primary uk-button-small uk-margin-small-top uk-icon uk-float-right"
56
                title="Copy to clipboard" [disabled]="!selectedFormat" (click)="downloadFile()">
57
          <span class="custom-icon " uk-icon="download"></span>
58
          <span class="uk-margin-small-left">Download</span>
59
        </button>
60
      </div>
61
    </div>
62
  `
63
})
64
export class CiteThisComponent implements OnInit, OnDestroy {
65
  public selectedStyle: string = null;
66
  public selectedFormat: string = null;
67
  public fileText: string;
68
  properties:EnvProperties;
69
  public citationText: string;
70
  public citation: Citation = new Citation();
71
  @Input() result: ResultLandingInfo;
72
  @Input() id: string;
73
  @Input() type: string = "article";
74
  @Input() piwikSiteId;
75
  public data:CitationData;
76
  public clipboard;
77
  timeout;
78
  cite;citeConfig;
79
  sub;
80
  constructor( @Inject(DOCUMENT) private document, private rendererFactory: RendererFactory2, private _piwikService: PiwikService){
81
}
82
  ngOnInit() {
83
    this.properties = properties;
84
    try{
85
      if (!this.document.getElementById('citationjs')) {
86
        const renderer = this.rendererFactory.createRenderer(this.document, {
87
          id: '-1',
88
          encapsulation: ViewEncapsulation.None,
89
          styles: [],
90
          data: {}
91
        });
92
        const head = this.document.head;
93
        if (head === null) {
94
          throw new Error('<head> not found within DOCUMENT.');
95
        }
96
        const script = renderer.createElement('script');
97
        renderer.setAttribute(script, "id", "citationjs");
98
        renderer.setAttribute(script, "src", "assets/common-assets/citation-0.4.0-9.min.js");
99
        renderer.setAttribute(script, "type", "text/javascript");
100
        renderer.appendChild(head, script);
101
        this.timeout = setTimeout(() => {
102
          const script2 = renderer.createElement('script');
103
          renderer.setAttribute(script2, "id", "citationjs2");
104
          renderer.setAttribute(script2, "type", "text/javascript");
105
          renderer.setProperty(script2,  "text","const Cite = require('citation-js')");
106
          renderer.appendChild(head, script2);
107
        }, 500);
108
      }
109

    
110
  }catch (e) {
111
    console.error(e)
112
  }
113
  }
114
  
115
  ngOnDestroy() {
116
    delete this.clipboard;
117
    clearTimeout(this.timeout);
118
  }
119
  private initiate(){
120
    this.citeConfig = Cite.plugins.config.get('csl');
121
    this.cite = new Cite();
122
    this.parseData();
123
    this.createClipboard();
124
  }
125
  private createClipboard() {
126
    if (typeof window !== 'undefined') {
127
      delete this.clipboard;
128
      let Clipboard;
129
      Clipboard = require('clipboard');
130
      this.clipboard = new Clipboard('.clipboard_btn');
131
    }
132
  }
133
  
134
  parseData() {
135
    var citationData: CitationData = new CitationData();
136
    
137
    if (this.result.identifiers && Array.from(this.result.identifiers.keys()).length > 0) {
138
      var keys = Array.from(this.result.identifiers.keys());
139
      for (var i = 0; i < keys.length; i++) {
140
        if (keys[i] == "doi") {
141
          var ids = this.result.identifiers.get(keys[i]);
142
          for (var j = 0; j < ids.length; j++) {
143
            citationData.DOI = ids[j];
144
            break;
145
          }
146
        }
147
      }
148
    }
149
    citationData.id = this.id;
150
    citationData.type =  this.mapTypes();
151
    if (this.result.title) {
152
      citationData.title = this.result.title;
153
    }
154
    if (this.result.publisher) {
155
      citationData.publisher = this.result.publisher;
156
    }
157
    if (this.result.authors) {
158
      citationData.author = [];
159
      var max_length = (this.result.authors.length > 10) ? 10 : this.result.authors.length;
160
      for (var i = 0; i < max_length; i++) {
161
        if (this.result.authors[i] && this.result.authors[i].fullName && this.result.authors[i].fullName.indexOf(", ") !== -1) {
162
          citationData.author.push({
163
            given: this.result.authors[i].fullName.split(", ")[1],
164
            family: this.result.authors[i].fullName.split(", ")[0],
165
            'parse-names': true
166
          });
167
        } else {
168
          citationData.author.push({given: "", family: this.result.authors[i].fullName, 'parse-names': true});
169
        }
170
        // citationData.authors.push(this.result.authors[i]);
171
      }
172
    }
173
    if (this.result.dateofacceptance != undefined) {
174
      citationData.issued = {};
175
      var date: string = (this.result.dateofacceptance.getFullYear()) + ""; // transform to string in case it is an integer
176
      var dateArray: string[] = (date && (date).indexOf('-') !== -1) ? [date.split('-')[0]] : [date];
177
      if (dateArray.length < 3) {
178
        // dateArray.push[1];
179
        // dateArray.push[1];
180
      }
181
      citationData.issued = {"date-parts": [["" + dateArray[0]]]};
182
      if (this.result.date) {
183
        citationData.date = this.result.date;
184
      }
185
      if (this.result.journal) {
186
        if (this.result.journal.journal) {
187
          citationData["container-title"] = this.result.journal.journal;
188
        }
189
        if (this.result.journal.issn) {
190
          citationData.ISSN = this.result.journal.issn;
191
        }
192
        if (this.result.journal.issue) {
193
          citationData.issue = this.result.journal.issue;
194
        }
195
        citationData.type = "article-journal"; // in case of APA volume and pages appear only in specific types not just article
196
        if (this.result.journal.volume) {
197
          citationData.volume = this.result.journal.volume;
198
        }
199
        if (this.result.journal["start_page"] && this.result.journal["end_page"]) {
200
          citationData.page = this.result.journal["start_page"] + "-" + this.result.journal["end_page"];
201
        }
202
      }
203
    }
204
    
205
    
206
    this.data = citationData;
207
    this.cite.set(this.data);
208
    
209
  }
210
  private mapTypes(){
211
    if (this.result.types != undefined && this.result.types.length > 0) {
212
      if(this.result.types.indexOf("Article") != -1) {
213
        return "article";
214
      }else if(this.result.types.indexOf("Conference object") != -1){
215
        return "paper-conference";
216
      }else if( this.result.types[0]){
217
        return this.result.types[0].toLowerCase();
218
      }
219
    }
220
    return "";
221
  }
222
  styleChanged() {
223
    this.citationText  = this.get(this.selectedStyle);
224
    
225
  }
226
  formatChanged() {
227
    this.fileText = this.get(this.selectedFormat, false);
228
  }
229
  downloadFile(){
230
    if (typeof document !== 'undefined') {
231
      var url = window.URL.createObjectURL(new Blob([this.fileText]));
232
      var a = window.document.createElement('a');
233
      window.document.body.appendChild(a);
234
      a.setAttribute('style', 'display: none');
235
      a.href = url;
236
      a.download = this.selectedFormat + this.citation.fileSuffix[this.citation.fileFormats.indexOf(this.selectedFormat)];
237
      a.click();
238
      window.URL.revokeObjectURL(url);
239
      a.remove(); // remove the element
240
      if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
241
        this.sub = this._piwikService.trackDownload(this.properties, "DownloadCitation"+this.selectedFormat,  this.piwikSiteId).subscribe();
242
      }
243
    }
244
  }
245

    
246
  get(style:string, isBibliography:boolean = true){
247
    try {
248
      if (!isBibliography  && style != "bibtex") {
249
        return this.getFormat(style);
250
      } else {
251
        return this.getBibliography(style);
252
      }
253
    }catch (e) {
254
      console.error(e);
255
      return "";
256
    }
257
  }
258

    
259
  /**
260
   * Supports formats bibtex, bibtxt, ris
261
   * @param format
262
   */
263
  getFormat(format:string) {
264
    if(!this.cite){
265
      this.initiate();
266
    }
267
    return this.cite.format(format, {
268
      format: 'text'
269
    });
270
  }
271

    
272
  /**
273
   * Based on this and citeproc library https://citation.js.org/api/tutorial-plugins.html
274
   * if the template doesn;t exist add the CSL xml and the library will produce the citation
275
   * @param template
276
   */
277

    
278
  getBibliography(template:string) {
279
    if(!this.cite || !this.citeConfig ){
280
      this.initiate();
281
    }
282
    if (!this.citeConfig.templates.get(template)) {
283
      this.citeConfig.templates.add(template, this.citation[template]);
284
    }
285
    return this.cite.format('bibliography', {
286
      format: 'text',
287
      template: template,
288
      lang: 'en-US'
289
    });
290
  }
291
}
(2-2/3)