Added code highlighting

This commit is contained in:
Jori Lallo
2016-05-22 22:08:09 -07:00
parent 84b3b8ee39
commit d53bd8cebb
9 changed files with 144 additions and 24 deletions

View File

@@ -2,6 +2,10 @@ import {
DataTypes,
sequelize,
} from '../sequelize';
import {
convertToMarkdown,
truncateMarkdown,
} from '../utils/markdown';
import Atlas from './Atlas';
import Team from './Team';
import User from './User';
@@ -10,6 +14,15 @@ const Document = sequelize.define('document', {
id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
title: DataTypes.STRING,
text: DataTypes.TEXT,
html: DataTypes.TEXT,
preview: DataTypes.TEXT,
}, {
hooks: {
beforeCreate: (doc) => {
doc.html = convertToMarkdown(doc.text);
doc.preview = truncateMarkdown(doc.text, 160);
},
}
});
Document.belongsTo(Atlas, { as: 'atlas' });

View File

@@ -1,6 +1,3 @@
import marked from 'marked';
import { truncateMarkdown } from './utils/truncate';
import Document from './models/Document';
export function presentUser(user) {
@@ -60,8 +57,8 @@ export async function presentDocument(document, includeAtlas=false) {
id: document.id,
title: document.title,
text: document.text,
html: marked(document.text),
preview: truncateMarkdown(document.text, 160),
html: document.html,
preview: document.preview,
createdAt: document.createdAt,
updatedAt: document.updatedAt,
atlas: document.atlaId,

45
server/utils/markdown.js Normal file
View File

@@ -0,0 +1,45 @@
import truncate from 'truncate-html';
import marked, { Renderer } from 'marked';
import highlight from 'highlight.js';
const renderer = new Renderer();
renderer.code = (code, language) => {
const validLang = !!(language && highlight.getLanguage(language));
const highlighted = validLang ? highlight.highlight(language, code).value : code;
return `<pre><code class="hljs ${language}">${highlighted}</code></pre>`;
};
marked.setOptions({
renderer: renderer,
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: true,
});
// TODO: This is syncronous and can be costly,
// should be performed outside http request
const convertToMarkdown = (text) => {
return marked(text);
};
truncate.defaultOptions = {
stripTags: false,
ellipsis: '...',
decodeEntities: false,
excludes: ['h1', 'pre', ],
};
const truncateMarkdown = (text, length) => {
const html = convertToMarkdown(text);
return truncate(html, length);
};
export {
convertToMarkdown,
truncateMarkdown,
};

View File

@@ -1,18 +0,0 @@
import truncate from 'truncate-html';
import marked from 'marked';
truncate.defaultOptions = {
stripTags: false,
ellipsis: '...',
decodeEntities: false,
excludes: ['h1', 'pre',],
};
const truncateMarkdown = (text, length) => {
const html = marked(text);
return truncate(html, length);
};
export {
truncateMarkdown
};