Merge branch 'feat/code-highlighter' into chore/all-my-stuffs

# Conflicts:
#	src/tools/index.ts
This commit is contained in:
ShareVB committed 2024-11-03 20:17:57 +01:00
commit 528e88c908
8 files changed
+199 -4

No files matched your search

+4 -1
View File
@@ -286,6 +286,9 @@
"watchTriggerable": true,
"watchWithFilter": true,
"whenever": true,
"toValue": true
"toValue": true,
"injectLocal": true,
"provideLocal": true,
"useClipboardItems": true
}
}
+9
View File
@@ -36,6 +36,7 @@ declare global {
const h: typeof import('vue')['h']
const ignorableWatch: typeof import('@vueuse/core')['ignorableWatch']
const inject: typeof import('vue')['inject']
const injectLocal: typeof import('@vueuse/core')['injectLocal']
const isDefined: typeof import('@vueuse/core')['isDefined']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
@@ -65,6 +66,7 @@ declare global {
const onUpdated: typeof import('vue')['onUpdated']
const pausableWatch: typeof import('@vueuse/core')['pausableWatch']
const provide: typeof import('vue')['provide']
const provideLocal: typeof import('@vueuse/core')['provideLocal']
const reactify: typeof import('@vueuse/core')['reactify']
const reactifyObject: typeof import('@vueuse/core')['reactifyObject']
const reactive: typeof import('vue')['reactive']
@@ -128,6 +130,7 @@ declare global {
const useBrowserLocation: typeof import('@vueuse/core')['useBrowserLocation']
const useCached: typeof import('@vueuse/core')['useCached']
const useClipboard: typeof import('@vueuse/core')['useClipboard']
const useClipboardItems: typeof import('@vueuse/core')['useClipboardItems']
const useCloned: typeof import('@vueuse/core')['useCloned']
const useColorMode: typeof import('@vueuse/core')['useColorMode']
const useConfirmDialog: typeof import('@vueuse/core')['useConfirmDialog']
@@ -326,6 +329,7 @@ declare module 'vue' {
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly ignorableWatch: UnwrapRef<typeof import('@vueuse/core')['ignorableWatch']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly injectLocal: UnwrapRef<typeof import('@vueuse/core')['injectLocal']>
readonly isDefined: UnwrapRef<typeof import('@vueuse/core')['isDefined']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
@@ -355,6 +359,7 @@ declare module 'vue' {
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly pausableWatch: UnwrapRef<typeof import('@vueuse/core')['pausableWatch']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly provideLocal: UnwrapRef<typeof import('@vueuse/core')['provideLocal']>
readonly reactify: UnwrapRef<typeof import('@vueuse/core')['reactify']>
readonly reactifyObject: UnwrapRef<typeof import('@vueuse/core')['reactifyObject']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
@@ -418,6 +423,7 @@ declare module 'vue' {
readonly useBrowserLocation: UnwrapRef<typeof import('@vueuse/core')['useBrowserLocation']>
readonly useCached: UnwrapRef<typeof import('@vueuse/core')['useCached']>
readonly useClipboard: UnwrapRef<typeof import('@vueuse/core')['useClipboard']>
readonly useClipboardItems: UnwrapRef<typeof import('@vueuse/core')['useClipboardItems']>
readonly useCloned: UnwrapRef<typeof import('@vueuse/core')['useCloned']>
readonly useColorMode: UnwrapRef<typeof import('@vueuse/core')['useColorMode']>
readonly useConfirmDialog: UnwrapRef<typeof import('@vueuse/core')['useConfirmDialog']>
@@ -610,6 +616,7 @@ declare module '@vue/runtime-core' {
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly ignorableWatch: UnwrapRef<typeof import('@vueuse/core')['ignorableWatch']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly injectLocal: UnwrapRef<typeof import('@vueuse/core')['injectLocal']>
readonly isDefined: UnwrapRef<typeof import('@vueuse/core')['isDefined']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
@@ -639,6 +646,7 @@ declare module '@vue/runtime-core' {
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly pausableWatch: UnwrapRef<typeof import('@vueuse/core')['pausableWatch']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly provideLocal: UnwrapRef<typeof import('@vueuse/core')['provideLocal']>
readonly reactify: UnwrapRef<typeof import('@vueuse/core')['reactify']>
readonly reactifyObject: UnwrapRef<typeof import('@vueuse/core')['reactifyObject']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
@@ -702,6 +710,7 @@ declare module '@vue/runtime-core' {
readonly useBrowserLocation: UnwrapRef<typeof import('@vueuse/core')['useBrowserLocation']>
readonly useCached: UnwrapRef<typeof import('@vueuse/core')['useCached']>
readonly useClipboard: UnwrapRef<typeof import('@vueuse/core')['useClipboard']>
readonly useClipboardItems: UnwrapRef<typeof import('@vueuse/core')['useClipboardItems']>
readonly useCloned: UnwrapRef<typeof import('@vueuse/core')['useCloned']>
readonly useColorMode: UnwrapRef<typeof import('@vueuse/core')['useColorMode']>
readonly useConfirmDialog: UnwrapRef<typeof import('@vueuse/core')['useConfirmDialog']>
+4 -2
View File
@@ -50,7 +50,7 @@
"@types/markdown-it": "^13.0.7",
"@vicons/material": "^0.12.0",
"@vicons/tabler": "^0.12.0",
"@vueuse/core": "^10.3.0",
"@vueuse/core": "^10.11.1",
"@vueuse/head": "^1.0.0",
"@vueuse/router": "^10.0.0",
"@zxing/library": "^0.21.0",
@@ -75,7 +75,7 @@
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"js-base64": "^3.7.7",
"jsbarcode": "^3.11.7",
"jsbarcode": "^3.11.6",
"json5": "^2.2.3",
"jwt-decode": "^3.1.2",
"libphonenumber-js": "^1.10.28",
@@ -95,6 +95,8 @@
"plausible-tracker": "^0.3.8",
"qrcode": "^1.5.1",
"randexp": "^0.5.3",
"regex": "^4.3.3",
"shiki": "^1.22.0",
"sql-formatter": "^13.0.0",
"sshpk": "^1.18.0",
"ua-parser-js": "^1.0.35",
+32 -1
View File
@@ -1,5 +1,5 @@
// eslint-disable-next-line no-restricted-imports
import { useClipboard } from '@vueuse/core';
import { useClipboard, useClipboardItems } from '@vueuse/core';
import { useMessage } from 'naive-ui';
import type { MaybeRefOrGetter } from 'vue';
@@ -28,3 +28,34 @@ export function useCopy({ source, text = 'Copied to the clipboard', createToast
},
};
}
export function useCopyClipboardItems({ source, text = 'Copied to the clipboard', createToast = true }: { source?: MaybeRefOrGetter<Array<{ mime: string; content: string }>>; text?: string; createToast?: boolean } = {}) {
function toClipboardItem(item: { mime: string; content: string }) {
return new ClipboardItem({
[item.mime]: new Blob([item.content], { type: item.mime }),
});
}
const sourceClipboardItems = computed(() => (toValue(source) || []).map(toClipboardItem));
const { copy, copied, ...rest } = useClipboardItems({
source: sourceClipboardItems,
});
const message = useMessage();
return {
...rest,
isJustCopied: copied,
async copy(content?: { mime: string; content: string }[], { notificationMessage }: { notificationMessage?: string } = {}) {
if (source) {
await copy();
}
else {
await copy((content || []).map(toClipboardItem));
}
if (createToast) {
message.success(notificationMessage ?? text);
}
},
};
}
@@ -0,0 +1,133 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { bundledLanguagesInfo, createHighlighter } from 'shiki/bundle/full';
import { bundledThemesInfo } from 'shiki/themes';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { useCopy, useCopyClipboardItems } from '@/composable/copy';
const code = ref(`// Using 'typeof' to infer types
const person = { name: "Alice", age: 30 };
type PersonType = typeof person; // { name: string; age: number }
// 'satisfies' to ensure a type matches but allows more specific types
type Animal = { name: string };
const dog = { name: "Buddy", breed: "Golden Retriever" } satisfies Animal;
// Generics with 'extends' and default values
function identity<T extends number | string = string>(arg: T): T {
return arg;
}`);
const themes = ref<{ value: string; label: string }[]>(
bundledThemesInfo.map((item) => {
return {
value: item.id,
label: item.displayName,
};
}));
const langs = ref<{ value: string; label: string }[]>(
bundledLanguagesInfo.map(item => ({
value: item.id,
label: item.name,
})));
const currentTheme = useQueryParamOrStorage({ name: 'theme', storageName: 'code-highlighter:theme', defaultValue: 'dark-plus' });
const currentLang = useQueryParamOrStorage({ name: 'lang', storageName: 'code-highlighter:lang', defaultValue: 'typescript' });
const showLineNumbers = ref(false);
const formattedCodeHtml = computedAsync(async () => {
const currentThemeValue = currentTheme.value;
const currentLangValue = currentLang.value;
const codeValue = code.value;
const needLineNumbers = showLineNumbers.value;
const lineNumberWidth = Math.log10(codeValue.split('\n').length) + 2;
const highlighter = await createHighlighter(
{
langs: [currentLangValue],
themes: [currentThemeValue],
});
return highlighter.codeToHtml(codeValue, {
lang: currentLangValue,
theme: currentThemeValue,
transformers: [
{
postprocess(html: string) {
// when copied to clipboard and pasted to LibreOffice,
// formatting of first line is only kept if there is a line break before...
const ensureFirstLineFormattedWhenCopied
= (html: string) => html.replace('<code>', '<code>\n');
if (!needLineNumbers) {
return ensureFirstLineFormattedWhenCopied(html);
}
let lineNumber = 1;
return html.replace(/<span class="line/g, (m) => {
const lineNumberFormatted = (lineNumber++).toString().padStart(lineNumberWidth, ' ');
return `<span class="line-number" style="white-space-collapse: preserve">${lineNumberFormatted} </span>${m}`;
}).replace('<code>', '<code>\n');
},
},
],
});
});
const htmlClipboardItems = computed(() => [{
mime: 'text/html',
content: formattedCodeHtml.value,
}]);
const { copy: copyHtml } = useCopyClipboardItems({ source: htmlClipboardItems });
const { copy: copyText } = useCopy({ source: code });
</script>
<template>
<div>
<div mb-3 flex items-baseline gap-1>
<c-select
v-model:value="currentLang"
label="Language"
label-position="left"
searchable
:options="langs"
flex-1
/>
<c-select
v-model:value="currentTheme"
label="Theme"
label-position="left"
searchable
:options="themes"
flex-1
/>
</div>
<c-input-text
v-model:value="code"
label="Code snippet to format:"
multiline
placeholder="Put your code snippet here"
rows="5"
mb-3
/>
<div flex justify-center gap-2>
<n-form-item label="Show line numbers" label-placement="left">
<n-switch v-model:value="showLineNumbers" />
</n-form-item>
<c-button @click="copyHtml()">
Copy HTML Formatted
</c-button>
<c-button @click="copyText()">
Copy Code Text
</c-button>
</div>
<div v-html="formattedCodeHtml" /><!-- //NOSONAR -->
</div>
</template>
<style scoped>
::v-deep(.line-number) {
text-wrap: nowrap;
}
</style>
+12
View File
@@ -0,0 +1,12 @@
import { Code } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Code/Scripts Highlighter',
path: '/code-highlighter',
description: 'Highlight programming code fragments',
keywords: ['code', 'highlighter'],
component: () => import('./code-highlighter.vue'),
icon: Code,
createdAt: new Date('2024-08-15'),
});
+2
View File
@@ -3,6 +3,7 @@ import { tool as base64StringConverter } from './base64-string-converter';
import { tool as basicAuthGenerator } from './basic-auth-generator';
import { tool as emailNormalizer } from './email-normalizer';
import { tool as bounceParser } from './bounce-parser';
import { tool as codeHighlighter } from './code-highlighter';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
@@ -187,6 +188,7 @@ export const toolsByCategory: ToolCategory[] = [
xmlFormatter,
yamlViewer,
emailNormalizer,
codeHighlighter,
regexTester,
regexMemo,
],
+3
View File
@@ -114,6 +114,9 @@ export default defineConfig({
},
build: {
target: 'esnext',
rollupOptions: {
external: ['regex'],
},
},
optimizeDeps: {
include: ['re2-wasm-embedded'], // optionally specify dependency name