Skip to content
Merged
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
3 changes: 1 addition & 2 deletions app/components/Editor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,6 @@ defineEmits([

const { orientation, language } = toRefs(props);
const { $bus, $shiki } = useNuxtApp();
const { options: languageOptions } = useLanguages();

const root = ref(null);
const monaco = ref(null);
Expand All @@ -231,7 +230,7 @@ defineExpose({
focusToggle: () => hideButton.value?.$el?.focus({ preventScroll: true }),
});

const languages = computed(() => languageOptions($shiki.languages()));
const languages = computed(() => $shiki.languageOptions());
const landscape = computed(() => ['left', 'right'].includes(orientation.value));

const languageAlias = computed(
Expand Down
25 changes: 9 additions & 16 deletions app/components/ModalPreferences.vue
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,14 @@
<TabsContent value="editor" class="mt-0 space-y-4">
<SettingsSection title="Language & Position">
<SettingsRow label="Default Language">
<Select v-model="preferences.editorLanguage">
<SelectTrigger class="w-28 sm:w-40">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem
v-for="lang in languages"
:key="lang"
:value="lang"
>
{{ lang }}
</SelectItem>
</SelectContent>
</Select>
<SearchableSelect
v-model="preferences.editorLanguage"
:options="languages"
button-aria-label="Default Language"
placeholder="Search languages..."
empty-text="No languages found."
class="w-28 sm:w-40"
/>
</SettingsRow>

<SettingsRow label="Panel Position">
Expand Down Expand Up @@ -571,7 +565,6 @@ defineProps({
defineEmits(['update:modelValue']);

const { $shiki } = useNuxtApp();
const { options: languageOptions } = useLanguages();
const activeTab = ref('editor');
const isAutoColorScheme = ref(null);
const customAspectRatioWidth = ref('');
Expand All @@ -581,7 +574,7 @@ const { types: socialTypes, positions: socialPositions } = useSocials();

const { fontFamilies } = useFonts();

const languages = computed(() => languageOptions($shiki.languages()));
const languages = computed(() => $shiki.languageOptions());

const tabs = [
{ value: 'editor', label: 'Editor', icon: CodeIcon },
Expand Down
60 changes: 41 additions & 19 deletions app/components/SearchableSelect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<button
type="button"
:aria-label="buttonAriaLabel"
:title="modelValue"
:title="selectedLabel"
:class="
cn(
'ui-field rounded-control flex h-7 items-center justify-between border px-2 py-1 text-start text-xs disabled:cursor-not-allowed disabled:opacity-50',
Expand All @@ -13,7 +13,7 @@
)
"
>
<span class="truncate">{{ modelValue }}</span>
<span class="truncate">{{ selectedLabel }}</span>
<ChevronsUpDownIcon class="ml-2 size-3 shrink-0 opacity-50" />
</button>
</PopoverTrigger>
Expand Down Expand Up @@ -49,20 +49,20 @@
<div class="p-1">
<button
v-for="option in filteredOptions"
:key="option"
:key="option.value"
type="button"
:data-active-searchable-select-option="
activeOption === option ? 'true' : undefined
activeOption === option.value ? 'true' : undefined
"
class="ui-menu-item relative flex w-full items-center py-1 pr-2 pl-6 text-left text-xs"
@mouseenter="activeOption = option"
@click="selectOption(option)"
@mouseenter="activeOption = option.value"
@click="selectOption(option.value)"
>
<CheckIcon
v-if="option === modelValue"
v-if="option.value === selectedOption?.value"
class="absolute left-2 size-4"
/>
<span class="truncate">{{ option }}</span>
<span class="truncate">{{ option.label }}</span>
</button>

<div
Expand Down Expand Up @@ -103,25 +103,45 @@ const searchInput = ref(null);
const optionsScrollArea = ref(null);
const activeOption = ref(null);

const selectedOption = computed(
() =>
props.options.find((option) => option.value === props.modelValue) ??
props.options.find((option) => option.aliases.includes(props.modelValue))
);
const selectedLabel = computed(() => selectedOption.value?.label ?? props.modelValue);

const filteredOptions = computed(() => {
const query = search.value.trim().toLowerCase();

if (!query) {
return props.options;
}

return props.options.filter((option) => option.toLowerCase().includes(query));
const exact = [];
const partial = [];

for (const option of props.options) {
const terms = [option.label, option.value, ...option.aliases].map((term) =>
term.toLowerCase()
);

if (terms.includes(query)) {
exact.push(option);
} else if (terms.some((term) => term.includes(query))) {
partial.push(option);
}
}

return [...exact, ...partial];
});

function selectOption(option) {
emit('update:modelValue', option);
function selectOption(value) {
emit('update:modelValue', value);
open.value = false;
}

function activateCurrentOption() {
activeOption.value = filteredOptions.value.includes(props.modelValue)
? props.modelValue
: filteredOptions.value[0];
activeOption.value = selectedOption.value?.value ?? filteredOptions.value[0]?.value;
}

function moveActiveOption(direction) {
Expand All @@ -130,14 +150,16 @@ function moveActiveOption(direction) {
return;
}

const currentIndex = filteredOptions.value.indexOf(activeOption.value);
const currentIndex = filteredOptions.value.findIndex(
(option) => option.value === activeOption.value
);
const fallbackIndex = direction > 0 ? -1 : 0;
const nextIndex = (currentIndex === -1 ? fallbackIndex : currentIndex) + direction;

activeOption.value =
filteredOptions.value[
(nextIndex + filteredOptions.value.length) % filteredOptions.value.length
];
].value;
}

function handleSearchKeydown(event) {
Expand Down Expand Up @@ -189,9 +211,9 @@ watch(filteredOptions, () => {
return;
}

if (!filteredOptions.value.includes(activeOption.value)) {
activateCurrentOption();
}
activeOption.value = search.value.trim()
? filteredOptions.value[0]?.value
: (selectedOption.value?.value ?? filteredOptions.value[0]?.value);
});

watch(activeOption, async () => {
Expand Down
21 changes: 10 additions & 11 deletions app/composables/useLanguages.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
import { orderBy } from 'lodash';
import { invert } from 'lodash';

const languageAliases = {
bash: 'shellscript',
dockerfile: 'docker',
};

const editorLanguageIds = invert(languageAliases);

export default function () {
function options(languages = []) {
return orderBy(
languages.map((language) => {
return (
{
docker: 'dockerfile',
shellscript: 'bash',
}[language] ?? language
);
})
);
return languages
.map(({ id, name, aliases = [] }) => ({
value: editorLanguageIds[id] ?? id,
label: name,
aliases: [id, ...aliases],
}))
.sort((a, b) => a.label.localeCompare(b.label, 'en'));
}

function highlightLanguage(language) {
Expand Down
12 changes: 8 additions & 4 deletions app/plugins/shiki.client.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { ref } from 'vue';
import { computed, ref } from 'vue';
import useLanguages from '@/composables/useLanguages';

export default defineNuxtPlugin(() => {
const worker = new Worker(new URL('../workers/shiki.worker.js', import.meta.url), {
type: 'module',
});

const pending = new Map();
const allLanguageIds = ref([]);
const allLanguages = ref([]);
const { options } = useLanguages();
const languageOptions = computed(() => options(allLanguages.value));
const allThemeIds = ref([]);
let requestId = 0;
let failure = null;
Expand Down Expand Up @@ -50,15 +53,16 @@ export default defineNuxtPlugin(() => {
}

const ready = send('initialize').then(({ languages, themes }) => {
allLanguageIds.value = languages;
allLanguages.value = languages;
allThemeIds.value = themes;
});

return {
provide: {
shiki: {
ready,
languages: () => allLanguageIds.value,
languages: () => allLanguages.value.map(({ id }) => id),
languageOptions: () => languageOptions.value,
themes: () => allThemeIds.value,
async tokenizeBlocks(payload) {
await ready;
Expand Down
4 changes: 2 additions & 2 deletions app/workers/shiki.worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ async function initialize() {
});

const languages = bundledLanguagesInfo
.map(({ id }) => id)
.filter((id) => !['php-html', 'html-derivative'].includes(id));
.filter(({ id }) => !['php-html', 'html-derivative'].includes(id))
.map(({ id, name, aliases = [] }) => ({ id, name, aliases }));

const bundledThemes = bundledThemesInfo
.map(({ id }) => id)
Expand Down
19 changes: 14 additions & 5 deletions tests/components/Editor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ describe('Editor', () => {
});

it('shows the language, settings, and add controls in a compact dock', async () => {
vi.spyOn(useNuxtApp().$shiki, 'languageOptions').mockReturnValue([
{ value: 'php', label: 'PHP', aliases: ['php'] },
]);
const wrapper = mount(Editor, {
props: { id: 'first', language: 'php' },
global: { stubs: { Monaco: MonacoStub }, directives: { tooltip: {} } },
Expand All @@ -64,7 +67,7 @@ describe('Editor', () => {

const dock = wrapper.get('[aria-label="Editor tools"]');
expect(dock.findAll('button')).toHaveLength(3);
expect(dock.get('[aria-label="Code language"]').text()).toBe('php');
expect(dock.get('[aria-label="Code language"]').text()).toBe('PHP');
expect(dock.get('[aria-label="Editor settings"]').exists()).toBe(true);
expect(wrapper.find('.workspace-statusbar').exists()).toBe(false);

Expand All @@ -73,10 +76,13 @@ describe('Editor', () => {
wrapper.unmount();
});

it('searches languages from the upward-opening dropdown', async () => {
vi.spyOn(useNuxtApp().$shiki, 'languages').mockReturnValue(['php', 'javascript']);
it('prioritizes an exact alias and emits the saved language id', async () => {
vi.spyOn(useNuxtApp().$shiki, 'languageOptions').mockReturnValue([
{ value: 'json', label: 'JSON', aliases: ['json'] },
{ value: 'javascript', label: 'JavaScript', aliases: ['js', 'mjs'] },
]);
const wrapper = mount(Editor, {
props: { id: 'first', language: 'php' },
props: { id: 'first', language: 'json' },
attachTo: document.body,
global: { stubs: { Monaco: MonacoStub }, directives: { tooltip: {} } },
});
Expand All @@ -87,7 +93,10 @@ describe('Editor', () => {
const search = new DOMWrapper(
document.querySelector('[placeholder="Search languages..."]')
);
await search.setValue('javascript');
await search.setValue('JS');
expect(
document.querySelector('[data-active-searchable-select-option]').textContent.trim()
).toBe('JavaScript');
await search.trigger('keydown', { key: 'Enter' });
await flushPromises();

Expand Down
19 changes: 13 additions & 6 deletions tests/composables/useLanguages.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@ import { describe, expect, it } from 'vitest';
import useLanguages from '~/composables/useLanguages';

describe('useLanguages', () => {
it('exposes familiar markdown language ids instead of internal grammar ids', () => {
it('sorts display names while preserving editor ids and searchable grammar aliases', () => {
const { options } = useLanguages();

expect(options(['typescript', 'shellscript', 'php', 'docker'])).toEqual([
'bash',
'dockerfile',
'php',
'typescript',
expect(
options([
{ id: 'shellscript', name: 'Shell', aliases: ['bash', 'sh', 'zsh'] },
{ id: 'csharp', name: 'C#', aliases: ['cs'] },
{ id: 'php', name: 'PHP' },
{ id: 'docker', name: 'Dockerfile', aliases: ['dockerfile'] },
])
).toEqual([
{ value: 'csharp', label: 'C#', aliases: ['csharp', 'cs'] },
{ value: 'dockerfile', label: 'Dockerfile', aliases: ['docker', 'dockerfile'] },
{ value: 'php', label: 'PHP', aliases: ['php'] },
{ value: 'bash', label: 'Shell', aliases: ['shellscript', 'bash', 'sh', 'zsh'] },
]);
});

Expand Down
9 changes: 8 additions & 1 deletion tests/plugins/shiki.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,18 @@ describe('Shiki worker client', () => {
} = shikiPlugin();
worker.dispatchEvent(
new MessageEvent('message', {
data: { id: 1, result: { languages: ['php'], themes: ['github-dark'] } },
data: {
id: 1,
result: {
languages: [{ id: 'php', name: 'PHP', aliases: [] }],
themes: ['github-dark'],
},
},
})
);
await shiki.ready;
expect(shiki.languages()).toEqual(['php']);
expect(shiki.languageOptions()).toEqual([{ value: 'php', label: 'PHP', aliases: ['php'] }]);
const first = shiki.tokenizeBlocks({ theme: 'github-dark', blocks: [] });
const second = shiki.tokenizeBlocks({ theme: 'github-light', blocks: [] });
await Promise.resolve();
Expand Down
Loading