/
Markdown.tsx
258 lines (236 loc) · 9.41 KB
/
Markdown.tsx
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
* Copyright 2020 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react'
import { v4 as uuid } from 'uuid'
import TurndownService from 'turndown'
import ReactMarkdown from 'react-markdown'
import { dirname, isAbsolute, join, relative } from 'path'
import { List, ListComponent, ListItem } from '@patternfly/react-core'
import { REPL, Tab as KuiTab, getPrimaryTabId } from '@kui-shell/core'
// GitHub Flavored Markdown plugin; see https://github.com/IBM/kui/issues/6563
import gfm from 'remark-gfm'
import Tooltip from '../spi/Tooltip'
import CodeSnippet from '../spi/CodeSnippet'
const SimpleEditor = React.lazy(() => import('./Editor/SimpleEditor'))
interface Props {
source: string
contentType?: 'text/html' | 'application/markdown'
tab?: KuiTab
repl?: REPL
/** if we have the full path to the source file */
fullpath?: string
/** css class for top-level element */
className?: string
/** Do not linkify external links */
noExternalLinks?: boolean
/** If true, don't provide scrollability */
nested?: boolean
/** Base HTTP Url? */
baseUrl?: string
}
export default class Markdown extends React.PureComponent<Props> {
private readonly _uuid = uuid()
private onCopy(value: string) {
navigator.clipboard.writeText(value)
}
private allContentIsRemote(): boolean {
return typeof this.props.baseUrl === 'string'
}
private anchorFrom(txt: string): string {
return `${this._uuid}-${txt}`
}
/** @return markdown source, as string in application/markdown format */
private source() {
if (this.props.contentType === 'text/html') {
const { gfm } = require('turndown-plugin-gfm')
const td = new TurndownService()
td.use(gfm)
return td.turndown(this.props.source)
} else {
return this.props.source
}
}
private handleImage(
src: string,
props: { width?: number | string; height?: number | string; align?: React.CSSProperties['float'] },
key?: string
) {
const isHttp = /^http/i.test(src)
const isLocal = !isHttp && !this.allContentIsRemote()
if (isLocal && this.props.fullpath) {
const absoluteSrc = isAbsolute(src) ? src : join(dirname(this.props.fullpath), src)
src = absoluteSrc
} else if (!isHttp && this.props.baseUrl) {
// then this is a relative path against
src = `${this.props.baseUrl}${src}`
}
const style = props ? { float: props.align } : undefined
return <img key={key} src={src} height={props.height} width={props.width} style={style} data-float={props.align} />
}
public render() {
return (
<ReactMarkdown
plugins={[gfm]}
source={this.source()}
data-is-nested={this.props.nested || undefined}
className={
this.props.className ||
'padding-content marked-content page-content' +
(!this.props.nested ? ' scrollable scrollable-x scrollable-auto' : ' full-height')
}
renderers={{
html: props => {
if (/<img/.test(props.value)) {
const images = props.value.split(/<img/).filter(_ => _)
const imageTags = images
.map((value, idx) => {
const srcMatch = value.match(/src="?([^"\s]+)"?/)
const heightMatch = value.match(/height="?(\d+)"?/)
const widthMatch = value.match(/width="?(\d+%?)"?/)
const alignMatch = value.match(/align="?([^"\s]+)"?/)
if (srcMatch) {
return this.handleImage(
srcMatch[1],
{
height: heightMatch && heightMatch[1],
width: widthMatch && widthMatch[1],
align: alignMatch && alignMatch[1]
},
idx
)
}
})
.filter(_ => _)
return <React.Fragment>{imageTags}</React.Fragment>
}
// Render the raw string for all other raw html tags
return <span>{props.value}</span>
},
link: props => {
const isLocal = !/^http/i.test(props.href)
const target = !isLocal ? '_blank' : undefined
const onClick = !isLocal
? (evt: React.MouseEvent) => evt.stopPropagation()
: async (evt: React.MouseEvent) => {
evt.stopPropagation()
let file = props.href
if (props.href.startsWith('#kuiexec?command=')) {
const raw = props.href.match(/#kuiexec\?command=([^&]+)(&quiet)?/)
if (raw) {
const cmdline = decodeURIComponent(raw[1])
const echo = !raw[2]
return this.props.repl.pexec(cmdline, { echo })
}
} else if (props.href.charAt(0) === '#') {
const elt = this.props.tab.querySelector(
`[data-markdown-anchor="${this.anchorFrom(props.href.slice(1))}"]`
)
if (elt) {
return elt.scrollIntoView()
}
} else if (file) {
if (this.props.fullpath) {
const absoluteHref = join(dirname(this.props.fullpath), props.href)
const relativeToCWD = relative(process.cwd() || process.env.PWD, absoluteHref)
file = relativeToCWD
}
return this.props.repl.pexec(`open ${this.props.repl.encodeComponent(file)}`)
}
}
if (!props.href) {
return <a className={this.props.className}>{props.children}</a>
} else if (!isLocal && this.props.noExternalLinks) {
return <span className={this.props.className}>{props.href}</span>
} else {
return (
<Tooltip markdown={`### External Link\n#### ${props.href}\n\n\`Link will open in a separate window\``}>
<a className="bx--link" {...props} target={target} onClick={onClick} />
</Tooltip>
)
}
},
code: props => {
if (this.props.nested) {
return (
<div className="paragraph">
<CodeSnippet value={props.value} onCopy={this.onCopy.bind(this, props.value)} />
</div>
)
} else {
return (
<div className="paragraph">
<code className="kui--code--editor">
<SimpleEditor
tabUUID={getPrimaryTabId(this.props.tab)}
content={props.value as string}
contentType={props.language}
fontSize={12}
simple
minHeight={0}
readonly
/>
</code>
</div>
)
}
},
heading: props => {
const valueChild =
props.children && props.children.length === 1
? props.children[0]
: props.children.find(_ => _.props.value)
const anchor =
!valueChild || !valueChild.props || !valueChild.props.value
? undefined
: this.anchorFrom(valueChild.props.value.toLowerCase().replace(/ /g, '-'))
return React.createElement(
`h${props.level}`,
Object.assign({}, props, {
'data-markdown-anchor': anchor,
'data-is-href': valueChild && valueChild.props && valueChild.props.href
}),
props.children
)
},
image: props => {
return this.handleImage(props.src, props) || <img {...props} />
},
list: props => {
return <List component={props.ordered ? ListComponent.ol : ListComponent.ul}>{props.children}</List>
},
listItem: props => <ListItem className={props.className}>{props.children}</ListItem>,
table: props => (
<table className={props.className + ' kui--table-like kui--structured-list'}>{props.children}</table>
),
tableHead: props => (
<thead className={props.className + ' kui--structured-list-thead'}>{props.children}</thead>
),
tableBody: props => (
<tbody className={props.className + ' kui--structured-list-tbody'}>{props.children}</tbody>
),
tableRow: props => <tr>{props.children}</tr>, // TODO ignoring columnAlignment
tableCell: props => {
if (props.isHeader) {
return <th style={{ textAlign: props.align }}>{props.children}</th>
} else {
return <td>{props.children}</td>
}
}
}}
/>
)
}
}