aboutsummaryrefslogtreecommitdiff
path: root/javascript/app/components/text-file.js
blob: 05be31abb708c7903ff627a14c44e2d031b4b2e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* global showdown */
import Ember from 'ember';
import {initializeLineSelection} from '../utils/line-selection';

function escapeHtml(text) {
  return text.replace(/[\"&<>]/g, function (a) {
    return { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' }[a];
  });
}

function addLineNumbers (text) {
  const start = "<table class='source-code'><tbody>";
  const end = "</tbody></table>";
  let lineNumber = 0;
  const lines = text.split("\n").map((line) => {
    lineNumber ++;
    const lineNumberHtml = "<td id='LN"+lineNumber+"' class='line-number'>"+lineNumber+"</td>";
    const lineContentHtml = "<td id='LC"+lineNumber+"' class='line-content'>"+escapeHtml(line)+"</td>";
    return "<tr>"+ lineNumberHtml + lineContentHtml + "</tr>";
  }).join("");
  return start + lines + end;
}

const markdownExtensions = ["markdown", "mdown", "mkdn", "mkd", "md"];

export default Ember.Component.extend({
  isMarkdown : Ember.computed('path',function() {
    const maybeExtension = this.get('path').split('.').pop();
    return markdownExtensions.any((extension) => (maybeExtension === extension));
  }),
  html : Ember.computed('path','isMarkdown',function() {
    if(this.get('isMarkdown')) {
      return this.markdownConverter.makeHtml(this.get('text'));
    } else {
      return addLineNumbers(this.get('text'));
    }
  }),
  init() {
    this._super(...arguments);
    this.markdownConverter = new showdown.Converter();    
  },
  didInsertElement() {
    const sourceCodeContainerElement = this.element.querySelector('.source-code-container');
    initializeLineSelection(sourceCodeContainerElement,this);
    this.element.parentNode.scrollTop = 0;
  },
  willDestroyElement : function () {
    this.cleanup();
  },
  cleanup() {
    if(this._onhashchange) {      
      window.removeEventListener('hashchange',this._onhashchange);
    }
    if(this._onkeydown) {
      document.removeEventListener('keydown',this._onkeydown);
    }
    if(this._onkeyup) {
      document.removeEventListener('keyup',this._onkeyup);
    }
  },
  pathObserver : Ember.observer('path',function() {
    Ember.run.next(this,() => {
      this.cleanup();
      this.didInsertElement();      
    });
  })
});