Skip to content

Commit 5271232

Browse files
add save code to file button (#712)
* add save code to file button * add guess extension add guess extension rename CodeFenceCopyButton to CodeFenceButton * remove file-saver * Revert "remove file-saver" This reverts commit d75fe7d. * use downloadBlob
1 parent 089ce87 commit 5271232

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

src/components/atoms/markdown/CodeFence.tsx

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ import React from 'react'
22
import styled from '../../../lib/styled'
33
import copy from 'copy-to-clipboard'
44
import Icon from '../Icon'
5-
import { mdiContentCopy } from '@mdi/js'
5+
import { mdiContentCopy, mdiContentSave } from '@mdi/js'
66
import { flexCenter } from '../../../lib/styled/styleFunctions'
7-
7+
import { downloadBlob } from '../../../lib/download';
88
const CodeFenceContainer = styled.div`
99
position: relative;
1010
`
1111

12-
const CodeFenceCopyButton = styled.button`
12+
const CodeFenceButton = styled.button`
1313
position: absolute;
1414
top: 0;
1515
right: 0;
@@ -36,7 +36,6 @@ const CodeFenceCopyButton = styled.button`
3636
color: ${({ theme }) => theme.navButtonActiveColor};
3737
}
3838
`
39-
4039
const CodeFence = (props: React.HTMLProps<HTMLPreElement> = {}) => {
4140
if (props.className != null && props.className!.includes('CodeMirror')) {
4241
const otherProps = { ...props }
@@ -45,14 +44,27 @@ const CodeFence = (props: React.HTMLProps<HTMLPreElement> = {}) => {
4544
return (
4645
<CodeFenceContainer>
4746
<pre {...otherProps} />
48-
<CodeFenceCopyButton
47+
<CodeFenceButton
4948
onClick={() => {
5049
copy(rawContent)
5150
}}
5251
title='Copy to Clipboard'
5352
>
5453
<Icon path={mdiContentCopy} />
55-
</CodeFenceCopyButton>
54+
</CodeFenceButton>
55+
{rawContent && <CodeFenceButton
56+
onClick={() => {
57+
var blob = new Blob([rawContent], { type: "text/plain;charset=utf-8" });
58+
var ext = "";
59+
if (props.className!.includes('language-'))
60+
ext = "." + /language-(.+?)$/.exec(props.className!)![1]
61+
downloadBlob(blob, "snippet" + ext);
62+
}}
63+
title='Save to File'
64+
style={{ right: '30px' }}
65+
>
66+
<Icon path={mdiContentSave} />
67+
</CodeFenceButton>}
5668
</CodeFenceContainer>
5769
)
5870
}

0 commit comments

Comments
 (0)