Compare commits

..
Author SHA1 Message Date
sharevb 6fbff77e92 feat(new tool): Math OCR to Latex
FIx #1009
2024-09-01 22:12:31 +02:00
35 changed files with 755 additions and 1360 deletions

No files matched your search

+1 -4
View File
@@ -286,9 +286,6 @@
"watchTriggerable": true,
"watchWithFilter": true,
"whenever": true,
"toValue": true,
"injectLocal": true,
"provideLocal": true,
"useClipboardItems": true
"toValue": true
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

+1 -5
View File
@@ -1,8 +1,4 @@
<picture>
<source srcset="./.github/logo-dark.png" media="(prefers-color-scheme: light)">
<source srcset="./.github/logo-white.png" media="(prefers-color-scheme: dark)">
<img src="./.github/logo-dark.png" alt="logo">
</picture>
![logo](.github/logo.png)
Useful tools for developer and people working in IT. [Have a look !](https://it-tools.tech).
-9
View File
@@ -36,7 +36,6 @@ 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']
@@ -66,7 +65,6 @@ 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']
@@ -130,7 +128,6 @@ 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']
@@ -329,7 +326,6 @@ 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']>
@@ -359,7 +355,6 @@ 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']>
@@ -423,7 +418,6 @@ 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']>
@@ -616,7 +610,6 @@ 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']>
@@ -646,7 +639,6 @@ 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']>
@@ -710,7 +702,6 @@ 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']>
+5 -12
View File
@@ -64,8 +64,6 @@ declare module '@vue/runtime-core' {
'CTextCopyable.demo': typeof import('./src/ui/c-text-copyable/c-text-copyable.demo.vue')['default']
CTooltip: typeof import('./src/ui/c-tooltip/c-tooltip.vue')['default']
'CTooltip.demo': typeof import('./src/ui/c-tooltip/c-tooltip.demo.vue')['default']
DataStorageUnitConverter: typeof import('./src/tools/data-storage-unit-converter/data-storage-unit-converter.vue')['default']
DataTransferRateConverter: typeof import('./src/tools/data-transfer-rate-converter/data-transfer-rate-converter.vue')['default']
DateTimeConverter: typeof import('./src/tools/date-time-converter/date-time-converter.vue')['default']
'DemoHome.page': typeof import('./src/ui/demo/demo-home.page.vue')['default']
DemoWrapper: typeof import('./src/ui/demo/demo-wrapper.vue')['default']
@@ -123,7 +121,6 @@ declare module '@vue/runtime-core' {
LoremIpsumGenerator: typeof import('./src/tools/lorem-ipsum-generator/lorem-ipsum-generator.vue')['default']
MacAddressGenerator: typeof import('./src/tools/mac-address-generator/mac-address-generator.vue')['default']
MacAddressLookup: typeof import('./src/tools/mac-address-lookup/mac-address-lookup.vue')['default']
MarkdownToHtml: typeof import('./src/tools/markdown-to-html/markdown-to-html.vue')['default']
MathEvaluator: typeof import('./src/tools/math-evaluator/math-evaluator.vue')['default']
MenuBar: typeof import('./src/tools/html-wysiwyg-editor/editor/menu-bar.vue')['default']
MenuBarItem: typeof import('./src/tools/html-wysiwyg-editor/editor/menu-bar-item.vue')['default']
@@ -132,23 +129,22 @@ declare module '@vue/runtime-core' {
MetaTagGenerator: typeof import('./src/tools/meta-tag-generator/meta-tag-generator.vue')['default']
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
NButton: typeof import('naive-ui')['NButton']
NCheckbox: typeof import('naive-ui')['NCheckbox']
NCode: typeof import('naive-ui')['NCode']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDivider: typeof import('naive-ui')['NDivider']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NForm: typeof import('naive-ui')['NForm']
NFormItem: typeof import('naive-ui')['NFormItem']
NH1: typeof import('naive-ui')['NH1']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NInput: typeof import('naive-ui')['NInput']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NSpace: typeof import('naive-ui')['NSpace']
NTable: typeof import('naive-ui')['NTable']
NScrollbar: typeof import('naive-ui')['NScrollbar']
NSlider: typeof import('naive-ui')['NSlider']
NSwitch: typeof import('naive-ui')['NSwitch']
NumeronymGenerator: typeof import('./src/tools/numeronym-generator/numeronym-generator.vue')['default']
OtpCodeGeneratorAndValidator: typeof import('./src/tools/otp-code-generator-and-validator/otp-code-generator-and-validator.vue')['default']
PasswordStrengthAnalyser: typeof import('./src/tools/password-strength-analyser/password-strength-analyser.vue')['default']
@@ -158,9 +154,6 @@ declare module '@vue/runtime-core' {
PhoneParserAndFormatter: typeof import('./src/tools/phone-parser-and-formatter/phone-parser-and-formatter.vue')['default']
QrCodeGenerator: typeof import('./src/tools/qr-code-generator/qr-code-generator.vue')['default']
RandomPortGenerator: typeof import('./src/tools/random-port-generator/random-port-generator.vue')['default']
RegexMemo: typeof import('./src/tools/regex-memo/regex-memo.vue')['default']
'RegexMemo.content': typeof import('./src/tools/regex-memo/regex-memo.content.md')['default']
RegexTester: typeof import('./src/tools/regex-tester/regex-tester.vue')['default']
ResultRow: typeof import('./src/tools/ipv4-range-expander/result-row.vue')['default']
RomanNumeralConverter: typeof import('./src/tools/roman-numeral-converter/roman-numeral-converter.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
+2 -5
View File
@@ -35,15 +35,14 @@
"release": "node ./scripts/release.mjs"
},
"dependencies": {
"@huggingface/transformers": "3.0.0-alpha.14",
"@it-tools/bip39": "^0.0.4",
"@it-tools/oggen": "^1.3.0",
"@regexper/render": "^1.0.0",
"@sindresorhus/slugify": "^2.2.1",
"@tiptap/pm": "2.1.6",
"@tiptap/starter-kit": "2.1.6",
"@tiptap/vue-3": "2.0.3",
"@types/figlet": "^1.5.8",
"@types/markdown-it": "^13.0.7",
"@vicons/material": "^0.12.0",
"@vicons/tabler": "^0.12.0",
"@vueuse/core": "^10.3.0",
@@ -72,7 +71,6 @@
"jwt-decode": "^3.1.2",
"libphonenumber-js": "^1.10.28",
"lodash": "^4.17.21",
"markdown-it": "^14.0.0",
"marked": "^10.0.0",
"mathjs": "^11.9.1",
"mime-types": "^2.1.35",
@@ -85,7 +83,6 @@
"pinia": "^2.0.34",
"plausible-tracker": "^0.3.8",
"qrcode": "^1.5.1",
"randexp": "^0.5.3",
"sql-formatter": "^13.0.0",
"ua-parser-js": "^1.0.35",
"ulid": "^2.3.0",
@@ -94,8 +91,8 @@
"uuid": "^9.0.0",
"vue": "^3.3.4",
"vue-i18n": "^9.9.1",
"vue-mathjax-next": "^0.0.6",
"vue-router": "^4.1.6",
"vue-shadow-dom": "^4.2.0",
"vue-tsc": "^1.8.1",
"xml-formatter": "^3.3.2",
"xml-js": "^1.6.11",
+564 -93
View File
File diff suppressed because it is too large. Load diff
-2
View File
@@ -7,7 +7,6 @@ import sqlHljs from 'highlight.js/lib/languages/sql';
import xmlHljs from 'highlight.js/lib/languages/xml';
import yamlHljs from 'highlight.js/lib/languages/yaml';
import iniHljs from 'highlight.js/lib/languages/ini';
import markdownHljs from 'highlight.js/lib/languages/markdown';
import { useCopy } from '@/composable/copy';
const props = withDefaults(
@@ -31,7 +30,6 @@ hljs.registerLanguage('html', xmlHljs);
hljs.registerLanguage('xml', xmlHljs);
hljs.registerLanguage('yaml', yamlHljs);
hljs.registerLanguage('toml', iniHljs);
hljs.registerLanguage('markdown', markdownHljs);
const { value, language, followHeightOf, copyPlacement, copyMessage } = toRefs(props);
const { height } = followHeightOf.value ? useElementSize(followHeightOf) : { height: ref(null) };
+1 -32
View File
@@ -1,8 +1,7 @@
import { useRouteQuery } from '@vueuse/router';
import { computed } from 'vue';
import { useStorage } from '@vueuse/core';
export { useQueryParam, useQueryParamOrStorage };
export { useQueryParam };
const transformers = {
number: {
@@ -17,12 +16,6 @@ const transformers = {
fromQuery: (value: string) => value.toLowerCase() === 'true',
toQuery: (value: boolean) => (value ? 'true' : 'false'),
},
object: {
fromQuery: (value: string) => {
return JSON.parse(value);
},
toQuery: (value: object) => JSON.stringify(value),
},
};
function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue: T }) {
@@ -40,27 +33,3 @@ function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue:
},
});
}
function useQueryParamOrStorage<T>({ name, storageName, defaultValue }: { name: string; storageName: string; defaultValue: T }) {
const type = typeof defaultValue;
const transformer = transformers[type as keyof typeof transformers] ?? transformers.string;
const storageRef = useStorage(storageName, defaultValue);
const proxyDefaultValue = transformer.toQuery(defaultValue as never);
const proxy = useRouteQuery(name, proxyDefaultValue);
const r = ref(defaultValue);
watch(r,
(value) => {
proxy.value = transformer.toQuery(value as never);
storageRef.value = value as never;
},
{ deep: true });
r.value = (proxy.value && proxy.value !== proxyDefaultValue
? transformer.fromQuery(proxy.value) as unknown as T
: storageRef.value as T) as never;
return r;
}
+1 -18
View File
@@ -3,11 +3,9 @@ import _ from 'lodash';
import { type Ref, reactive, watch } from 'vue';
type ValidatorReturnType = unknown;
type GetErrorMessageReturnType = string;
export interface UseValidationRule<T> {
validator: (value: T) => ValidatorReturnType
getErrorMessage?: (value: T) => GetErrorMessageReturnType
message: string
}
@@ -26,15 +24,6 @@ export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
}
}
export function getErrorMessageOrThrown(cb: () => GetErrorMessageReturnType): string {
try {
return cb() || '';
}
catch (e: any) {
return e.toString();
}
}
export interface ValidationAttrs {
feedback: string
validationStatus: string | undefined
@@ -72,13 +61,7 @@ export function useValidation<T>({
for (const rule of get(rules)) {
if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
if (rule.getErrorMessage) {
const getErrorMessage = rule.getErrorMessage;
state.message = rule.message.replace('{0}', getErrorMessageOrThrown(() => getErrorMessage(source.value)));
}
else {
state.message = rule.message;
}
state.message = rule.message;
state.status = 'error';
}
}
-2
View File
@@ -3,7 +3,6 @@ import { createPinia } from 'pinia';
import { createHead } from '@vueuse/head';
import { registerSW } from 'virtual:pwa-register';
import shadow from 'vue-shadow-dom';
import { plausible } from './plugins/plausible.plugin';
import 'virtual:uno.css';
@@ -24,6 +23,5 @@ app.use(i18nPlugin);
app.use(router);
app.use(naive);
app.use(plausible);
app.use(shadow);
app.mount('#app');
@@ -1,54 +0,0 @@
import { describe, expect, it } from 'vitest';
import { convertStorageAndRateUnitsDisplay, displayStorageAndRateUnits } from './data-storage-unit-converter.service';
describe('data-storage-unit-converter', () => {
describe('convertStorageAndRateUnitsDisplay', () => {
it('convert from same base units', () => {
expect(convertStorageAndRateUnitsDisplay({ value: 1024 * 1024, fromUnit: 'B', toUnit: 'MiB' })).toBe('1');
expect(convertStorageAndRateUnitsDisplay({ value: 1024, fromUnit: 'KiB', toUnit: 'MiB' })).toBe('1');
expect(convertStorageAndRateUnitsDisplay({ value: 1, fromUnit: 'MiB', toUnit: 'KiB' })).toBe('1024');
expect(convertStorageAndRateUnitsDisplay({ value: 1000, fromUnit: 'MB', toUnit: 'GB' })).toBe('1');
expect(convertStorageAndRateUnitsDisplay({ value: 1024, fromUnit: 'MB', toUnit: 'MB' })).toBe('1024');
expect(convertStorageAndRateUnitsDisplay({ value: 1, fromUnit: 'MB', toUnit: 'KB' })).toBe('1000');
expect(convertStorageAndRateUnitsDisplay({ value: 1024, fromUnit: 'MiB', toUnit: 'GiB' })).toBe('1');
expect(convertStorageAndRateUnitsDisplay({ value: 1000, fromUnit: 'MB', toUnit: 'GB' })).toBe('1');
expect(convertStorageAndRateUnitsDisplay({ value: 1000, fromUnit: 'Mb', toUnit: 'Gb' })).toBe('1');
});
it('convert between base units', () => {
expect(convertStorageAndRateUnitsDisplay({ value: 1, fromUnit: 'MB', toUnit: 'MiB' })).toBe('0.954');
expect(convertStorageAndRateUnitsDisplay({ value: 1, fromUnit: 'MiB', toUnit: 'MB' })).toBe('1.049');
expect(convertStorageAndRateUnitsDisplay({ value: 1000 * 1000, fromUnit: 'B', toUnit: 'MiB' })).toBe('0.954');
expect(convertStorageAndRateUnitsDisplay({ value: 1024, fromUnit: 'KB', toUnit: 'MiB' })).toBe('0.977');
expect(convertStorageAndRateUnitsDisplay({ value: 1000, fromUnit: 'MiB', toUnit: 'MB' })).toBe('1048.576');
expect(convertStorageAndRateUnitsDisplay({ value: 1, fromUnit: 'MB', toUnit: 'Mb' })).toBe('8');
expect(convertStorageAndRateUnitsDisplay({ value: 1000, fromUnit: 'KB', toUnit: 'Kb' })).toBe('8000');
expect(convertStorageAndRateUnitsDisplay({ value: 1000, fromUnit: 'KiB', toUnit: 'Kb' })).toBe('8192');
expect(convertStorageAndRateUnitsDisplay({ value: 8, fromUnit: 'Mb', toUnit: 'MB' })).toBe('1');
expect(convertStorageAndRateUnitsDisplay({ value: 1, fromUnit: 'Mb', toUnit: 'KB' })).toBe('125');
expect(convertStorageAndRateUnitsDisplay({ value: 125, fromUnit: 'KB', toUnit: 'Mb' })).toBe('1');
expect(convertStorageAndRateUnitsDisplay({ value: 1, fromUnit: 'MiB', toUnit: 'Kb' })).toBe('8388.608');
expect(convertStorageAndRateUnitsDisplay({ value: 8388.608, fromUnit: 'Kb', toUnit: 'MiB' })).toBe('1');
});
it('convert with unit display', () => {
expect(convertStorageAndRateUnitsDisplay({ value: 1024 * 1024, fromUnit: 'B', toUnit: 'MiB', appendUnit: true })).toBe('1MiB');
});
//
});
describe('displayStorageAndRateUnits', () => {
it('convert to correct display value', () => {
expect(displayStorageAndRateUnits({
value: 1.234567, unit: 'MB', appendUnit: false,
})).toBe('1.235');
expect(displayStorageAndRateUnits({
value: 1.234567, unit: 'MB', appendUnit: true,
})).toBe('1.235MB');
expect(displayStorageAndRateUnits({
value: 1.234567, unit: 'MB', appendUnit: true, precision: 5,
})).toBe('1.23457MB');
});
});
});
@@ -1,45 +0,0 @@
export type BibytesUnits = 'iB' | 'KiB' | 'MiB' | 'GiB' | 'TiB' | 'PiB' | 'EiB' | 'ZiB' | 'YiB';
export type BytesUnits = 'B' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB';
export type BitsUnits = 'b' | 'Kb' | 'Mb' | 'Gb' | 'Tb' | 'Pb' | 'Eb' | 'Zb' | 'Yb';
export type AllSupportedUnits = BibytesUnits | BytesUnits | BitsUnits;
export function displayStorageAndRateUnits(
{ value, unit, precision = 3, appendUnit = false }:
{ value: number; unit: AllSupportedUnits; precision?: number ; appendUnit?: boolean }): string {
return value.toFixed(precision).replace(/0+$/, '').replace(/\.$/, '') + (appendUnit ? unit : ''); // NOSONAR
}
export function convertStorageAndRateUnitsDisplay(
{ value, fromUnit, toUnit, precision = 3, appendUnit = false }:
{ value: number; fromUnit: AllSupportedUnits; toUnit: AllSupportedUnits; precision?: number; appendUnit?: boolean }): string {
return displayStorageAndRateUnits({
precision,
unit: toUnit,
appendUnit,
value: convertStorageAndRateUnits({
value, fromUnit, toUnit,
}),
});
}
export function convertStorageAndRateUnits(
{ value, fromUnit, toUnit }:
{ value: number; fromUnit: AllSupportedUnits; toUnit: AllSupportedUnits }): number {
const units = [
'iB', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB',
'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB',
'b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb',
];
const fromIndex = units.indexOf(fromUnit);
const fromFactor = fromIndex / 9 > 1 ? 1000 : 1024;
const fromDivisor = fromIndex / 9 > 2 ? 8 : 1;
const toIndex = units.indexOf(toUnit);
const toFactor = toIndex / 9 > 1 ? 1000 : 1024;
const toDivisor = toIndex / 9 > 2 ? 8 : 1;
const fromBase = (fromFactor ** (fromIndex % 9)) / fromDivisor;
const toBase = (toFactor ** (toIndex % 9)) / toDivisor;
return value * fromBase / toBase;
}
@@ -1,96 +0,0 @@
<script setup lang="ts">
import InputCopyable from '../../components/InputCopyable.vue';
import { type AllSupportedUnits, convertStorageAndRateUnitsDisplay } from './data-storage-unit-converter.service';
const input = ref<{ size: string; unit: string }>({ size: '0', unit: 'KB' });
const output = ref<{ unit: string; precision: number; appendUnit: boolean }>({ unit: 'MB', precision: 3, appendUnit: false });
const allUnits = [
{ value: 'B', label: 'Bytes (B)' },
{ value: 'b', label: 'Bits (bit)' },
{ value: 'iB', label: 'Bibytes (iB)' },
{ value: 'KB', label: 'Kilobytes (KB)' },
{ value: 'Kb', label: 'Kilobits (Kbit)' },
{ value: 'KiB', label: 'Kibibytes (KiB)' },
{ value: 'MB', label: 'Megabytes (MB)' },
{ value: 'Mb', label: 'Megabits (Mbit)' },
{ value: 'MiB', label: 'Mebibytes (MiB)' },
{ value: 'GB', label: 'Gigabytes (GB)' },
{ value: 'Gb', label: 'Gigabits (Gbit)' },
{ value: 'GiB', label: 'Gibibytes (GiB)' },
{ value: 'TB', label: 'Terabytes (TB)' },
{ value: 'Tb', label: 'Terabits (Tbit)' },
{ value: 'TiB', label: 'Tebibytes (TiB)' },
{ value: 'PB', label: 'Petabytes (PB)' },
{ value: 'Pb', label: 'Petabits (Pbit)' },
{ value: 'PiB', label: 'Pebibytes (PiB)' },
{ value: 'EB', label: 'Exabytes (EB)' },
{ value: 'Eb', label: 'Exabits (Ebit)' },
{ value: 'EiB', label: 'Exbibytes (EiB)' },
{ value: 'ZB', label: 'Zettabytes (ZB)' },
{ value: 'Zb', label: 'Zettabits (Zbit)' },
{ value: 'ZiB', label: 'Zebibytes (ZiB)' },
{ value: 'YB', label: 'Yottabytes (YB)' },
{ value: 'Yb', label: 'Yottabits (Ybit)' },
{ value: 'YiB', label: 'Yobibytes (YiB)' },
];
const convertedValue = computed(() => {
try {
return convertStorageAndRateUnitsDisplay({
value: Number(input.value.size),
fromUnit: input.value.unit as AllSupportedUnits,
toUnit: output.value.unit as AllSupportedUnits,
precision: output.value.precision,
appendUnit: output.value.appendUnit,
});
}
catch (e: any) {
return e.toString();
}
});
</script>
<template>
<div>
<c-card>
<n-form-item label="Input Size:" label-placement="left" mb-1>
<c-input-text
v-model:value="input.size"
placeholder="Put your number here (ex: 1024)"
mr-2
/>
<c-select
v-model:value="input.unit"
:options="allUnits"
placeholder="Select input unit"
/>
</n-form-item>
<div flex items-baseline gap-2>
<c-select
v-model:value="output.unit"
label="Output:" label-position="left"
:options="allUnits"
placeholder="Select output unit"
/>
<n-form-item label="Precision:" label-placement="left">
<n-input-number v-model:value="output.precision" style="width:100px" placeholder="Precision..." :max="10" :min="0" />
</n-form-item>
<n-checkbox v-model:checked="output.appendUnit">
Show unit?
</n-checkbox>
</div>
<n-divider />
<InputCopyable
label="Output value"
:value="convertedValue"
placeholder="Output value will be here..."
/>
</c-card>
</div>
</template>
@@ -1,16 +0,0 @@
import { ArrowsLeftRight } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Data Storage Unit converter',
path: '/data-storage-unit-converter',
description: 'Convert data storage or transfer units (bytes, bibytes, bits, kilobytes...)',
keywords: ['data', 'storage', 'unit', 'conversion',
'bits', 'bytes', 'bibytes', 'binary',
'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB',
'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB',
'b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb'],
component: () => import('./data-storage-unit-converter.vue'),
icon: ArrowsLeftRight,
createdAt: new Date('2024-08-15'),
});
@@ -1,47 +0,0 @@
import { describe, expect, it } from 'vitest';
import { amountTransferable, transferSpeedRate, transferTimeSeconds } from './data-transfer-rate-converter.service';
describe('data-transfer-converter', () => {
describe('transferTimeSeconds', () => {
it('compute transfer time in seconds', () => {
expect(transferTimeSeconds({
dataSize: 100,
dataSizeUnit: 'MB',
bitRate: 10,
bitRateUnit: 'Mb',
})).toBe(80);
});
});
describe('transferSpeedRate', () => {
it('compute transferSpeedRate', () => {
expect(transferSpeedRate({
dataSize: 100,
dataSizeUnit: 'MB',
hours: 0,
minutes: 1,
seconds: 20,
bitRateUnit: 'Mb',
})).toBe(10);
expect(transferSpeedRate({
dataSize: 100,
dataSizeUnit: 'MB',
hours: 0,
minutes: 1,
seconds: 20,
bitRateUnit: 'MB',
})).toBe(1.25);
});
});
describe('amountTransferable', () => {
it('compute amount transfered', () => {
expect(amountTransferable({
bitRate: 10,
bitRateUnit: 'Mb',
hours: 1,
minutes: 0,
seconds: 0,
dataSizeUnit: 'MB',
})).toBe(4500);
});
});
});
@@ -1,57 +0,0 @@
import { type AllSupportedUnits, convertStorageAndRateUnits } from '../data-storage-unit-converter/data-storage-unit-converter.service';
export function transferTimeSeconds({
dataSize,
dataSizeUnit,
bitRate,
bitRateUnit,
}: {
dataSize: number
dataSizeUnit: AllSupportedUnits
bitRate: number
bitRateUnit: AllSupportedUnits
}): number {
const dataSizeInBytes = convertStorageAndRateUnits({ value: dataSize, fromUnit: dataSizeUnit, toUnit: 'B' });
const bitRateInBytes = convertStorageAndRateUnits({ value: bitRate, fromUnit: bitRateUnit, toUnit: 'B' });
return bitRateInBytes > 0 ? dataSizeInBytes / bitRateInBytes : 0;
}
export function transferSpeedRate({
dataSize,
dataSizeUnit,
hours,
minutes,
seconds,
bitRateUnit,
}: {
dataSize: number
dataSizeUnit: AllSupportedUnits
hours: number
minutes: number
seconds: number
bitRateUnit: AllSupportedUnits
}): number {
const dataSizeInBits = convertStorageAndRateUnits({ value: dataSize, fromUnit: dataSizeUnit, toUnit: 'b' });
const timeInSeconds = hours * 3600 + minutes * 60 + seconds;
return convertStorageAndRateUnits({ value: timeInSeconds > 0 ? dataSizeInBits / timeInSeconds : 0, fromUnit: 'b', toUnit: bitRateUnit });
}
export function amountTransferable({
bitRate,
bitRateUnit,
hours,
minutes,
seconds,
dataSizeUnit,
}: {
bitRate: number
bitRateUnit: AllSupportedUnits
hours: number
minutes: number
seconds: number
dataSizeUnit: AllSupportedUnits
}): number {
const bitRateInBytes = convertStorageAndRateUnits({ value: bitRate, fromUnit: bitRateUnit, toUnit: 'B' });
const timeInSeconds = hours * 3600 + minutes * 60 + seconds;
return convertStorageAndRateUnits({ value: bitRateInBytes * timeInSeconds, fromUnit: 'B', toUnit: dataSizeUnit });
}
@@ -1,246 +0,0 @@
<script setup lang="ts">
import { formatDuration, intervalToDuration } from 'date-fns';
import { type AllSupportedUnits, displayStorageAndRateUnits } from '../data-storage-unit-converter/data-storage-unit-converter.service';
import { amountTransferable, transferSpeedRate, transferTimeSeconds } from './data-transfer-rate-converter.service';
const allStorateUnits = [
{ value: 'B', label: 'Bytes (B)' },
{ value: 'iB', label: 'Bibytes (iB)' },
{ value: 'KB', label: 'Kilobytes (KB)' },
{ value: 'KiB', label: 'Kibibytes (KiB)' },
{ value: 'MB', label: 'Megabytes (MB)' },
{ value: 'MiB', label: 'Mebibytes (MiB)' },
{ value: 'GB', label: 'Gigabytes (GB)' },
{ value: 'GiB', label: 'Gibibytes (GiB)' },
{ value: 'TB', label: 'Terabytes (TB)' },
{ value: 'TiB', label: 'Tebibytes (TiB)' },
{ value: 'PB', label: 'Petabytes (PB)' },
{ value: 'PiB', label: 'Pebibytes (PiB)' },
{ value: 'EB', label: 'Exabytes (EB)' },
{ value: 'EiB', label: 'Exbibytes (EiB)' },
{ value: 'ZB', label: 'Zettabytes (ZB)' },
{ value: 'ZiB', label: 'Zebibytes (ZiB)' },
{ value: 'YB', label: 'Yottabytes (YB)' },
{ value: 'YiB', label: 'Yobibytes (YiB)' },
];
const allBitsUnits = [
{ value: 'b', label: 'Bits (bit)' },
{ value: 'Kb', label: 'Kilobits (Kbit)' },
{ value: 'Mb', label: 'Megabits (Mbit)' },
{ value: 'Gb', label: 'Gigabits (Gbit)' },
{ value: 'Tb', label: 'Terabits (Tbit)' },
{ value: 'Pb', label: 'Petabits (Pbit)' },
{ value: 'Eb', label: 'Exabits (Ebit)' },
{ value: 'Zb', label: 'Zettabits (Zbit)' },
{ value: 'Yb', label: 'Yottabits (Ybit)' },
];
const allRateUnits = [...allBitsUnits, ...allStorateUnits];
function convertToTimeDisplay(seconds: number) {
if (seconds === 0) {
return '0';
}
return formatDuration(intervalToDuration({ start: 0, end: seconds * 1000 }));
}
const transferTimeInput = ref<{
dataSize: string
dataSizeUnit: string
bitRate: string
bitRateUnit: string
}>({
dataSize: '0',
dataSizeUnit: 'MB',
bitRate: '1',
bitRateUnit: 'Mb',
});
const transferTimeOutput = computed(() => {
try {
return convertToTimeDisplay(transferTimeSeconds({
dataSize: Number(transferTimeInput.value.dataSize),
dataSizeUnit: transferTimeInput.value.dataSizeUnit as AllSupportedUnits,
bitRate: Number(transferTimeInput.value.bitRate),
bitRateUnit: transferTimeInput.value.bitRateUnit as AllSupportedUnits,
}));
}
catch (e: any) {
return e.toString();
}
});
const transferSpeedRateInput = ref<{
dataSize: string
dataSizeUnit: string
hours: number
minutes: number
seconds: number
bitRateUnit: string
}>({
dataSize: '0',
dataSizeUnit: 'GB',
hours: 0,
minutes: 0,
seconds: 0,
bitRateUnit: 'Mb',
});
const transferSpeedRateOutput = computed(() => {
try {
return displayStorageAndRateUnits({
unit: transferSpeedRateInput.value.bitRateUnit as AllSupportedUnits,
appendUnit: true,
value: transferSpeedRate({
dataSize: Number(transferSpeedRateInput.value.dataSize),
dataSizeUnit: transferSpeedRateInput.value.dataSizeUnit as AllSupportedUnits,
hours: transferSpeedRateInput.value.hours,
minutes: transferSpeedRateInput.value.minutes,
seconds: transferSpeedRateInput.value.seconds,
bitRateUnit: transferSpeedRateInput.value.bitRateUnit as AllSupportedUnits,
}),
});
}
catch (e: any) {
return e.toString();
}
});
const amountTransferableInput = ref<{
bitRate: string
bitRateUnit: string
hours: number
minutes: number
seconds: number
dataSizeUnit: string
}>({
bitRate: '0',
bitRateUnit: 'Mb',
hours: 0,
minutes: 0,
seconds: 0,
dataSizeUnit: 'MB',
});
const amountTransferableOutput = computed(() => {
try {
return displayStorageAndRateUnits({
unit: amountTransferableInput.value.dataSizeUnit as AllSupportedUnits,
appendUnit: true,
value: amountTransferable({
bitRate: Number(amountTransferableInput.value.bitRate),
bitRateUnit: amountTransferableInput.value.bitRateUnit as AllSupportedUnits,
hours: amountTransferableInput.value.hours,
minutes: amountTransferableInput.value.minutes,
seconds: amountTransferableInput.value.seconds,
dataSizeUnit: amountTransferableInput.value.dataSizeUnit as AllSupportedUnits,
}),
});
}
catch (e: any) {
return e.toString();
}
});
</script>
<template>
<div>
<c-card title="Transfer Time" mb-2>
<n-form-item label="Data Size:" label-placement="left">
<n-input v-model:value="transferTimeInput.dataSize" placeholder="Data Size..." :min="0" w-full />
<c-select
v-model:value="transferTimeInput.dataSizeUnit"
searchable
:options="allStorateUnits"
placeholder="Select a storage unit"
ml-1
/>
</n-form-item>
<n-form-item label="Bit Rate:" label-placement="left">
<n-input v-model:value="transferTimeInput.bitRate" placeholder="Bit Rate..." :min="0" w-full />
<c-select
v-model:value="transferTimeInput.bitRateUnit"
searchable
:options="allRateUnits"
placeholder="Select a bit rate unit"
ml-1
/>
</n-form-item>
<n-divider />
<InputCopyable
label="Transfer time"
:value="transferTimeOutput"
placeholder="Transfer time will be here..."
/>
</c-card>
<c-card title="Transfer Bit Rate/Speed" mb-2>
<n-form-item label="Data Size:" label-placement="left">
<n-input v-model:value="transferSpeedRateInput.dataSize" placeholder="Data Size..." :min="0" w-full />
<c-select
v-model:value="transferSpeedRateInput.dataSizeUnit"
:options="allStorateUnits"
placeholder="Select a storage unit"
ml-1
/>
</n-form-item>
<n-form-item label="Duration (h/m/s):" label-placement="left">
<n-input-number v-model:value="transferSpeedRateInput.hours" mr-1 placeholder="Hours" :min="0" w-full />
<n-input-number v-model:value="transferSpeedRateInput.minutes" mr-1 placeholder="Minutes" :min="0" w-full />
<n-input-number v-model:value="transferSpeedRateInput.seconds" mr-1 placeholder="Seconds" :min="0" w-full />
</n-form-item>
<n-divider />
<div flex items-baseline gap-2>
<InputCopyable
label="Transfer Bit Rate/Speed:"
label-position="left"
:value="transferSpeedRateOutput"
placeholder="Bit Rate will be here..."
/>
<c-select
v-model:value="transferSpeedRateInput.bitRateUnit"
:options="allRateUnits"
placeholder="Select a bit rate unit"
ml-1
/>
</div>
</c-card>
<c-card title="Amount Transferable" mb-2>
<n-form-item label="Bit Rate:" label-placement="left">
<n-input v-model:value="amountTransferableInput.bitRate" placeholder="Bit Rate..." :min="0" w-full />
<c-select
v-model:value="amountTransferableInput.bitRateUnit"
:options="allRateUnits"
placeholder="Select a bit rate unit"
ml-1
/>
</n-form-item>
<n-form-item label="Duration (h/m/s):" label-placement="left">
<n-input-number v-model:value="amountTransferableInput.hours" mr-1 placeholder="Hours" :min="0" w-full />
<n-input-number v-model:value="amountTransferableInput.minutes" mr-1 placeholder="Minutes" :min="0" w-full />
<n-input-number v-model:value="amountTransferableInput.seconds" mr-1 placeholder="Seconds" :min="0" w-full />
</n-form-item>
<n-divider />
<div flex items-baseline gap-2>
<InputCopyable
label="Amount transferable:"
label-position="left"
:value="amountTransferableOutput"
placeholder="Amount transferable will be here..."
/>
<c-select
v-model:value="amountTransferableInput.dataSizeUnit"
searchable
:options="allStorateUnits"
placeholder="Select a storage unit"
ml-1
/>
</div>
</c-card>
</div>
</template>
@@ -1,12 +0,0 @@
import { TransferIn } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Data Transfer Rate Calculator',
path: '/data-transfer-rate-converter',
description: 'Compute Data Transfer times, rates and amount of data',
keywords: ['data', 'transfer', 'rate', 'convert', 'time'],
component: () => import('./data-transfer-rate-converter.vue'),
icon: TransferIn,
createdAt: new Date('2024-08-15'),
});
+2 -10
View File
@@ -2,8 +2,7 @@ import { tool as base64FileConverter } from './base64-file-converter';
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 dataTransferRateConverter } from './data-transfer-rate-converter';
import { tool as dataStorageUnitConverter } from './data-storage-unit-converter';
import { tool as mathOcr } from './math-ocr';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
@@ -11,9 +10,6 @@ import { tool as textToUnicode } from './text-to-unicode';
import { tool as safelinkDecoder } from './safelink-decoder';
import { tool as xmlToJson } from './xml-to-json';
import { tool as jsonToXml } from './json-to-xml';
import { tool as regexTester } from './regex-tester';
import { tool as regexMemo } from './regex-memo';
import { tool as markdownToHtml } from './markdown-to-html';
import { tool as pdfSignatureChecker } from './pdf-signature-checker';
import { tool as numeronymGenerator } from './numeronym-generator';
import { tool as macAddressGenerator } from './mac-address-generator';
@@ -117,7 +113,6 @@ export const toolsByCategory: ToolCategory[] = [
tomlToYaml,
xmlToJson,
jsonToXml,
markdownToHtml,
],
},
{
@@ -160,8 +155,6 @@ export const toolsByCategory: ToolCategory[] = [
xmlFormatter,
yamlViewer,
emailNormalizer,
regexTester,
regexMemo,
],
},
{
@@ -174,8 +167,7 @@ export const toolsByCategory: ToolCategory[] = [
mathEvaluator,
etaCalculator,
percentageCalculator,
dataTransferRateConverter,
dataStorageUnitConverter,
mathOcr,
],
},
{
-12
View File
@@ -1,12 +0,0 @@
import { Markdown } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Markdown to HTML',
path: '/markdown-to-html',
description: 'Convert Markdown to Html and allow to print (as PDF)',
keywords: ['markdown', 'html', 'converter', 'pdf'],
component: () => import('./markdown-to-html.vue'),
icon: Markdown,
createdAt: new Date('2024-08-25'),
});
@@ -1,44 +0,0 @@
<script setup lang="ts">
import markdownit from 'markdown-it';
import TextareaCopyable from '@/components/TextareaCopyable.vue';
const inputMarkdown = ref('');
const outputHtml = computed(() => {
const md = markdownit();
return md.render(inputMarkdown.value);
});
function printHtml() {
const w = window.open();
if (w === null) {
return;
}
w.document.body.innerHTML = outputHtml.value;
w.print();
}
</script>
<template>
<div>
<c-input-text
v-model:value="inputMarkdown"
multiline raw-text
placeholder="Your Markdown content..."
rows="8"
autofocus
label="Your Markdown to convert:"
/>
<n-divider />
<n-form-item label="Output HTML:">
<TextareaCopyable :value="outputHtml" :word-wrap="true" language="html" />
</n-form-item>
<div flex justify-center>
<n-button @click="printHtml">
Print as PDF
</n-button>
</div>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
import { MathSymbols } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Math OCR',
path: '/math-ocr',
description: 'Convert Math Formula images to Latex',
keywords: ['math', 'ocr', 'latex', 'formula', 'image'],
component: () => import('./math-ocr.vue'),
icon: MathSymbols,
createdAt: new Date('2024-08-15'),
});
+97
View File
@@ -0,0 +1,97 @@
<script setup lang="ts">
import type { Ref } from 'vue';
import { pipeline } from '@huggingface/transformers';
import VueMathjax from 'vue-mathjax-next';
import { useScriptTag } from '@vueuse/core';
import TextareaCopyable from '@/components/TextareaCopyable.vue';
useScriptTag('https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS_HTML');
const ocrInProgress = ref(false);
const fileInput = ref() as Ref<File>;
const latexResult = computedAsync(async () => {
try {
return (await ocr(fileInput.value));
}
catch (e: any) {
return e.toString();
}
});
async function onUpload(file: File) {
if (file) {
fileInput.value = file;
}
}
function toBase64(file: File) {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result?.toString() ?? '');
reader.onerror = error => reject(error);
});
}
type TexifyResult = Array<{ generated_text: string }>;
async function ocr(file: File) {
if (!file) {
return '';
}
ocrInProgress.value = true;
const imgBase64 = await toBase64(file);
const pipe = await pipeline('image-to-text', 'Xenova/texify');
const out: TexifyResult = (await pipe(imgBase64, { max_new_tokens: 384 })) as TexifyResult;
ocrInProgress.value = false;
return out.map(t => t.generated_text).join('\n');
};
</script>
<template>
<div style="max-width: 600px;">
<c-alert type="warning" mb-2>
NB: processing is done in your browser, so be patient, processing can take a while
<br>
This tool required internet connection (to access models)
</c-alert>
<c-file-upload
title="Drag and drop a Image here, or click to select a file"
paste-image
@file-upload="onUpload"
/>
<n-divider />
<div>
<h3>Latex Result</h3>
<TextareaCopyable
v-if="!ocrInProgress"
v-model:value="latexResult"
:word-wrap="true" mb-2
/>
<div style="text-align: center">
<VueMathjax
v-if="!ocrInProgress"
:formula="latexResult"
/>
</div>
<n-spin
v-if="ocrInProgress"
size="small"
/>
</div>
</div>
</template>
<style lang="less" scoped>
::v-deep(.n-upload-trigger) {
width: 100%;
}
</style>
+3
View File
@@ -0,0 +1,3 @@
declare module "vue-mathjax-next" {
}
-12
View File
@@ -1,12 +0,0 @@
import { BrandJavascript } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Regex cheatsheet',
path: '/regex-memo',
description: 'Javascript Regex/Regular Expression cheatsheet',
keywords: ['regex', 'regular', 'expression', 'javascript', 'memo', 'cheatsheet'],
component: () => import('./regex-memo.vue'),
icon: BrandJavascript,
createdAt: new Date('2024-09-20'),
});
-121
View File
@@ -1,121 +0,0 @@
### Normal characters
Expression | Description
:--|:--
`.` or `[^\n\r]` | any character *excluding* a newline or carriage return
`[A-Za-z]` | alphabet
`[a-z]` | lowercase alphabet
`[A-Z]` | uppercase alphabet
`\d` or `[0-9]` | digit
`\D` or `[^0-9]` | non-digit
`_` | underscore
`\w` or `[A-Za-z0-9_]` | alphabet, digit or underscore
`\W` or `[^A-Za-z0-9_]` | inverse of `\w`
`\S` | inverse of `\s`
### Whitespace characters
Expression | Description
:--|:--
` ` | space
`\t` | tab
`\n` | newline
`\r` | carriage return
`\s` | space, tab, newline or carriage return
### Character set
Expression | Description
:--|:--
`[xyz]` | either `x`, `y` or `z`
`[^xyz]` | neither `x`, `y` nor `z`
`[1-3]` | either `1`, `2` or `3`
`[^1-3]` | neither `1`, `2` nor `3`
- Think of a character set as an `OR` operation on the single characters that are enclosed between the square brackets.
- Use `^` after the opening `[` to “negate” the character set.
- Within a character set, `.` means a literal period.
### Characters that require escaping
#### Outside a character set
Expression | Description
:--|:--
`\.` | period
`\^` | caret
`\$` | dollar sign
`\|` | pipe
`\\` | back slash
`\/` | forward slash
`\(` | opening bracket
`\)` | closing bracket
`\[` | opening square bracket
`\]` | closing square bracket
`\{` | opening curly bracket
`\}` | closing curly bracket
#### Inside a character set
Expression | Description
:--|:--
`\\` | back slash
`\]` | closing square bracket
- A `^` must be escaped only if it occurs immediately after the opening `[` of the character set.
- A `-` must be escaped only if it occurs between two alphabets or two digits.
### Quantifiers
Expression | Description
:--|:--
`{2}` | exactly 2
`{2,}` | at least 2
`{2,7}` | at least 2 but no more than 7
`*` | 0 or more
`+` | 1 or more
`?` | exactly 0 or 1
- The quantifier goes *after* the expression to be quantified.
### Boundaries
Expression | Description
:--|:--
`^` | start of string
`$` | end of string
`\b` | word boundary
- How word boundary matching works:
- At the beginning of the string if the first character is `\w`.
- Between two adjacent characters within the string, if the first character is `\w` and the second character is `\W`.
- At the end of the string if the last character is `\w`.
### Matching
Expression | Description
:--|:--
`foo\|bar` | match either `foo` or `bar`
`foo(?=bar)` | match `foo` if it’s before `bar`
`foo(?!bar)` | match `foo` if it’s *not* before `bar`
`(?<=bar)foo` | match `foo` if it’s after `bar`
`(?<!bar)foo` | match `foo` if it’s *not* after `bar`
### Grouping and capturing
Expression | Description
:--|:--
`(foo)` | capturing group; match and capture `foo`
`(?:foo)` | non-capturing group; match `foo` but *without* capturing `foo`
`(foo)bar\1` | `\1` is a backreference to the 1st capturing group; match `foobarfoo`
- Capturing groups are only relevant in the following methods:
- `string.match(regexp)`
- `string.matchAll(regexp)`
- `string.replace(regexp, callback)`
- `\N` is a backreference to the `Nth` capturing group. Capturing groups are numbered starting from 1.
## References and tools
- [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
- [RegExplained](https://leaverou.github.io/regexplained/)
-32
View File
@@ -1,32 +0,0 @@
<script setup lang="ts">
import { useThemeVars } from 'naive-ui';
import Memo from './regex-memo.content.md';
const themeVars = useThemeVars();
</script>
<template>
<div>
<Memo />
</div>
</template>
<style lang="less" scoped>
::v-deep(pre) {
margin: 0;
padding: 15px 22px;
background-color: v-bind('themeVars.cardColor');
border-radius: 4px;
overflow: auto;
}
::v-deep(table) {
border-collapse: collapse;
}
::v-deep(table), ::v-deep(td), ::v-deep(th) {
border: 1px solid v-bind('themeVars.textColor1');
padding: 5px;
}
::v-deep(a) {
color: v-bind('themeVars.textColor1');
}
</style>
-12
View File
@@ -1,12 +0,0 @@
import { Language } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Regex Tester',
path: '/regex-tester',
description: 'Regex Tester',
keywords: ['regex', 'tester', 'sample', 'expression'],
component: () => import('./regex-tester.vue'),
icon: Language,
createdAt: new Date('2024-09-20'),
});
@@ -1,106 +0,0 @@
import { describe, expect, it } from 'vitest';
import { matchRegex } from './regex-tester.service';
const regexesData = [
{
regex: '',
text: '',
flags: '',
result: [],
},
{
regex: '.*',
text: '',
flags: '',
result: [],
},
{
regex: '',
text: 'aaa',
flags: '',
result: [],
},
{
regex: 'a',
text: 'baaa',
flags: '',
result: [
{
captures: [],
groups: [],
index: 1,
value: 'a',
},
],
},
{
regex: '(.)(?<g>r)',
text: 'azertyr',
flags: 'g',
result: [
{
captures: [
{
end: 3,
name: '1',
start: 2,
value: 'e',
},
{
end: 4,
name: '2',
start: 3,
value: 'r',
},
],
groups: [
{
end: 4,
name: 'g',
start: 3,
value: 'r',
},
],
index: 2,
value: 'er',
},
{
captures: [
{
end: 6,
name: '1',
start: 5,
value: 'y',
},
{
end: 7,
name: '2',
start: 6,
value: 'r',
},
],
groups: [
{
end: 7,
name: 'g',
start: 6,
value: 'r',
},
],
index: 5,
value: 'yr',
},
],
},
];
describe('regex-tester', () => {
for (const reg of regexesData) {
const { regex, text, flags, result: expected_result } = reg;
it(`Should matchRegex("${regex}","${text}","${flags}") return correct result`, async () => {
const result = matchRegex(regex, text, `${flags}d`);
expect(result).to.deep.equal(expected_result);
});
}
});
@@ -1,61 +0,0 @@
interface RegExpGroupIndices {
[name: string]: [number, number]
}
interface RegExpIndices extends Array<[number, number]> {
groups: RegExpGroupIndices
}
interface RegExpExecArrayWithIndices extends RegExpExecArray {
indices: RegExpIndices
}
interface GroupCapture {
name: string
value: string
start: number
end: number
};
export function matchRegex(regex: string, text: string, flags: string) {
// if (regex === '' || text === '') {
// return [];
// }
let lastIndex = -1;
const re = new RegExp(regex, flags);
const results = [];
let match = re.exec(text) as RegExpExecArrayWithIndices;
while (match !== null) {
if (re.lastIndex === lastIndex || match[0] === '') {
break;
}
const indices = match.indices;
const captures: Array<GroupCapture> = [];
Object.entries(match).forEach(([captureName, captureValue]) => {
if (captureName !== '0' && captureName.match(/\d+/)) {
captures.push({
name: captureName,
value: captureValue,
start: indices[Number(captureName)][0],
end: indices[Number(captureName)][1],
});
}
});
const groups: Array<GroupCapture> = [];
Object.entries(match.groups || {}).forEach(([groupName, groupValue]) => {
groups.push({
name: groupName,
value: groupValue,
start: indices.groups[groupName][0],
end: indices.groups[groupName][1],
});
});
results.push({
index: match.index,
value: match[0],
captures,
groups,
});
lastIndex = re.lastIndex;
match = re.exec(text) as RegExpExecArrayWithIndices;
}
return results;
}
-193
View File
@@ -1,193 +0,0 @@
<script setup lang="ts">
import RandExp from 'randexp';
import { render } from '@regexper/render';
import type { ShadowRootExpose } from 'vue-shadow-dom';
import { matchRegex } from './regex-tester.service';
import { useValidation } from '@/composable/validation';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const regex = useQueryParamOrStorage({ name: 'regex', storageName: 'regex-tester:regex', defaultValue: '' });
const text = ref('');
const global = ref(true);
const ignoreCase = ref(false);
const multiline = ref(false);
const dotAll = ref(true);
const unicode = ref(true);
const unicodeSets = ref(false);
const visualizerSVG = ref<ShadowRootExpose>();
const regexValidation = useValidation({
source: regex,
rules: [
{
message: 'Invalid regex: {0}',
validator: value => new RegExp(value),
getErrorMessage: (value) => {
const _ = new RegExp(value);
return '';
},
},
],
});
const results = computed(() => {
let flags = 'd';
if (global.value) {
flags += 'g';
}
if (ignoreCase.value) {
flags += 'i';
}
if (multiline.value) {
flags += 'm';
}
if (dotAll.value) {
flags += 's';
}
if (unicode.value) {
flags += 'u';
}
else if (unicodeSets.value) {
flags += 'v';
}
try {
return matchRegex(regex.value, text.value, flags);
}
catch (_) {
return [];
}
});
const sample = computed(() => {
try {
const randexp = new RandExp(new RegExp(regex.value.replace(/\(\?\<[^\>]*\>/g, '(?:')));
return randexp.gen();
}
catch (_) {
return '';
}
});
watchEffect(
async () => {
const regexValue = regex.value;
// shadow root is required:
// @regexper/render append a <defs><style> that broke svg transparency of icons in the whole site
const visualizer = visualizerSVG.value?.shadow_root;
if (visualizer) {
while (visualizer.lastChild) {
visualizer.removeChild(visualizer.lastChild);
}
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
try {
await render(regexValue, svg);
}
catch (_) {
}
visualizer.appendChild(svg);
}
},
);
</script>
<template>
<div max-w-600px>
<c-card title="Regex" mb-1>
<c-input-text
v-model:value="regex"
label="Regex to test:"
placeholder="Put the regex to test"
multiline
rows="3"
:validation="regexValidation"
/>
<router-link target="_blank" to="/regex-memo" mb-1 mt-1>
See Regular Expression Cheatsheet
</router-link>
<n-space>
<n-checkbox v-model:checked="global">
<span title="Global search">Global search. (<code>g</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="ignoreCase">
<span title="Case-insensitive search">Case-insensitive search. (<code>i</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="multiline">
<span title="Allows ^ and $ to match next to newline characters.">Multiline(<code>m</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="dotAll">
<span title="Allows . to match newline characters.">Singleline(<code>s</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="unicode">
<span title="Unicode; treat a pattern as a sequence of Unicode code points.">Unicode(<code>u</code>)</span>
</n-checkbox>
<n-checkbox v-model:checked="unicodeSets">
<span title="An upgrade to the u mode with more Unicode features.">Unicode Sets (<code>v</code>)</span>
</n-checkbox>
</n-space>
<n-divider />
<c-input-text
v-model:value="text"
label="Text to match:"
placeholder="Put the text to match"
multiline
rows="5"
/>
</c-card>
<c-card title="Matches" mb-1 mt-3>
<n-table v-if="results?.length > 0">
<thead>
<tr>
<th scope="col">
Index in text
</th>
<th scope="col">
Value
</th>
<th scope="col">
Captures
</th>
<th scope="col">
Groups
</th>
</tr>
</thead>
<tbody>
<tr v-for="match of results" :key="match.index">
<td>{{ match.index }}</td>
<td>{{ match.value }}</td>
<td>
<ul>
<li v-for="capture in match.captures" :key="capture.name">
"{{ capture.name }}" = {{ capture.value }} [{{ capture.start }} - {{ capture.end }}]
</li>
</ul>
</td>
<td>
<ul>
<li v-for="group in match.groups" :key="group.name">
"{{ group.name }}" = {{ group.value }} [{{ group.start }} - {{ group.end }}]
</li>
</ul>
</td>
</tr>
</tbody>
</n-table>
<c-alert v-else>
No match
</c-alert>
</c-card>
<c-card title="Sample matching text" mt-3>
<pre style="white-space: pre-wrap; word-break: break-all;">{{ sample }}</pre>
</c-card>
<c-card title="Regex Diagram" style="overflow-x: scroll;" mt-3>
<shadow-root ref="visualizerSVG">
&#xa0;
</shadow-root>
</c-card>
</div>
</template>
+66 -2
View File
@@ -5,10 +5,12 @@ const props = withDefaults(defineProps<{
multiple?: boolean
accept?: string
title?: string
pasteImage?: boolean
}>(), {
multiple: false,
accept: undefined,
title: 'Drag and drop files here, or click to select files',
pasteImage: false,
});
const emit = defineEmits<{
@@ -16,11 +18,31 @@ const emit = defineEmits<{
(event: 'fileUpload', file: File): void
}>();
const { multiple } = toRefs(props);
const { multiple, pasteImage } = toRefs(props);
const isOverDropZone = ref(false);
function toBase64(file: File) {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result?.toString() ?? '');
reader.onerror = error => reject(error);
});
}
const fileInput = ref<HTMLInputElement | null>(null);
const imgPreview = ref<HTMLImageElement | null>(null);
async function handlePreview(image: File) {
if (imgPreview.value) {
imgPreview.value.src = await toBase64(image);
}
}
function clearPreview() {
if (imgPreview.value) {
imgPreview.value.src = '';
}
}
function triggerFileInput() {
fileInput.value?.click();
@@ -39,7 +61,30 @@ function handleDrop(event: DragEvent) {
handleUpload(files);
}
function handleUpload(files: FileList | null | undefined) {
async function onPasteImage(evt: ClipboardEvent) {
if (!pasteImage.value) {
return false;
}
const items = evt.clipboardData?.items;
if (!items) {
return false;
}
for (let i = 0; i < items.length; i++) {
if (items[i].type.includes('image')) {
const imageFile = items[i].getAsFile();
if (imageFile) {
await handlePreview(imageFile);
emit('fileUpload', imageFile);
}
}
}
return true;
}
async function handleUpload(files: FileList | null | undefined) {
clearPreview();
if (_.isNil(files) || _.isEmpty(files)) {
return;
}
@@ -49,6 +94,7 @@ function handleUpload(files: FileList | null | undefined) {
return;
}
await handlePreview(files[0]);
emit('fileUpload', files[0]);
}
</script>
@@ -60,6 +106,7 @@ function handleUpload(files: FileList | null | undefined) {
'border-primary border-opacity-100': isOverDropZone,
}"
@click="triggerFileInput"
@paste.prevent="onPasteImage"
@drop.prevent="handleDrop"
@dragover.prevent
@dragenter="isOverDropZone = true"
@@ -73,6 +120,7 @@ function handleUpload(files: FileList | null | undefined) {
:accept="accept"
@change="handleFileInput"
>
<slot>
<span op-70>
{{ title }}
@@ -90,6 +138,22 @@ function handleUpload(files: FileList | null | undefined) {
<c-button>
Browse files
</c-button>
<div v-if="pasteImage">
<!-- separator -->
<div my-4 w-full flex items-center justify-center op-70>
<div class="h-1px max-w-100px flex-1 bg-gray-300 op-50" />
<div class="mx-2 text-gray-400">
or
</div>
<div class="h-1px max-w-100px flex-1 bg-gray-300 op-50" />
</div>
<p>Paste an image from clipboard</p>
</div>
</slot>
<div mt-2>
<img ref="imgPreview" width="150">
</div>
</div>
</template>