Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Функционал глобального переключения синтаксисов #683

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/.vitepress/theme/components/DocsLayout.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import DocsEcosystem from './DocsEcosystem.vue'
import DocsComponentWidget from './DocsComponentWidget.vue'
import DocsBreadcrumbs from './DocsBreadcrumbs.vue'
import DocsNotFound from './DocsNotFound.vue'
import { useSyntaxSwitcher } from '../composables/syntax-switcher'

const { Layout } = DefaultTheme
useSyntaxSwitcher('vitepress:default-syntax', ['modx', 'fenom'])
</script>

<template>
Expand Down
54 changes: 54 additions & 0 deletions docs/.vitepress/theme/composables/syntax-switcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { onMounted, watch } from 'vue'
import { inBrowser, useRouter } from 'vitepress'

function setSyntax(
syntax: string,
target?: HTMLLabelElement,
) {
const allGroups = document.querySelectorAll('.vp-code-group')
const group = target && target.closest('.vp-code-group')

for (let i = 0; i < allGroups.length; i++) {
if (group && allGroups[i] === group) continue
Array.from(allGroups[i].querySelectorAll('label')).find(el => el.innerText === syntax)?.click()
}
}

export function useSyntaxSwitcher(
key: string,
labels: Array<string>,
): void {
if (inBrowser) {
onMounted(() => {
const { route } = useRouter()
watch(
() => route.data.relativePath,
() => {
const defaultSyntax = localStorage.getItem(key)
defaultSyntax && setSyntax(defaultSyntax)
}, {
immediate: true,
flush: 'post',
})
})

window.addEventListener('click', (e: Event) => {
const target = e.target as HTMLLabelElement

if (
!target.matches('.vp-code-group .tabs label') ||
!e.isTrusted
) {
return
}

const syntax = target.innerText
if (!labels.some(label => label === syntax)) {
return
}

localStorage.setItem(key, syntax)
setSyntax(syntax, target)
})
}
}