Commit 05ec487e authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Create Formatter class.

Performs formatting of comments markdown.
parent 19b8adfd
Loading
Loading
Loading
Loading

comments/formatter.js

0 → 100644
+33 −0
Original line number Diff line number Diff line
var marked = require('marked');
var sanitizer = require('sanitizer');

/**
 * Performs formatting of comments.
 * @singleton
 */
var Formatter = {
    /**
     * Converts Markdown-formatted comment text into HTML.
     *
     * @param {String} content Markdown-formatted text
     * @return {String} HTML
     */
    format: function(content) {
        var markdowned;
        try {
            markdowned = marked(content);
        } catch(e) {
            markdowned = content;
        }

        // Strip dangerous markup, but allow links to all URL-s
        var sanitized_output = sanitizer.sanitize(markdowned, function(str) {
            return str;
        });

        // IE does not support '
        return sanitized_output.replace(/'/g, ''');
    }
};

module.exports = Formatter;
+32 −0
Original line number Diff line number Diff line
describe("Formatter#format", function() {
    var Formatter = require("./formatter");

    function format(text) {
        return Formatter.format(text).trim();
    }

    it("turns markdown into HTML", function() {
        expect(format("Hello **world**!")).toEqual("<p>Hello <strong>world</strong>!</p>");
    });

    it("allows simple HTML", function() {
        expect(format("Hello <b>world</b>!")).toEqual("<p>Hello <b>world</b>!</p>");
    });

    it("removes scripts", function() {
        expect(format("Hello <script src='/blah.js'></script>")).toEqual("<p>Hello </p>");
    });

    it("allows links to outside URL-s", function() {
        expect(format("[blah](http://example.com)")).toEqual('<p><a href="http://example.com">blah</a></p>');
    });

    it("turns apostrophes into &#39;", function() {
        expect(format("Let's rock!")).toEqual('<p>Let&#39;s rock!</p>');
    });

    it("turns URL-s into links", function() {
        expect(format("http://example.com")).toEqual('<p><a href="http://example.com">http://example.com</a></p>');
    });

});
+2 −0
Original line number Diff line number Diff line
@@ -8,6 +8,8 @@
        "jasmine-node": "~1.0",
        "express": "~3.0",
        "connect-mysql-session": "~0.1",
        "marked": "~0.2",
        "sanitizer": "~0.0",
        "mongoose": "~3.0"
    }
}