forked from elmasse/hyper-markdown-preview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (70 loc) · 2.2 KB
/
index.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const { existsSync, readFileSync } = require('fs');
const { exec } = require('child_process');
const { resolve } = require('path');
const { markdown, replaceLocalImagePlugin } = require('./markdown');
const matcher = require('./shell-matcher');
const resolveCWD = (pid, cb) => {
exec(`lsof -n -p ${pid} | grep cwd | tr -s ' ' | cut -d ' ' -f9-`, (err, cwd) => {
if (err) {
cb(err, null);
} else {
cwd = cwd.trim();
cb(null, cwd);
}
});
}
exports.middleware = (store) => (next) => (action) => {
if ('SESSION_ADD_DATA' === action.type) {
const { data } = action;
const state = store.getState();
const { sessions } = state;
const { activeUid } = sessions;
const session = sessions.sessions[activeUid];
const { pid, shell } = session;
const match = data.match(matcher[shell]);
if (match) {
const file = match[2];
if (/\.(md|markdown)$/.test(file)) {
resolveCWD(pid, (err, cwd) => {
if (err) {
console.log('Cannot retrieve CWD', err);
return;
}
const path = resolve(cwd, file);
if (existsSync(path)) {
markdown.use(replaceLocalImagePlugin, {cwd});
const source = readFileSync(path, 'UTF-8');
const html = `<html>
<head>
<meta charset="utf-8">
<style>
.markdown-body {
font-family: Helvetica, Arial, sans serif;
}
img {
max-width: 90vw;
}
</style>
</head>
<body class="markdown-body">${markdown.render(source)}</body>
</html>`;
const url = URL.createObjectURL(new Blob([html],{type: 'text/html'}));
store.dispatch({
type: 'SESSION_URL_SET',
uid: activeUid,
url
});
} else {
next(action);
}
});
} else {
next(action);
}
} else {
next(action);
}
} else {
next(action);
}
};