| 1 |
import { getSnippetType } from './snippets/snippets' |
| 2 |
import type { SnippetsExport } from '../types/schema/SnippetsExport' |
| 3 |
import type { Snippet } from '../types/Snippet' |
| 4 |
|
| 5 |
const SECOND_IN_MS = 1000 |
| 6 |
const TIMEOUT_SECONDS = 40 |
| 7 |
const JSON_INDENT_SPACES = 2 |
| 8 |
|
| 9 |
const MIME_INFO = <const> { |
| 10 |
php: ['php', 'text/php'], |
| 11 |
html: ['php', 'text/php'], |
| 12 |
css: ['css', 'text/css'], |
| 13 |
js: ['js', 'text/javascript'], |
| 14 |
cond: ['json', 'application/json'], |
| 15 |
json: ['json', 'application/json'] |
| 16 |
} |
| 17 |
|
| 18 |
export const downloadAsFile = (content: BlobPart, filename: string, type: string) => { |
| 19 |
const link = document.createElement('a') |
| 20 |
link.download = filename |
| 21 |
link.href = URL.createObjectURL(new Blob([content], { type })) |
| 22 |
|
| 23 |
setTimeout(() => URL.revokeObjectURL(link.href), TIMEOUT_SECONDS * SECOND_IN_MS) |
| 24 |
setTimeout(() => link.click(), 0) |
| 25 |
} |
| 26 |
|
| 27 |
export const downloadSnippetExportFile = ( |
| 28 |
content: SnippetsExport | string, |
| 29 |
{ id, name, scope }: Snippet, |
| 30 |
type?: keyof typeof MIME_INFO |
| 31 |
) => { |
| 32 |
const sanitizedName = name.toLowerCase().replace(/[^\w-]+/g, '-').trim() |
| 33 |
const title = '' === sanitizedName ? `snippet-${id}` : sanitizedName |
| 34 |
|
| 35 |
if ('string' === typeof content) { |
| 36 |
const [ext, mimeType] = MIME_INFO[type ?? getSnippetType({ scope })] |
| 37 |
const filename = `${title}.code-snippets.${ext}` |
| 38 |
downloadAsFile(content, filename, mimeType) |
| 39 |
} else { |
| 40 |
const filename = `${title}.code-snippets.json` |
| 41 |
downloadAsFile(JSON.stringify(content, undefined, JSON_INDENT_SPACES), filename, 'application/json') |
| 42 |
} |
| 43 |
} |
| 44 |
|