| 1 |
import { SnippetType } from '../types/snippet' |
| 2 |
import { EditorConfiguration } from 'codemirror' |
| 3 |
|
| 4 |
const EDITOR_MODES: Record<SnippetType, string> = { |
| 5 |
css: 'text/css', |
| 6 |
js: 'javascript', |
| 7 |
php: 'text/x-php', |
| 8 |
html: 'application/x-httpd-php' |
| 9 |
} |
| 10 |
|
| 11 |
const selectScope = (type: SnippetType, snippetForm: HTMLElement | null) => { |
| 12 |
const editor = window.code_snippets_editor?.codemirror |
| 13 |
const scope = snippetForm?.querySelector<HTMLInputElement>(`.${type}-scopes-list input:first-child`) |
| 14 |
|
| 15 |
if (scope) { |
| 16 |
scope.checked = true |
| 17 |
} |
| 18 |
|
| 19 |
editor?.setOption('lint' as keyof EditorConfiguration, 'php' === type || 'css' === type) |
| 20 |
if (type in EDITOR_MODES) { |
| 21 |
editor?.setOption('mode', EDITOR_MODES[type]) |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
const switchTab = (tabsContainer: HTMLElement, tab: Element) => { |
| 26 |
const prevActive = tabsContainer.querySelector('.nav-tab-active') |
| 27 |
prevActive?.setAttribute('href', '#') |
| 28 |
prevActive?.classList.remove('nav-tab-active') |
| 29 |
|
| 30 |
tab.classList.add('nav-tab-active') |
| 31 |
tab.removeAttribute('href') |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
export const handleSnippetTypeTabs = () => { |
| 36 |
const tabsContainer = document.getElementById('snippet-type-tabs') |
| 37 |
|
| 38 |
if (!tabsContainer) { |
| 39 |
return |
| 40 |
} |
| 41 |
|
| 42 |
const snippetForm = document.getElementById('snippet-form') |
| 43 |
const tabs = tabsContainer.querySelectorAll('.nav-tab') |
| 44 |
|
| 45 |
for (const tab of tabs) { |
| 46 |
tab.addEventListener('click', event => { |
| 47 |
if (tab.classList.contains('nav-tab-active') || tab.classList.contains('nav-tab-inactive')) return |
| 48 |
const type = tab.getAttribute('data-type') as SnippetType |
| 49 |
event.preventDefault() |
| 50 |
|
| 51 |
// Update the form styles to match the new type. |
| 52 |
snippetForm?.setAttribute('data-snippet-type', type) |
| 53 |
|
| 54 |
// Switch the active tab and change the snippet scope. |
| 55 |
switchTab(tabsContainer, tab) |
| 56 |
selectScope(type, snippetForm) |
| 57 |
}) |
| 58 |
} |
| 59 |
|
| 60 |
} |
| 61 |
|