PluginProbe
Code Snippets / 3.7.0
Code Snippets v3.7.0
3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 3.0.1 All 64 releases
code-snippets / js / utils / files.ts

files.ts in Code Snippets 3.7.0, at js/utils/files.ts

44 lines 1.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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