mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-28 16:19:48 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63c842bdb3 | ||
|
|
748126f207 |
No files matched your search
Vendored
+3
-8
@@ -72,7 +72,6 @@ declare module '@vue/runtime-core' {
|
|||||||
DockerRunToDockerComposeConverter: typeof import('./src/tools/docker-run-to-docker-compose-converter/docker-run-to-docker-compose-converter.vue')['default']
|
DockerRunToDockerComposeConverter: typeof import('./src/tools/docker-run-to-docker-compose-converter/docker-run-to-docker-compose-converter.vue')['default']
|
||||||
DynamicValues: typeof import('./src/tools/benchmark-builder/dynamic-values.vue')['default']
|
DynamicValues: typeof import('./src/tools/benchmark-builder/dynamic-values.vue')['default']
|
||||||
Editor: typeof import('./src/tools/html-wysiwyg-editor/editor/editor.vue')['default']
|
Editor: typeof import('./src/tools/html-wysiwyg-editor/editor/editor.vue')['default']
|
||||||
EmailNormalizer: typeof import('./src/tools/email-normalizer/email-normalizer.vue')['default']
|
|
||||||
EmojiCard: typeof import('./src/tools/emoji-picker/emoji-card.vue')['default']
|
EmojiCard: typeof import('./src/tools/emoji-picker/emoji-card.vue')['default']
|
||||||
EmojiGrid: typeof import('./src/tools/emoji-picker/emoji-grid.vue')['default']
|
EmojiGrid: typeof import('./src/tools/emoji-picker/emoji-grid.vue')['default']
|
||||||
EmojiPicker: typeof import('./src/tools/emoji-picker/emoji-picker.vue')['default']
|
EmojiPicker: typeof import('./src/tools/emoji-picker/emoji-picker.vue')['default']
|
||||||
@@ -109,9 +108,9 @@ declare module '@vue/runtime-core' {
|
|||||||
Ipv6UlaGenerator: typeof import('./src/tools/ipv6-ula-generator/ipv6-ula-generator.vue')['default']
|
Ipv6UlaGenerator: typeof import('./src/tools/ipv6-ula-generator/ipv6-ula-generator.vue')['default']
|
||||||
JsonDiff: typeof import('./src/tools/json-diff/json-diff.vue')['default']
|
JsonDiff: typeof import('./src/tools/json-diff/json-diff.vue')['default']
|
||||||
JsonMinify: typeof import('./src/tools/json-minify/json-minify.vue')['default']
|
JsonMinify: typeof import('./src/tools/json-minify/json-minify.vue')['default']
|
||||||
|
JsonToCsharp: typeof import('./src/tools/json-to-csharp/json-to-csharp.vue')['default']
|
||||||
JsonToCsv: typeof import('./src/tools/json-to-csv/json-to-csv.vue')['default']
|
JsonToCsv: typeof import('./src/tools/json-to-csv/json-to-csv.vue')['default']
|
||||||
JsonToToml: typeof import('./src/tools/json-to-toml/json-to-toml.vue')['default']
|
JsonToToml: typeof import('./src/tools/json-to-toml/json-to-toml.vue')['default']
|
||||||
JsonToXml: typeof import('./src/tools/json-to-xml/json-to-xml.vue')['default']
|
|
||||||
JsonToYaml: typeof import('./src/tools/json-to-yaml-converter/json-to-yaml.vue')['default']
|
JsonToYaml: typeof import('./src/tools/json-to-yaml-converter/json-to-yaml.vue')['default']
|
||||||
JsonViewer: typeof import('./src/tools/json-viewer/json-viewer.vue')['default']
|
JsonViewer: typeof import('./src/tools/json-viewer/json-viewer.vue')['default']
|
||||||
JwtParser: typeof import('./src/tools/jwt-parser/jwt-parser.vue')['default']
|
JwtParser: typeof import('./src/tools/jwt-parser/jwt-parser.vue')['default']
|
||||||
@@ -129,22 +128,19 @@ declare module '@vue/runtime-core' {
|
|||||||
MetaTagGenerator: typeof import('./src/tools/meta-tag-generator/meta-tag-generator.vue')['default']
|
MetaTagGenerator: typeof import('./src/tools/meta-tag-generator/meta-tag-generator.vue')['default']
|
||||||
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
|
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
|
||||||
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
|
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
|
||||||
|
NCheckbox: typeof import('naive-ui')['NCheckbox']
|
||||||
NCode: typeof import('naive-ui')['NCode']
|
NCode: typeof import('naive-ui')['NCode']
|
||||||
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
|
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
|
||||||
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
|
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
|
||||||
NEllipsis: typeof import('naive-ui')['NEllipsis']
|
NEllipsis: typeof import('naive-ui')['NEllipsis']
|
||||||
NForm: typeof import('naive-ui')['NForm']
|
|
||||||
NFormItem: typeof import('naive-ui')['NFormItem']
|
|
||||||
NH1: typeof import('naive-ui')['NH1']
|
NH1: typeof import('naive-ui')['NH1']
|
||||||
NH3: typeof import('naive-ui')['NH3']
|
NH3: typeof import('naive-ui')['NH3']
|
||||||
NIcon: typeof import('naive-ui')['NIcon']
|
NIcon: typeof import('naive-ui')['NIcon']
|
||||||
NInputNumber: typeof import('naive-ui')['NInputNumber']
|
|
||||||
NLayout: typeof import('naive-ui')['NLayout']
|
NLayout: typeof import('naive-ui')['NLayout']
|
||||||
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
|
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
|
||||||
NMenu: typeof import('naive-ui')['NMenu']
|
NMenu: typeof import('naive-ui')['NMenu']
|
||||||
NScrollbar: typeof import('naive-ui')['NScrollbar']
|
NScrollbar: typeof import('naive-ui')['NScrollbar']
|
||||||
NSlider: typeof import('naive-ui')['NSlider']
|
NSpace: typeof import('naive-ui')['NSpace']
|
||||||
NSwitch: typeof import('naive-ui')['NSwitch']
|
|
||||||
NumeronymGenerator: typeof import('./src/tools/numeronym-generator/numeronym-generator.vue')['default']
|
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']
|
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']
|
PasswordStrengthAnalyser: typeof import('./src/tools/password-strength-analyser/password-strength-analyser.vue')['default']
|
||||||
@@ -186,7 +182,6 @@ declare module '@vue/runtime-core' {
|
|||||||
UuidGenerator: typeof import('./src/tools/uuid-generator/uuid-generator.vue')['default']
|
UuidGenerator: typeof import('./src/tools/uuid-generator/uuid-generator.vue')['default']
|
||||||
WifiQrCodeGenerator: typeof import('./src/tools/wifi-qr-code-generator/wifi-qr-code-generator.vue')['default']
|
WifiQrCodeGenerator: typeof import('./src/tools/wifi-qr-code-generator/wifi-qr-code-generator.vue')['default']
|
||||||
XmlFormatter: typeof import('./src/tools/xml-formatter/xml-formatter.vue')['default']
|
XmlFormatter: typeof import('./src/tools/xml-formatter/xml-formatter.vue')['default']
|
||||||
XmlToJson: typeof import('./src/tools/xml-to-json/xml-to-json.vue')['default']
|
|
||||||
YamlToJson: typeof import('./src/tools/yaml-to-json-converter/yaml-to-json.vue')['default']
|
YamlToJson: typeof import('./src/tools/yaml-to-json-converter/yaml-to-json.vue')['default']
|
||||||
YamlToToml: typeof import('./src/tools/yaml-to-toml/yaml-to-toml.vue')['default']
|
YamlToToml: typeof import('./src/tools/yaml-to-toml/yaml-to-toml.vue')['default']
|
||||||
YamlViewer: typeof import('./src/tools/yaml-viewer/yaml-viewer.vue')['default']
|
YamlViewer: typeof import('./src/tools/yaml-viewer/yaml-viewer.vue')['default']
|
||||||
|
|||||||
+1
-7
@@ -35,7 +35,6 @@
|
|||||||
"release": "node ./scripts/release.mjs"
|
"release": "node ./scripts/release.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@huggingface/transformers": "3.0.0-alpha.14",
|
|
||||||
"@it-tools/bip39": "^0.0.4",
|
"@it-tools/bip39": "^0.0.4",
|
||||||
"@it-tools/oggen": "^1.3.0",
|
"@it-tools/oggen": "^1.3.0",
|
||||||
"@sindresorhus/slugify": "^2.2.1",
|
"@sindresorhus/slugify": "^2.2.1",
|
||||||
@@ -58,7 +57,6 @@
|
|||||||
"crypto-js": "^4.1.1",
|
"crypto-js": "^4.1.1",
|
||||||
"date-fns": "^2.29.3",
|
"date-fns": "^2.29.3",
|
||||||
"dompurify": "^3.0.6",
|
"dompurify": "^3.0.6",
|
||||||
"email-normalizer": "^1.0.0",
|
|
||||||
"emojilib": "^3.0.10",
|
"emojilib": "^3.0.10",
|
||||||
"figlet": "^1.7.0",
|
"figlet": "^1.7.0",
|
||||||
"figue": "^1.2.0",
|
"figue": "^1.2.0",
|
||||||
@@ -66,7 +64,6 @@
|
|||||||
"highlight.js": "^11.7.0",
|
"highlight.js": "^11.7.0",
|
||||||
"iarna-toml-esm": "^3.0.5",
|
"iarna-toml-esm": "^3.0.5",
|
||||||
"ibantools": "^4.3.3",
|
"ibantools": "^4.3.3",
|
||||||
"js-base64": "^3.7.6",
|
|
||||||
"json5": "^2.2.3",
|
"json5": "^2.2.3",
|
||||||
"jwt-decode": "^3.1.2",
|
"jwt-decode": "^3.1.2",
|
||||||
"libphonenumber-js": "^1.10.28",
|
"libphonenumber-js": "^1.10.28",
|
||||||
@@ -91,11 +88,9 @@
|
|||||||
"uuid": "^9.0.0",
|
"uuid": "^9.0.0",
|
||||||
"vue": "^3.3.4",
|
"vue": "^3.3.4",
|
||||||
"vue-i18n": "^9.9.1",
|
"vue-i18n": "^9.9.1",
|
||||||
"vue-mathjax-next": "^0.0.6",
|
|
||||||
"vue-router": "^4.1.6",
|
"vue-router": "^4.1.6",
|
||||||
"vue-tsc": "^1.8.1",
|
"vue-tsc": "^1.8.1",
|
||||||
"xml-formatter": "^3.3.2",
|
"xml-formatter": "^3.3.2",
|
||||||
"xml-js": "^1.6.11",
|
|
||||||
"yaml": "^2.2.1"
|
"yaml": "^2.2.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -142,6 +137,5 @@
|
|||||||
"vitest": "^0.34.0",
|
"vitest": "^0.34.0",
|
||||||
"workbox-window": "^7.0.0",
|
"workbox-window": "^7.0.0",
|
||||||
"zx": "^7.2.1"
|
"zx": "^7.2.1"
|
||||||
},
|
}
|
||||||
"packageManager": "pnpm@8.15.3"
|
|
||||||
}
|
}
|
||||||
Generated
+175
-626
File diff suppressed because it is too large.
Load diff
@@ -48,7 +48,7 @@ const output = computed(() => transformer.value(input.value));
|
|||||||
monospace
|
monospace
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div overflow-auto>
|
<div>
|
||||||
<div mb-5px>
|
<div mb-5px>
|
||||||
{{ outputLabel }}
|
{{ outputLabel }}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
import _ from 'lodash';
|
|
||||||
|
|
||||||
function useDebouncedRef<T>(initialValue: T, delay: number, immediate: boolean = false) {
|
|
||||||
const state = ref(initialValue);
|
|
||||||
const debouncedRef = customRef((track, trigger) => ({
|
|
||||||
get() {
|
|
||||||
track();
|
|
||||||
return state.value;
|
|
||||||
},
|
|
||||||
set: _.debounce(
|
|
||||||
(value) => {
|
|
||||||
state.value = value;
|
|
||||||
trigger();
|
|
||||||
},
|
|
||||||
delay,
|
|
||||||
{ leading: immediate },
|
|
||||||
),
|
|
||||||
}));
|
|
||||||
return debouncedRef;
|
|
||||||
}
|
|
||||||
export default useDebouncedRef;
|
|
||||||
@@ -1,13 +1,8 @@
|
|||||||
import { extension as getExtensionFromMimeType, extension as getMimeTypeFromExtension } from 'mime-types';
|
import { extension as getExtensionFromMime } from 'mime-types';
|
||||||
import type { Ref } from 'vue';
|
import type { Ref } from 'vue';
|
||||||
import _ from 'lodash';
|
import _ from 'lodash';
|
||||||
|
|
||||||
export {
|
export { getMimeTypeFromBase64, useDownloadFileFromBase64 };
|
||||||
getMimeTypeFromBase64,
|
|
||||||
getMimeTypeFromExtension, getExtensionFromMimeType,
|
|
||||||
useDownloadFileFromBase64, useDownloadFileFromBase64Refs,
|
|
||||||
previewImageFromBase64,
|
|
||||||
};
|
|
||||||
|
|
||||||
const commonMimeTypesSignatures = {
|
const commonMimeTypesSignatures = {
|
||||||
'JVBERi0': 'application/pdf',
|
'JVBERi0': 'application/pdf',
|
||||||
@@ -41,78 +36,30 @@ function getFileExtensionFromMimeType({
|
|||||||
defaultExtension?: string
|
defaultExtension?: string
|
||||||
}) {
|
}) {
|
||||||
if (mimeType) {
|
if (mimeType) {
|
||||||
return getExtensionFromMimeType(mimeType) ?? defaultExtension;
|
return getExtensionFromMime(mimeType) ?? defaultExtension;
|
||||||
}
|
}
|
||||||
|
|
||||||
return defaultExtension;
|
return defaultExtension;
|
||||||
}
|
}
|
||||||
|
|
||||||
function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
|
function useDownloadFileFromBase64({ source, filename }: { source: Ref<string>; filename?: string }) {
|
||||||
{ sourceValue: string; filename?: string; extension?: string; fileMimeType?: string }) {
|
|
||||||
if (sourceValue === '') {
|
|
||||||
throw new Error('Base64 string is empty');
|
|
||||||
}
|
|
||||||
|
|
||||||
const defaultExtension = extension ?? 'txt';
|
|
||||||
const { mimeType } = getMimeTypeFromBase64({ base64String: sourceValue });
|
|
||||||
let base64String = sourceValue;
|
|
||||||
if (!mimeType) {
|
|
||||||
const targetMimeType = fileMimeType ?? getMimeTypeFromExtension(defaultExtension);
|
|
||||||
base64String = `data:${targetMimeType};base64,${sourceValue}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cleanExtension = extension ?? getFileExtensionFromMimeType(
|
|
||||||
{ mimeType, defaultExtension });
|
|
||||||
let cleanFileName = filename ?? `file.${cleanExtension}`;
|
|
||||||
if (extension && !cleanFileName.endsWith(`.${extension}`)) {
|
|
||||||
cleanFileName = `${cleanFileName}.${cleanExtension}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const a = document.createElement('a');
|
|
||||||
a.href = base64String;
|
|
||||||
a.download = cleanFileName;
|
|
||||||
a.click();
|
|
||||||
}
|
|
||||||
|
|
||||||
function useDownloadFileFromBase64(
|
|
||||||
{ source, filename, extension, fileMimeType }:
|
|
||||||
{ source: Ref<string>; filename?: string; extension?: string; fileMimeType?: string }) {
|
|
||||||
return {
|
return {
|
||||||
download() {
|
download() {
|
||||||
downloadFromBase64({ sourceValue: source.value, filename, extension, fileMimeType });
|
if (source.value === '') {
|
||||||
|
throw new Error('Base64 string is empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { mimeType } = getMimeTypeFromBase64({ base64String: source.value });
|
||||||
|
const base64String = mimeType
|
||||||
|
? source.value
|
||||||
|
: `data:text/plain;base64,${source.value}`;
|
||||||
|
|
||||||
|
const cleanFileName = filename ?? `file.${getFileExtensionFromMimeType({ mimeType })}`;
|
||||||
|
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = base64String;
|
||||||
|
a.download = cleanFileName;
|
||||||
|
a.click();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function useDownloadFileFromBase64Refs(
|
|
||||||
{ source, filename, extension }:
|
|
||||||
{ source: Ref<string>; filename?: Ref<string>; extension?: Ref<string> }) {
|
|
||||||
return {
|
|
||||||
download() {
|
|
||||||
downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value });
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function previewImageFromBase64(base64String: string): HTMLImageElement {
|
|
||||||
if (base64String === '') {
|
|
||||||
throw new Error('Base64 string is empty');
|
|
||||||
}
|
|
||||||
|
|
||||||
const img = document.createElement('img');
|
|
||||||
img.src = base64String;
|
|
||||||
|
|
||||||
const container = document.createElement('div');
|
|
||||||
container.appendChild(img);
|
|
||||||
|
|
||||||
const previewContainer = document.getElementById('previewContainer');
|
|
||||||
if (previewContainer) {
|
|
||||||
previewContainer.innerHTML = '';
|
|
||||||
previewContainer.appendChild(container);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new Error('Preview container element not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
return img;
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useRouteQuery } from '@vueuse/router';
|
import { useRouteQuery } from '@vueuse/router';
|
||||||
import { computed } from 'vue';
|
import { computed } from 'vue';
|
||||||
|
import { useStorage } from '@vueuse/core';
|
||||||
|
|
||||||
export { useQueryParam };
|
export { useQueryParam, useQueryParamOrStorage };
|
||||||
|
|
||||||
const transformers = {
|
const transformers = {
|
||||||
number: {
|
number: {
|
||||||
@@ -16,6 +17,12 @@ const transformers = {
|
|||||||
fromQuery: (value: string) => value.toLowerCase() === 'true',
|
fromQuery: (value: string) => value.toLowerCase() === 'true',
|
||||||
toQuery: (value: boolean) => (value ? 'true' : 'false'),
|
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 }) {
|
function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue: T }) {
|
||||||
@@ -33,3 +40,27 @@ 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;
|
||||||
|
}
|
||||||
@@ -2,19 +2,12 @@
|
|||||||
import { useBase64 } from '@vueuse/core';
|
import { useBase64 } from '@vueuse/core';
|
||||||
import type { Ref } from 'vue';
|
import type { Ref } from 'vue';
|
||||||
import { useCopy } from '@/composable/copy';
|
import { useCopy } from '@/composable/copy';
|
||||||
import { getExtensionFromMimeType, getMimeTypeFromBase64, previewImageFromBase64, useDownloadFileFromBase64Refs } from '@/composable/downloadBase64';
|
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';
|
||||||
import { useValidation } from '@/composable/validation';
|
import { useValidation } from '@/composable/validation';
|
||||||
import { isValidBase64 } from '@/utils/base64';
|
import { isValidBase64 } from '@/utils/base64';
|
||||||
|
|
||||||
const fileName = ref('file');
|
|
||||||
const fileExtension = ref('');
|
|
||||||
const base64Input = ref('');
|
const base64Input = ref('');
|
||||||
const { download } = useDownloadFileFromBase64Refs(
|
const { download } = useDownloadFileFromBase64({ source: base64Input });
|
||||||
{
|
|
||||||
source: base64Input,
|
|
||||||
filename: fileName,
|
|
||||||
extension: fileExtension,
|
|
||||||
});
|
|
||||||
const base64InputValidation = useValidation({
|
const base64InputValidation = useValidation({
|
||||||
source: base64Input,
|
source: base64Input,
|
||||||
rules: [
|
rules: [
|
||||||
@@ -25,35 +18,6 @@ const base64InputValidation = useValidation({
|
|||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
watch(
|
|
||||||
base64Input,
|
|
||||||
(newValue, _) => {
|
|
||||||
const { mimeType } = getMimeTypeFromBase64({ base64String: newValue });
|
|
||||||
if (mimeType) {
|
|
||||||
fileExtension.value = getExtensionFromMimeType(mimeType) || fileExtension.value;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
function previewImage() {
|
|
||||||
if (!base64InputValidation.isValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const image = previewImageFromBase64(base64Input.value);
|
|
||||||
image.style.maxWidth = '100%';
|
|
||||||
image.style.maxHeight = '400px';
|
|
||||||
const previewContainer = document.getElementById('previewContainer');
|
|
||||||
if (previewContainer) {
|
|
||||||
previewContainer.innerHTML = '';
|
|
||||||
previewContainer.appendChild(image);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (_) {
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function downloadFile() {
|
function downloadFile() {
|
||||||
if (!base64InputValidation.isValid) {
|
if (!base64InputValidation.isValid) {
|
||||||
return;
|
return;
|
||||||
@@ -80,24 +44,6 @@ async function onUpload(file: File) {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<c-card title="Base64 to file">
|
<c-card title="Base64 to file">
|
||||||
<n-grid cols="3" x-gap="12">
|
|
||||||
<n-gi span="2">
|
|
||||||
<c-input-text
|
|
||||||
v-model:value="fileName"
|
|
||||||
label="File Name"
|
|
||||||
placeholder="Download filename"
|
|
||||||
mb-2
|
|
||||||
/>
|
|
||||||
</n-gi>
|
|
||||||
<n-gi>
|
|
||||||
<c-input-text
|
|
||||||
v-model:value="fileExtension"
|
|
||||||
label="Extension"
|
|
||||||
placeholder="Extension"
|
|
||||||
mb-2
|
|
||||||
/>
|
|
||||||
</n-gi>
|
|
||||||
</n-grid>
|
|
||||||
<c-input-text
|
<c-input-text
|
||||||
v-model:value="base64Input"
|
v-model:value="base64Input"
|
||||||
multiline
|
multiline
|
||||||
@@ -107,14 +53,7 @@ async function onUpload(file: File) {
|
|||||||
mb-2
|
mb-2
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div flex justify-center py-2>
|
<div flex justify-center>
|
||||||
<div id="previewContainer" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div flex justify-center gap-3>
|
|
||||||
<c-button :disabled="base64Input === '' || !base64InputValidation.isValid" @click="previewImage()">
|
|
||||||
Preview image
|
|
||||||
</c-button>
|
|
||||||
<c-button :disabled="base64Input === '' || !base64InputValidation.isValid" @click="downloadFile()">
|
<c-button :disabled="base64Input === '' || !base64InputValidation.isValid" @click="downloadFile()">
|
||||||
Download file
|
Download file
|
||||||
</c-button>
|
</c-button>
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { normalizeEmail } from 'email-normalizer';
|
|
||||||
import { withDefaultOnError } from '@/utils/defaults';
|
|
||||||
import { useCopy } from '@/composable/copy';
|
|
||||||
|
|
||||||
const emails = ref('');
|
|
||||||
const normalizedEmails = computed(() => {
|
|
||||||
if (!emails.value) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
return emails.value
|
|
||||||
.split('\n')
|
|
||||||
.map((email) => {
|
|
||||||
return withDefaultOnError(() => normalizeEmail({ email }), `Unable to parse email: ${email}`);
|
|
||||||
})
|
|
||||||
.join('\n');
|
|
||||||
});
|
|
||||||
|
|
||||||
const { copy } = useCopy({ source: normalizedEmails, text: 'Normalized emails copied to the clipboard', createToast: true });
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div>
|
|
||||||
<div class="mb-2">
|
|
||||||
Raw emails to normalize:
|
|
||||||
</div>
|
|
||||||
<c-input-text
|
|
||||||
v-model:value="emails"
|
|
||||||
placeholder="Put your emails here (one per line)..."
|
|
||||||
rows="3"
|
|
||||||
multiline
|
|
||||||
autocomplete="off"
|
|
||||||
autocorrect="off"
|
|
||||||
autocapitalize="off"
|
|
||||||
spellcheck="false"
|
|
||||||
autofocus
|
|
||||||
monospace
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div class="mb-2 mt-4">
|
|
||||||
Normalized emails:
|
|
||||||
</div>
|
|
||||||
<c-input-text
|
|
||||||
:value="normalizedEmails"
|
|
||||||
placeholder="Normalized emails will appear here..."
|
|
||||||
rows="3"
|
|
||||||
autocomplete="off"
|
|
||||||
autocorrect="off"
|
|
||||||
autocapitalize="off"
|
|
||||||
spellcheck="false"
|
|
||||||
multiline
|
|
||||||
readonly
|
|
||||||
monospace
|
|
||||||
/>
|
|
||||||
<div class="mt-4 flex justify-center gap-2">
|
|
||||||
<c-button @click="emails = ''">
|
|
||||||
Clear emails
|
|
||||||
</c-button>
|
|
||||||
<c-button :disabled="!normalizedEmails" @click="copy()">
|
|
||||||
Copy normalized emails
|
|
||||||
</c-button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { Mail } from '@vicons/tabler';
|
|
||||||
import { defineTool } from '../tool';
|
|
||||||
|
|
||||||
export const tool = defineTool({
|
|
||||||
name: 'Email normalizer',
|
|
||||||
path: '/email-normalizer',
|
|
||||||
description: 'Normalize email addresses to a standard format for easier comparison. Useful for deduplication and data cleaning.',
|
|
||||||
keywords: ['email', 'normalizer'],
|
|
||||||
component: () => import('./email-normalizer.vue'),
|
|
||||||
icon: Mail,
|
|
||||||
createdAt: new Date('2024-08-15'),
|
|
||||||
});
|
|
||||||
@@ -4,7 +4,6 @@ import emojiKeywords from 'emojilib';
|
|||||||
import _ from 'lodash';
|
import _ from 'lodash';
|
||||||
import type { EmojiInfo } from './emoji.types';
|
import type { EmojiInfo } from './emoji.types';
|
||||||
import { useFuzzySearch } from '@/composable/fuzzySearch';
|
import { useFuzzySearch } from '@/composable/fuzzySearch';
|
||||||
import useDebouncedRef from '@/composable/debouncedref';
|
|
||||||
|
|
||||||
const escapeUnicode = ({ emoji }: { emoji: string }) => emoji.split('').map(unit => `\\u${unit.charCodeAt(0).toString(16).padStart(4, '0')}`).join('');
|
const escapeUnicode = ({ emoji }: { emoji: string }) => emoji.split('').map(unit => `\\u${unit.charCodeAt(0).toString(16).padStart(4, '0')}`).join('');
|
||||||
const getEmojiCodePoints = ({ emoji }: { emoji: string }) => emoji.codePointAt(0) ? `0x${emoji.codePointAt(0)?.toString(16)}` : undefined;
|
const getEmojiCodePoints = ({ emoji }: { emoji: string }) => emoji.codePointAt(0) ? `0x${emoji.codePointAt(0)?.toString(16)}` : undefined;
|
||||||
@@ -24,7 +23,7 @@ const emojisGroups: { emojiInfos: EmojiInfo[]; group: string }[] = _
|
|||||||
.map((emojiInfos, group) => ({ group, emojiInfos }))
|
.map((emojiInfos, group) => ({ group, emojiInfos }))
|
||||||
.value();
|
.value();
|
||||||
|
|
||||||
const searchQuery = useDebouncedRef('', 500);
|
const searchQuery = ref('');
|
||||||
|
|
||||||
const { searchResult } = useFuzzySearch({
|
const { searchResult } = useFuzzySearch({
|
||||||
search: searchQuery,
|
search: searchQuery,
|
||||||
|
|||||||
+3
-13
@@ -1,15 +1,12 @@
|
|||||||
import { tool as base64FileConverter } from './base64-file-converter';
|
import { tool as base64FileConverter } from './base64-file-converter';
|
||||||
import { tool as base64StringConverter } from './base64-string-converter';
|
import { tool as base64StringConverter } from './base64-string-converter';
|
||||||
import { tool as basicAuthGenerator } from './basic-auth-generator';
|
import { tool as basicAuthGenerator } from './basic-auth-generator';
|
||||||
import { tool as emailNormalizer } from './email-normalizer';
|
import { tool as jsonToCsharp } from './json-to-csharp';
|
||||||
import { tool as mathOcr } from './math-ocr';
|
|
||||||
|
|
||||||
import { tool as asciiTextDrawer } from './ascii-text-drawer';
|
import { tool as asciiTextDrawer } from './ascii-text-drawer';
|
||||||
|
|
||||||
import { tool as textToUnicode } from './text-to-unicode';
|
import { tool as textToUnicode } from './text-to-unicode';
|
||||||
import { tool as safelinkDecoder } from './safelink-decoder';
|
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 pdfSignatureChecker } from './pdf-signature-checker';
|
import { tool as pdfSignatureChecker } from './pdf-signature-checker';
|
||||||
import { tool as numeronymGenerator } from './numeronym-generator';
|
import { tool as numeronymGenerator } from './numeronym-generator';
|
||||||
import { tool as macAddressGenerator } from './mac-address-generator';
|
import { tool as macAddressGenerator } from './mac-address-generator';
|
||||||
@@ -111,8 +108,7 @@ export const toolsByCategory: ToolCategory[] = [
|
|||||||
listConverter,
|
listConverter,
|
||||||
tomlToJson,
|
tomlToJson,
|
||||||
tomlToYaml,
|
tomlToYaml,
|
||||||
xmlToJson,
|
jsonToCsharp,
|
||||||
jsonToXml,
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -154,7 +150,6 @@ export const toolsByCategory: ToolCategory[] = [
|
|||||||
dockerRunToDockerComposeConverter,
|
dockerRunToDockerComposeConverter,
|
||||||
xmlFormatter,
|
xmlFormatter,
|
||||||
yamlViewer,
|
yamlViewer,
|
||||||
emailNormalizer,
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -163,12 +158,7 @@ export const toolsByCategory: ToolCategory[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Math',
|
name: 'Math',
|
||||||
components: [
|
components: [mathEvaluator, etaCalculator, percentageCalculator],
|
||||||
mathEvaluator,
|
|
||||||
etaCalculator,
|
|
||||||
percentageCalculator,
|
|
||||||
mathOcr,
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Measurement',
|
name: 'Measurement',
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { CSharp } from '@vicons/tabler';
|
||||||
|
import { defineTool } from '../tool';
|
||||||
|
|
||||||
|
export const tool = defineTool({
|
||||||
|
name: 'JSON to C#',
|
||||||
|
path: '/json-to-csharp',
|
||||||
|
description: 'Convert JSON data to C# type definition',
|
||||||
|
keywords: ['json', 'c#', 'csharp'],
|
||||||
|
component: () => import('./json-to-csharp.vue'),
|
||||||
|
icon: CSharp,
|
||||||
|
createdAt: new Date('2024-05-11'),
|
||||||
|
});
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import JSON5 from 'json5';
|
||||||
|
import json2csharp from './json2csharp';
|
||||||
|
import type { UseValidationRule } from '@/composable/validation';
|
||||||
|
import TextareaCopyable from '@/components/TextareaCopyable.vue';
|
||||||
|
import { withDefaultOnError } from '@/utils/defaults';
|
||||||
|
import { useQueryParamOrStorage } from '@/composable/queryParams';
|
||||||
|
|
||||||
|
const defaultValue = `{
|
||||||
|
a:"n",
|
||||||
|
arr: [1, 2],
|
||||||
|
nested: {
|
||||||
|
a:1,
|
||||||
|
b:"2"
|
||||||
|
}
|
||||||
|
}`;
|
||||||
|
const jsonInput = ref(defaultValue);
|
||||||
|
const pascalCase = useQueryParamOrStorage({ name: 'pascalcase', storageName: 'json-c#:pc', defaultValue: true });
|
||||||
|
const useFields = useQueryParamOrStorage({ name: 'fields', storageName: 'json-c#:fi', defaultValue: false });
|
||||||
|
const useNullable = useQueryParamOrStorage({ name: 'nullable', storageName: 'json-c#:null', defaultValue: false });
|
||||||
|
const addJsonProperty = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:jsp', defaultValue: false });
|
||||||
|
const nullValueHandlingIgnore = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:ign', defaultValue: true });
|
||||||
|
const addJsonPropertyName = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:jspp', defaultValue: true });
|
||||||
|
const generateImmutableClasses = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:imm', defaultValue: false });
|
||||||
|
const useRecordTypes = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:rec', defaultValue: true });
|
||||||
|
const useReadonlyLists = useQueryParamOrStorage({ name: 'pascal', storageName: 'json-c#:rdl', defaultValue: false });
|
||||||
|
const rootTypeName = useQueryParamOrStorage({ name: 'root', storageName: 'json-c#:rt', defaultValue: 'Root' });
|
||||||
|
|
||||||
|
const csharpOutput = computed(() => withDefaultOnError(
|
||||||
|
() => json2csharp({
|
||||||
|
src: JSON5.parse(jsonInput.value),
|
||||||
|
rootTypeName: rootTypeName.value,
|
||||||
|
pascalCase: pascalCase.value,
|
||||||
|
useFields: useFields.value,
|
||||||
|
useNullable: useNullable.value,
|
||||||
|
addJsonProperty: addJsonProperty.value,
|
||||||
|
nullValueHandlingIgnore: nullValueHandlingIgnore.value,
|
||||||
|
addJsonPropertyName: addJsonPropertyName.value,
|
||||||
|
generateImmutableClasses: generateImmutableClasses.value,
|
||||||
|
useRecordTypes: useRecordTypes.value,
|
||||||
|
useReadonlyLists: useReadonlyLists.value,
|
||||||
|
}), ''));
|
||||||
|
const rules: UseValidationRule<string>[] = [
|
||||||
|
{
|
||||||
|
validator: (v: string) => v === '' || JSON5.parse(v),
|
||||||
|
message: 'Provided JSON is not valid.',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<c-card title="JSON to C#">
|
||||||
|
<c-input-text
|
||||||
|
v-model:value="jsonInput"
|
||||||
|
multiline
|
||||||
|
placeholder="Put your json string here..."
|
||||||
|
rows="10"
|
||||||
|
label="JSON to C#"
|
||||||
|
:validation-rules="rules"
|
||||||
|
raw-text
|
||||||
|
mb-5
|
||||||
|
/>
|
||||||
|
<n-space justify="center">
|
||||||
|
<n-checkbox v-model:checked="pascalCase">
|
||||||
|
Use Pascal case
|
||||||
|
</n-checkbox>
|
||||||
|
<n-checkbox v-model:checked="useRecordTypes">
|
||||||
|
Use Record types
|
||||||
|
</n-checkbox>
|
||||||
|
<n-checkbox v-model:checked="generateImmutableClasses">
|
||||||
|
Generate Immutable classes
|
||||||
|
</n-checkbox>
|
||||||
|
<n-checkbox v-model:checked="useFields">
|
||||||
|
Use fields
|
||||||
|
</n-checkbox>
|
||||||
|
<n-checkbox v-model:checked="addJsonProperty">
|
||||||
|
Add JsonProperty attributes
|
||||||
|
</n-checkbox>
|
||||||
|
<n-checkbox v-model:checked="nullValueHandlingIgnore" :disabled="!addJsonProperty">
|
||||||
|
Use NullValueHandling.Ignore
|
||||||
|
</n-checkbox>
|
||||||
|
<n-checkbox v-model:checked="addJsonPropertyName">
|
||||||
|
Add JsonPropertyName attributes
|
||||||
|
</n-checkbox>
|
||||||
|
<n-checkbox v-model:checked="useNullable">
|
||||||
|
Use nullable types
|
||||||
|
</n-checkbox>
|
||||||
|
<n-checkbox v-model:checked="useReadonlyLists">
|
||||||
|
Use Readonly lists
|
||||||
|
</n-checkbox>
|
||||||
|
</n-space>
|
||||||
|
<c-input-text v-model:value="rootTypeName" label="Root type name" placeholder="Your root type name..." clearable raw-text mb-5 />
|
||||||
|
</c-card>
|
||||||
|
<c-card title="Your C# code" mt-2>
|
||||||
|
<TextareaCopyable
|
||||||
|
:value="csharpOutput"
|
||||||
|
language="csharp"
|
||||||
|
/>
|
||||||
|
</c-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,617 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { getPrimitiveProp, isDate, json2classes, json2csharp } from './json2csharp';
|
||||||
|
|
||||||
|
// Test isDate function
|
||||||
|
describe('isDate', () => {
|
||||||
|
it('should return true for valid date strings', () => {
|
||||||
|
expect(isDate('2024-03-08')).toBe(true);
|
||||||
|
expect(isDate('2024-03-08T12:34:56Z')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false for invalid date strings', () => {
|
||||||
|
expect(isDate('hello')).toBe(false);
|
||||||
|
expect(isDate('2024-13-08')).toBe(false); // Invalid month
|
||||||
|
expect(isDate('9999-99-99')).toBe(false); // Invalid format
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test getPrimitiveProp function
|
||||||
|
describe('getPrimitiveProp', () => {
|
||||||
|
it('should return \'string\' type for non-date strings', () => {
|
||||||
|
expect(getPrimitiveProp('hello', 'testKey')).toEqual({
|
||||||
|
type: 'string',
|
||||||
|
name: 'testKey',
|
||||||
|
canBeNullable: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return \'DateTime\' type for date strings', () => {
|
||||||
|
expect(getPrimitiveProp('2024-03-08', 'dateKey')).toEqual({
|
||||||
|
type: 'DateTime',
|
||||||
|
name: 'dateKey',
|
||||||
|
canBeNullable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return \'int\' for integers', () => {
|
||||||
|
expect(getPrimitiveProp(42, 'numberKey')).toEqual({
|
||||||
|
type: 'int',
|
||||||
|
name: 'numberKey',
|
||||||
|
canBeNullable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return \'double\' for floating point numbers', () => {
|
||||||
|
expect(getPrimitiveProp(3.14, 'floatKey')).toEqual({
|
||||||
|
type: 'double',
|
||||||
|
name: 'floatKey',
|
||||||
|
canBeNullable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return \'bool\' for boolean values', () => {
|
||||||
|
expect(getPrimitiveProp(true, 'boolKey')).toEqual({
|
||||||
|
type: 'bool',
|
||||||
|
name: 'boolKey',
|
||||||
|
canBeNullable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw an error for unsupported types', () => {
|
||||||
|
expect(() => getPrimitiveProp({}, 'objKey')).toThrow('Unexpected key \'objKey\' of type object');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test json2classes function
|
||||||
|
describe('json2classes', () => {
|
||||||
|
it('should convert JSON to class definitions with custom root', () => {
|
||||||
|
const json = { name: 'John', age: 30 };
|
||||||
|
const result = json2classes(json, 'Main');
|
||||||
|
expect(result).to.deep.eq([
|
||||||
|
{
|
||||||
|
key: 'Main',
|
||||||
|
props: [
|
||||||
|
{ type: 'string', name: 'name', canBeNullable: false },
|
||||||
|
{ type: 'int', name: 'age', canBeNullable: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle nested objects', () => {
|
||||||
|
const json = { user: { name: 'John' } };
|
||||||
|
const result = json2classes(json);
|
||||||
|
expect(result).to.deep.eq([
|
||||||
|
{ key: 'Root', props: [{ type: 'User', name: 'user' }] },
|
||||||
|
{ key: 'User', props: [{ type: 'string', name: 'name', canBeNullable: false }] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle arrays of primitives', () => {
|
||||||
|
const json = { numbers: [1, 2, 3] };
|
||||||
|
const result = json2classes(json);
|
||||||
|
expect(result).to.deep.eq([
|
||||||
|
{ key: 'Root', props: [{ type: 'int', name: 'numbers', isArray: true, canBeNullable: true }] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle arrays of objects', () => {
|
||||||
|
const json = { users: [{ name: 'John' }, { name: 'Jane' }] };
|
||||||
|
const result = json2classes(json);
|
||||||
|
expect(result).to.deep.eq([
|
||||||
|
{ key: 'Root', props: [{ type: 'UsersItem', name: 'users', isArray: true }] },
|
||||||
|
{ key: 'UsersItem', props: [{ type: 'string', name: 'name', canBeNullable: false }] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test json2csharp function
|
||||||
|
describe('json2csharp', () => {
|
||||||
|
const cleanTabs = (s: string) => s.replace(/\t/g, ' ');
|
||||||
|
|
||||||
|
it('should convert JSON to C# class with default options', () => {
|
||||||
|
const json = JSON.stringify({ name: 'John', age: 30 });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"name\")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
[JsonPropertyName(\"age\")]
|
||||||
|
public int Age { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not change case if pascalCase option is false', () => {
|
||||||
|
const json = JSON.stringify({ test: { user_name: 'John' } });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, pascalCase: false }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"test\")]
|
||||||
|
public Test test { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Test
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"user_name\")]
|
||||||
|
public string user_name { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle when root is an array', () => {
|
||||||
|
const json = JSON.stringify([{ age: 30 }]);
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class RootItem
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"age\")]
|
||||||
|
public int? Age { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use nullable types if useNullable option is true', () => {
|
||||||
|
const json = JSON.stringify({ age: 30 });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"age\")]
|
||||||
|
public int? Age { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add JsonProperty attributes if addJsonProperty is true', () => {
|
||||||
|
const json = JSON.stringify({ name: 'John' });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonProperty(\"name\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"name\")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add JsonPropertyName attributes if addJsonPropertyName is true', () => {
|
||||||
|
const json = JSON.stringify({ name: 'John' });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, addJsonPropertyName: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"name\")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should generate immutable classes if generateImmutableClasses is true', () => {
|
||||||
|
const json = JSON.stringify({ name: 'John' });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, generateImmutableClasses: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
public Root(
|
||||||
|
string name
|
||||||
|
){
|
||||||
|
this.Name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonPropertyName(\"name\")]
|
||||||
|
public string Name { get; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should convert JSON with arrays into C# classes', () => {
|
||||||
|
const json = {
|
||||||
|
users: [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }],
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(cleanTabs(json2csharp({ src: json }))).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"users\")]
|
||||||
|
public UsersItem[] Users { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UsersItem
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"name\")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
[JsonPropertyName(\"age\")]
|
||||||
|
public int Age { get; set; }
|
||||||
|
}`);
|
||||||
|
expect(cleanTabs(json2csharp({ src: json, useRecordTypes: true }))).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public record Root(
|
||||||
|
[property: JsonPropertyName(\"users\")]
|
||||||
|
UsersItem[] Users
|
||||||
|
);
|
||||||
|
|
||||||
|
public record UsersItem(
|
||||||
|
[property: JsonPropertyName(\"name\")]
|
||||||
|
string Name,
|
||||||
|
[property: JsonPropertyName(\"age\")]
|
||||||
|
int Age
|
||||||
|
);`);
|
||||||
|
expect(cleanTabs(json2csharp({ src: json, useRecordTypes: true, pascalCase: false, useReadonlyLists: true }))).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public record Root(
|
||||||
|
[property: JsonPropertyName(\"users\")]
|
||||||
|
IReadonlyList<UsersItem> users
|
||||||
|
);
|
||||||
|
|
||||||
|
public record UsersItem(
|
||||||
|
[property: JsonPropertyName(\"name\")]
|
||||||
|
string name,
|
||||||
|
[property: JsonPropertyName(\"age\")]
|
||||||
|
int age
|
||||||
|
);`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should generate C# record types when useRecordTypes is true', () => {
|
||||||
|
const json = JSON.stringify({ name: 'John', age: 30 });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, useRecordTypes: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public record Root(
|
||||||
|
[property: JsonPropertyName(\"name\")]
|
||||||
|
string Name,
|
||||||
|
[property: JsonPropertyName(\"age\")]
|
||||||
|
int Age
|
||||||
|
);`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should generate C# record types with attributes when useRecordTypes/addJsonProperty/addJsonPropertyName are true', () => {
|
||||||
|
const json = JSON.stringify({ name: 'John', age: 30 });
|
||||||
|
const result = cleanTabs(json2csharp({
|
||||||
|
src: json,
|
||||||
|
useRecordTypes: true,
|
||||||
|
addJsonProperty: true,
|
||||||
|
addJsonPropertyName: true,
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public record Root(
|
||||||
|
[property: JsonProperty(\"name\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[property: JsonPropertyName(\"name\")]
|
||||||
|
string Name,
|
||||||
|
[property: JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[property: JsonPropertyName(\"age\")]
|
||||||
|
int Age
|
||||||
|
);`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle arrays of primitives', () => {
|
||||||
|
const json = JSON.stringify({ numbers: [1, 2, 3] });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"numbers\")]
|
||||||
|
public int[] Numbers { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle arrays of objects with PascalCase enabled', () => {
|
||||||
|
const json = JSON.stringify({
|
||||||
|
items: [{ item_name: 'A', price: 10.5 }],
|
||||||
|
});
|
||||||
|
const result = cleanTabs(json2csharp({
|
||||||
|
src: json,
|
||||||
|
pascalCase: true,
|
||||||
|
addJsonProperty: true,
|
||||||
|
addJsonPropertyName: true,
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonProperty(\"items\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"items\")]
|
||||||
|
public ItemsItem[] Items { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ItemsItem
|
||||||
|
{
|
||||||
|
[JsonProperty(\"item_name\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"item_name\")]
|
||||||
|
public string ItemName { get; set; }
|
||||||
|
[JsonProperty(\"price\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"price\")]
|
||||||
|
public double Price { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use nullable types for optional fields when useNullable is true', () => {
|
||||||
|
const json = JSON.stringify({ age: null, price: 10.5 });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, useNullable: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"age\")]
|
||||||
|
public Age Age { get; set; }
|
||||||
|
[JsonPropertyName(\"price\")]
|
||||||
|
public double? Price { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Age
|
||||||
|
{
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use fields when useFields is true', () => {
|
||||||
|
const json = JSON.stringify({ age: 1, price: 10.5 });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, useFields: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"age\")]
|
||||||
|
public int Age;
|
||||||
|
[JsonPropertyName(\"price\")]
|
||||||
|
public double Price;
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add JsonProperty attributes when addJsonProperty is true', () => {
|
||||||
|
const json = JSON.stringify({ firstName: 'John', lastName: 'Doe' });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true, nullValueHandlingIgnore: false }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonProperty(\"firstName\")]
|
||||||
|
[JsonPropertyName(\"firstName\")]
|
||||||
|
public string FirstName { get; set; }
|
||||||
|
[JsonProperty(\"lastName\")]
|
||||||
|
[JsonPropertyName(\"lastName\")]
|
||||||
|
public string LastName { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should add JsonProperty attributes when addJsonProperty and nullValueHandlingIgnore are true', () => {
|
||||||
|
const json = JSON.stringify({ firstName: 'John', lastName: 'Doe' });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, addJsonProperty: true, nullValueHandlingIgnore: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonProperty(\"firstName\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"firstName\")]
|
||||||
|
public string FirstName { get; set; }
|
||||||
|
[JsonProperty(\"lastName\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"lastName\")]
|
||||||
|
public string LastName { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle all types', () => {
|
||||||
|
const json = JSON.stringify({
|
||||||
|
id: 1, date: '2025-06-09', amount: 1.4, group: null, active: true, email: 'test@example.com',
|
||||||
|
});
|
||||||
|
const result = cleanTabs(json2csharp({ src: json }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"id\")]
|
||||||
|
public int Id { get; set; }
|
||||||
|
[JsonPropertyName(\"date\")]
|
||||||
|
public DateTime Date { get; set; }
|
||||||
|
[JsonPropertyName(\"amount\")]
|
||||||
|
public double Amount { get; set; }
|
||||||
|
[JsonPropertyName(\"group\")]
|
||||||
|
public Group Group { get; set; }
|
||||||
|
[JsonPropertyName(\"active\")]
|
||||||
|
public bool Active { get; set; }
|
||||||
|
[JsonPropertyName(\"email\")]
|
||||||
|
public string Email { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Group
|
||||||
|
{
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use readonly lists when useReadonlyLists is true', () => {
|
||||||
|
const json = JSON.stringify({
|
||||||
|
items: [{ name: 'Item1' }, { name: 'Item2' }],
|
||||||
|
});
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, useReadonlyLists: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"items\")]
|
||||||
|
public List<ItemsItem> Items { get; } = new List<ItemsItem>;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ItemsItem
|
||||||
|
{
|
||||||
|
[JsonPropertyName(\"name\")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use immutable class properties when generateImmutableClasses is true', () => {
|
||||||
|
const json = JSON.stringify({ title: 'Book', pages: 300 });
|
||||||
|
const result = cleanTabs(json2csharp({ src: json, generateImmutableClasses: true }));
|
||||||
|
|
||||||
|
expect(result).toBe(`using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
public Root(
|
||||||
|
string title,
|
||||||
|
int pages
|
||||||
|
){
|
||||||
|
this.Title = title;
|
||||||
|
this.Pages = pages;
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonPropertyName(\"title\")]
|
||||||
|
public string Title { get; }
|
||||||
|
[JsonPropertyName(\"pages\")]
|
||||||
|
public int Pages { get; }
|
||||||
|
}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should generate a combination of options correctly', () => {
|
||||||
|
const json = JSON.stringify({
|
||||||
|
people: [
|
||||||
|
{ first_name: 'John', age: 30 },
|
||||||
|
{ first_name: 'Jane', age: 25 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(cleanTabs(json2csharp({
|
||||||
|
src: json,
|
||||||
|
pascalCase: true,
|
||||||
|
useNullable: true,
|
||||||
|
addJsonProperty: true,
|
||||||
|
generateImmutableClasses: true,
|
||||||
|
useRecordTypes: false,
|
||||||
|
useReadonlyLists: true,
|
||||||
|
}))).toBe(`using System;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
public Root(
|
||||||
|
List<PeopleItem> people
|
||||||
|
){
|
||||||
|
this.People = people;
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"people\")]
|
||||||
|
public List<PeopleItem> People { get; } = new List<PeopleItem>;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PeopleItem
|
||||||
|
{
|
||||||
|
public PeopleItem(
|
||||||
|
string firstName,
|
||||||
|
int? age
|
||||||
|
){
|
||||||
|
this.FirstName = firstName;
|
||||||
|
this.Age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"first_name\")]
|
||||||
|
public string FirstName { get; }
|
||||||
|
[JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"age\")]
|
||||||
|
public int? Age { get; }
|
||||||
|
}`);
|
||||||
|
expect(cleanTabs(json2csharp({
|
||||||
|
src: json,
|
||||||
|
pascalCase: true,
|
||||||
|
useNullable: true,
|
||||||
|
addJsonProperty: true,
|
||||||
|
addJsonPropertyName: true,
|
||||||
|
generateImmutableClasses: false,
|
||||||
|
useRecordTypes: false,
|
||||||
|
useReadonlyLists: true,
|
||||||
|
}))).toBe(`using System;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public class Root
|
||||||
|
{
|
||||||
|
[JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"people\")]
|
||||||
|
public List<PeopleItem> People { get; } = new List<PeopleItem>;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PeopleItem
|
||||||
|
{
|
||||||
|
[JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"first_name\")]
|
||||||
|
public string FirstName { get; set; }
|
||||||
|
[JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[JsonPropertyName(\"age\")]
|
||||||
|
public int? Age { get; set; }
|
||||||
|
}`);
|
||||||
|
expect(cleanTabs(json2csharp({
|
||||||
|
src: json,
|
||||||
|
pascalCase: true,
|
||||||
|
useNullable: true,
|
||||||
|
addJsonProperty: true,
|
||||||
|
useRecordTypes: true,
|
||||||
|
useReadonlyLists: true,
|
||||||
|
}))).toBe(`using System;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
public record Root(
|
||||||
|
[property: JsonProperty(\"people\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[property: JsonPropertyName(\"people\")]
|
||||||
|
IReadonlyList<PeopleItem> People
|
||||||
|
);
|
||||||
|
|
||||||
|
public record PeopleItem(
|
||||||
|
[property: JsonProperty(\"first_name\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[property: JsonPropertyName(\"first_name\")]
|
||||||
|
string FirstName,
|
||||||
|
[property: JsonProperty(\"age\", NullValueHandling = NullValueHandling.Ignore)]
|
||||||
|
[property: JsonPropertyName(\"age\")]
|
||||||
|
int? Age
|
||||||
|
);`);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
import { camelCase as convertToCamelCase, pascalCase as convertToPascalCase } from 'change-case';
|
||||||
|
import JSON5 from 'json5';
|
||||||
|
|
||||||
|
function normalize(src: string, firstUpper = true) {
|
||||||
|
// return /^\d$/.test(src.charAt(0))
|
||||||
|
// ? `N${pascalCase(src)}`
|
||||||
|
// : pascalCase(src);
|
||||||
|
return /^\d$/.test(src.charAt(0))
|
||||||
|
? `N${src}`
|
||||||
|
: (firstUpper ? src.charAt(0).toUpperCase() + src.slice(1) : src);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDate(src: string) {
|
||||||
|
return /^(\d{4})(-(0[1-9]|1[0-2])(-([12]\d|0[1-9]|3[01]))([T\s]((([01]\d|2[0-3])((:)[0-5]\d))([\:]\d+)?)?(:[0-5]\d([\.]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)$/.test(
|
||||||
|
src,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Prop { type: string; name: string; isArray?: boolean; canBeNullable?: boolean }
|
||||||
|
|
||||||
|
export function getPrimitiveProp(obj: any, key: string): Prop {
|
||||||
|
const type = typeof obj;
|
||||||
|
switch (type) {
|
||||||
|
case 'string':
|
||||||
|
// eslint-disable-next-line no-case-declarations
|
||||||
|
const isObjDate = isDate(obj);
|
||||||
|
return { type: isObjDate ? 'DateTime' : 'string', name: key, canBeNullable: isObjDate };
|
||||||
|
case 'number':
|
||||||
|
return { type: Number.isInteger(obj) ? 'int' : 'double', name: key, canBeNullable: true };
|
||||||
|
case 'boolean':
|
||||||
|
return { type: 'bool', name: key, canBeNullable: true };
|
||||||
|
default:
|
||||||
|
throw new Error(`Unexpected key '${key}' of type ${type}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClassType { key: string; props: Array<Prop> }
|
||||||
|
|
||||||
|
function handleObject(
|
||||||
|
classes: Array<ClassType>,
|
||||||
|
obj: any,
|
||||||
|
key: string,
|
||||||
|
skip: boolean = false) {
|
||||||
|
const normalizedKey = normalize(key);
|
||||||
|
let target: ClassType = classes.find(x => x.key === normalizedKey) as never;
|
||||||
|
if (!target) {
|
||||||
|
target = { key: normalizedKey, props: [] };
|
||||||
|
if (!skip) {
|
||||||
|
classes.push(target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (obj != null) {
|
||||||
|
Object.keys(obj).forEach((k) => {
|
||||||
|
const keyName = Number.isNaN(Number(k)) ? k : `${normalizedKey}Item`;
|
||||||
|
let prop: Prop | null = null;
|
||||||
|
if (typeof obj[k] == 'object') {
|
||||||
|
if (Array.isArray(obj[k])) {
|
||||||
|
if (Array.from(obj[k]).length > 0) {
|
||||||
|
if (typeof obj[k][0] == 'object') {
|
||||||
|
handleObject(classes, obj[k], keyName, true);
|
||||||
|
prop = {
|
||||||
|
type: normalize(`${keyName}Item`),
|
||||||
|
name: keyName,
|
||||||
|
isArray: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
prop = getPrimitiveProp(obj[k][0], keyName);
|
||||||
|
prop.isArray = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
handleObject(classes, obj[k], keyName);
|
||||||
|
prop = { type: normalize(keyName), name: keyName };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
prop = getPrimitiveProp(obj[k], keyName);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (prop && !target.props.some(x => x.name === prop?.name)) {
|
||||||
|
target.props.push(prop);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function json2classes(src: object, rootTypeName: string = 'Root') {
|
||||||
|
const classes: Array<ClassType> = [];
|
||||||
|
handleObject(classes, src, rootTypeName);
|
||||||
|
return classes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function json2csharp(
|
||||||
|
{
|
||||||
|
src,
|
||||||
|
rootTypeName = 'Root',
|
||||||
|
pascalCase = true,
|
||||||
|
nullValueHandlingIgnore = true,
|
||||||
|
addJsonPropertyName = true,
|
||||||
|
useReadonlyLists,
|
||||||
|
useRecordTypes,
|
||||||
|
addJsonProperty,
|
||||||
|
generateImmutableClasses,
|
||||||
|
useFields,
|
||||||
|
useNullable,
|
||||||
|
}: {
|
||||||
|
src: any
|
||||||
|
rootTypeName?: string
|
||||||
|
pascalCase?: boolean
|
||||||
|
useFields?: boolean
|
||||||
|
useNullable?: boolean
|
||||||
|
addJsonProperty?: boolean
|
||||||
|
nullValueHandlingIgnore?: boolean
|
||||||
|
addJsonPropertyName?: boolean
|
||||||
|
generateImmutableClasses?: boolean
|
||||||
|
useRecordTypes?: boolean
|
||||||
|
useReadonlyLists?: boolean
|
||||||
|
}) {
|
||||||
|
const normalizeCase = (s: string) => {
|
||||||
|
const normalized = normalize(s, pascalCase);
|
||||||
|
return pascalCase ? convertToPascalCase(normalized) : normalized;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getPropType = (p: Prop) => {
|
||||||
|
let type = p.type;
|
||||||
|
if (p.isArray) {
|
||||||
|
if (useReadonlyLists) {
|
||||||
|
type = useRecordTypes ? `IReadonlyList<${type}>` : `List<${type}>`;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
type = `${type}[]`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const nullable = useNullable && p.canBeNullable ? '?' : '';
|
||||||
|
return { type, nullable };
|
||||||
|
};
|
||||||
|
|
||||||
|
const srcObj = typeof src === 'string' ? JSON5.parse(src) : src;
|
||||||
|
const classes = json2classes(
|
||||||
|
Array.isArray(srcObj) ? srcObj[0] : srcObj,
|
||||||
|
Array.isArray(srcObj) ? `${rootTypeName}Item` : rootTypeName);
|
||||||
|
let result = '';
|
||||||
|
result += 'using System;\n';
|
||||||
|
result += addJsonProperty ? 'using Newtonsoft.Json;\n' : '';
|
||||||
|
result += addJsonPropertyName ? 'using System.Text.Json;\n' : '';
|
||||||
|
result += '\n';
|
||||||
|
classes.forEach((c) => {
|
||||||
|
if (useRecordTypes) {
|
||||||
|
result += `public record ${normalizeCase(c.key)}(\n`;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result += `public class ${normalizeCase(c.key)}\n`;
|
||||||
|
result += '{\n';
|
||||||
|
}
|
||||||
|
if (!useRecordTypes && generateImmutableClasses) {
|
||||||
|
result += `\tpublic ${normalizeCase(c.key)}(\n`;
|
||||||
|
c.props.forEach((p) => {
|
||||||
|
const propType = getPropType(p);
|
||||||
|
result += `\t\t${propType.type}${propType.nullable} ${convertToCamelCase(p.name)},\n`;
|
||||||
|
});
|
||||||
|
result = result.replace(/,\n$/, '\n');
|
||||||
|
result += '\t){\n';
|
||||||
|
c.props.forEach((p) => {
|
||||||
|
result += `\t\tthis.${normalizeCase(p.name)} = ${convertToCamelCase(p.name)};\n`;
|
||||||
|
});
|
||||||
|
result += '\t}\n\n';
|
||||||
|
}
|
||||||
|
c.props.forEach((p) => {
|
||||||
|
const scope = useRecordTypes ? 'property: ' : '';
|
||||||
|
if (addJsonProperty) {
|
||||||
|
if (nullValueHandlingIgnore) {
|
||||||
|
result += `\t[${scope}JsonProperty("${p.name}", NullValueHandling = NullValueHandling.Ignore)]\n`;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result += `\t[${scope}JsonProperty("${p.name}")]\n`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (addJsonPropertyName) {
|
||||||
|
result += `\t[${scope}JsonPropertyName("${p.name}")]\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const propType = getPropType(p);
|
||||||
|
if (useRecordTypes) {
|
||||||
|
result += `\t${propType.type}${propType.nullable} ${normalizeCase(p.name)},\n`;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const newList = useReadonlyLists && p.isArray ? ` = new ${propType.type};` : '';
|
||||||
|
if (useFields) {
|
||||||
|
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)}${(newList || ';')}`;
|
||||||
|
}
|
||||||
|
else if (generateImmutableClasses || (p.isArray && useReadonlyLists)) {
|
||||||
|
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)} { get; }${newList}`;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result += `\tpublic ${propType.type}${propType.nullable} ${normalizeCase(p.name)} { get; set; }${newList}`;
|
||||||
|
}
|
||||||
|
result += '\n';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (useRecordTypes) {
|
||||||
|
result = result.replace(/,\n$/, '\n');
|
||||||
|
result += ');\n\n';
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result += '}\n\n';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return result.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export default json2csharp;
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { Braces } from '@vicons/tabler';
|
|
||||||
import { defineTool } from '../tool';
|
|
||||||
|
|
||||||
export const tool = defineTool({
|
|
||||||
name: 'JSON to XML',
|
|
||||||
path: '/json-to-xml',
|
|
||||||
description: 'Convert JSON to XML',
|
|
||||||
keywords: ['json', 'xml'],
|
|
||||||
component: () => import('./json-to-xml.vue'),
|
|
||||||
icon: Braces,
|
|
||||||
createdAt: new Date('2024-08-09'),
|
|
||||||
});
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import convert from 'xml-js';
|
|
||||||
import JSON5 from 'json5';
|
|
||||||
import { withDefaultOnError } from '@/utils/defaults';
|
|
||||||
import type { UseValidationRule } from '@/composable/validation';
|
|
||||||
|
|
||||||
const defaultValue = '{"a":{"_attributes":{"x":"1.234","y":"It\'s"}}}';
|
|
||||||
function transformer(value: string) {
|
|
||||||
return withDefaultOnError(() => {
|
|
||||||
return convert.js2xml(JSON5.parse(value), { compact: true });
|
|
||||||
}, '');
|
|
||||||
}
|
|
||||||
|
|
||||||
const rules: UseValidationRule<string>[] = [
|
|
||||||
{
|
|
||||||
validator: (v: string) => v === '' || JSON5.parse(v),
|
|
||||||
message: 'Provided JSON is not valid.',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<format-transformer
|
|
||||||
input-label="Your JSON content"
|
|
||||||
:input-default="defaultValue"
|
|
||||||
input-placeholder="Paste your JSON content here..."
|
|
||||||
output-label="Converted XML"
|
|
||||||
output-language="xml"
|
|
||||||
:transformer="transformer"
|
|
||||||
:input-validation-rules="rules"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
@@ -39,7 +39,7 @@ const validation = useValidation({
|
|||||||
{{ section.title }}
|
{{ section.title }}
|
||||||
</th>
|
</th>
|
||||||
<tr v-for="{ claim, claimDescription, friendlyValue, value } in decodedJWT[section.key]" :key="claim + value">
|
<tr v-for="{ claim, claimDescription, friendlyValue, value } in decodedJWT[section.key]" :key="claim + value">
|
||||||
<td class="claims" style="vertical-align: top;">
|
<td class="claims">
|
||||||
<span font-bold>
|
<span font-bold>
|
||||||
{{ claim }}
|
{{ claim }}
|
||||||
</span>
|
</span>
|
||||||
@@ -47,7 +47,7 @@ const validation = useValidation({
|
|||||||
({{ claimDescription }})
|
({{ claimDescription }})
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td style="word-wrap: break-word;word-break: break-all;">
|
<td>
|
||||||
<span>{{ value }}</span>
|
<span>{{ value }}</span>
|
||||||
<span v-if="friendlyValue" ml-2 op-70>
|
<span v-if="friendlyValue" ml-2 op-70>
|
||||||
({{ friendlyValue }})
|
({{ friendlyValue }})
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
import { generateLoremIpsum } from './lorem-ipsum-generator.service';
|
import { generateLoremIpsum } from './lorem-ipsum-generator.service';
|
||||||
import { useCopy } from '@/composable/copy';
|
import { useCopy } from '@/composable/copy';
|
||||||
import { randIntFromInterval } from '@/utils/random';
|
import { randIntFromInterval } from '@/utils/random';
|
||||||
import { computedRefreshable } from '@/composable/computedRefreshable';
|
|
||||||
|
|
||||||
const paragraphs = ref(1);
|
const paragraphs = ref(1);
|
||||||
const sentences = ref([3, 8]);
|
const sentences = ref([3, 8]);
|
||||||
@@ -10,7 +9,7 @@ const words = ref([8, 15]);
|
|||||||
const startWithLoremIpsum = ref(true);
|
const startWithLoremIpsum = ref(true);
|
||||||
const asHTML = ref(false);
|
const asHTML = ref(false);
|
||||||
|
|
||||||
const [loremIpsumText, refreshLoremIpsum] = computedRefreshable(() =>
|
const loremIpsumText = computed(() =>
|
||||||
generateLoremIpsum({
|
generateLoremIpsum({
|
||||||
paragraphCount: paragraphs.value,
|
paragraphCount: paragraphs.value,
|
||||||
asHTML: asHTML.value,
|
asHTML: asHTML.value,
|
||||||
@@ -19,7 +18,6 @@ const [loremIpsumText, refreshLoremIpsum] = computedRefreshable(() =>
|
|||||||
startWithLoremIpsum: startWithLoremIpsum.value,
|
startWithLoremIpsum: startWithLoremIpsum.value,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const { copy } = useCopy({ source: loremIpsumText, text: 'Lorem ipsum copied to the clipboard' });
|
const { copy } = useCopy({ source: loremIpsumText, text: 'Lorem ipsum copied to the clipboard' });
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -43,13 +41,10 @@ const { copy } = useCopy({ source: loremIpsumText, text: 'Lorem ipsum copied to
|
|||||||
|
|
||||||
<c-input-text :value="loremIpsumText" multiline placeholder="Your lorem ipsum..." readonly mt-5 rows="5" />
|
<c-input-text :value="loremIpsumText" multiline placeholder="Your lorem ipsum..." readonly mt-5 rows="5" />
|
||||||
|
|
||||||
<div mt-5 flex justify-center gap-3>
|
<div mt-5 flex justify-center>
|
||||||
<c-button autofocus @click="copy()">
|
<c-button autofocus @click="copy()">
|
||||||
Copy
|
Copy
|
||||||
</c-button>
|
</c-button>
|
||||||
<c-button @click="refreshLoremIpsum">
|
|
||||||
Refresh
|
|
||||||
</c-button>
|
|
||||||
</div>
|
</div>
|
||||||
</c-card>
|
</c-card>
|
||||||
</template>
|
</template>
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
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'),
|
|
||||||
});
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
<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
@@ -1,3 +0,0 @@
|
|||||||
declare module "vue-mathjax-next" {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { Braces } from '@vicons/tabler';
|
|
||||||
import { defineTool } from '../tool';
|
|
||||||
|
|
||||||
export const tool = defineTool({
|
|
||||||
name: 'XML to JSON',
|
|
||||||
path: '/xml-to-json',
|
|
||||||
description: 'Convert XML to JSON',
|
|
||||||
keywords: ['xml', 'json'],
|
|
||||||
component: () => import('./xml-to-json.vue'),
|
|
||||||
icon: Braces,
|
|
||||||
createdAt: new Date('2024-08-09'),
|
|
||||||
});
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import convert from 'xml-js';
|
|
||||||
import { isValidXML } from '../xml-formatter/xml-formatter.service';
|
|
||||||
import { withDefaultOnError } from '@/utils/defaults';
|
|
||||||
import type { UseValidationRule } from '@/composable/validation';
|
|
||||||
|
|
||||||
const defaultValue = '<a x="1.234" y="It\'s"/>';
|
|
||||||
function transformer(value: string) {
|
|
||||||
return withDefaultOnError(() => {
|
|
||||||
return JSON.stringify(convert.xml2js(value, { compact: true }), null, 2);
|
|
||||||
}, '');
|
|
||||||
}
|
|
||||||
|
|
||||||
const rules: UseValidationRule<string>[] = [
|
|
||||||
{
|
|
||||||
validator: isValidXML,
|
|
||||||
message: 'Provided XML is not valid.',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<format-transformer
|
|
||||||
input-label="Your XML content"
|
|
||||||
:input-default="defaultValue"
|
|
||||||
input-placeholder="Paste your XML content here..."
|
|
||||||
output-label="Converted JSON"
|
|
||||||
output-language="json"
|
|
||||||
:transformer="transformer"
|
|
||||||
:input-validation-rules="rules"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
@@ -5,12 +5,10 @@ const props = withDefaults(defineProps<{
|
|||||||
multiple?: boolean
|
multiple?: boolean
|
||||||
accept?: string
|
accept?: string
|
||||||
title?: string
|
title?: string
|
||||||
pasteImage?: boolean
|
|
||||||
}>(), {
|
}>(), {
|
||||||
multiple: false,
|
multiple: false,
|
||||||
accept: undefined,
|
accept: undefined,
|
||||||
title: 'Drag and drop files here, or click to select files',
|
title: 'Drag and drop files here, or click to select files',
|
||||||
pasteImage: false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
@@ -18,31 +16,11 @@ const emit = defineEmits<{
|
|||||||
(event: 'fileUpload', file: File): void
|
(event: 'fileUpload', file: File): void
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const { multiple, pasteImage } = toRefs(props);
|
const { multiple } = toRefs(props);
|
||||||
|
|
||||||
const isOverDropZone = ref(false);
|
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 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() {
|
function triggerFileInput() {
|
||||||
fileInput.value?.click();
|
fileInput.value?.click();
|
||||||
@@ -61,30 +39,7 @@ function handleDrop(event: DragEvent) {
|
|||||||
handleUpload(files);
|
handleUpload(files);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onPasteImage(evt: ClipboardEvent) {
|
function handleUpload(files: FileList | null | undefined) {
|
||||||
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)) {
|
if (_.isNil(files) || _.isEmpty(files)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -94,7 +49,6 @@ async function handleUpload(files: FileList | null | undefined) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await handlePreview(files[0]);
|
|
||||||
emit('fileUpload', files[0]);
|
emit('fileUpload', files[0]);
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -106,7 +60,6 @@ async function handleUpload(files: FileList | null | undefined) {
|
|||||||
'border-primary border-opacity-100': isOverDropZone,
|
'border-primary border-opacity-100': isOverDropZone,
|
||||||
}"
|
}"
|
||||||
@click="triggerFileInput"
|
@click="triggerFileInput"
|
||||||
@paste.prevent="onPasteImage"
|
|
||||||
@drop.prevent="handleDrop"
|
@drop.prevent="handleDrop"
|
||||||
@dragover.prevent
|
@dragover.prevent
|
||||||
@dragenter="isOverDropZone = true"
|
@dragenter="isOverDropZone = true"
|
||||||
@@ -120,7 +73,6 @@ async function handleUpload(files: FileList | null | undefined) {
|
|||||||
:accept="accept"
|
:accept="accept"
|
||||||
@change="handleFileInput"
|
@change="handleFileInput"
|
||||||
>
|
>
|
||||||
|
|
||||||
<slot>
|
<slot>
|
||||||
<span op-70>
|
<span op-70>
|
||||||
{{ title }}
|
{{ title }}
|
||||||
@@ -138,22 +90,6 @@ async function handleUpload(files: FileList | null | undefined) {
|
|||||||
<c-button>
|
<c-button>
|
||||||
Browse files
|
Browse files
|
||||||
</c-button>
|
</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>
|
</slot>
|
||||||
<div mt-2>
|
|
||||||
<img ref="imgPreview" width="150">
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -38,8 +38,7 @@ describe('base64 utils', () => {
|
|||||||
|
|
||||||
it('should throw for incorrect base64 string', () => {
|
it('should throw for incorrect base64 string', () => {
|
||||||
expect(() => base64ToText('a')).to.throw('Incorrect base64 string');
|
expect(() => base64ToText('a')).to.throw('Incorrect base64 string');
|
||||||
// should not really be false because trimming of space is now implied
|
expect(() => base64ToText(' ')).to.throw('Incorrect base64 string');
|
||||||
// expect(() => base64ToText(' ')).to.throw('Incorrect base64 string');
|
|
||||||
expect(() => base64ToText('é')).to.throw('Incorrect base64 string');
|
expect(() => base64ToText('é')).to.throw('Incorrect base64 string');
|
||||||
// missing final '='
|
// missing final '='
|
||||||
expect(() => base64ToText('bG9yZW0gaXBzdW0')).to.throw('Incorrect base64 string');
|
expect(() => base64ToText('bG9yZW0gaXBzdW0')).to.throw('Incorrect base64 string');
|
||||||
@@ -57,17 +56,17 @@ describe('base64 utils', () => {
|
|||||||
|
|
||||||
it('should return false for incorrect base64 string', () => {
|
it('should return false for incorrect base64 string', () => {
|
||||||
expect(isValidBase64('a')).to.eql(false);
|
expect(isValidBase64('a')).to.eql(false);
|
||||||
|
expect(isValidBase64(' ')).to.eql(false);
|
||||||
expect(isValidBase64('é')).to.eql(false);
|
expect(isValidBase64('é')).to.eql(false);
|
||||||
expect(isValidBase64('data:text/plain;notbase64,YQ==')).to.eql(false);
|
expect(isValidBase64('data:text/plain;notbase64,YQ==')).to.eql(false);
|
||||||
// missing final '='
|
// missing final '='
|
||||||
expect(isValidBase64('bG9yZW0gaXBzdW0')).to.eql(false);
|
expect(isValidBase64('bG9yZW0gaXBzdW0')).to.eql(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return true for untrimmed correct base64 string', () => {
|
it('should return false for untrimmed correct base64 string', () => {
|
||||||
expect(isValidBase64('bG9yZW0gaXBzdW0= ')).to.eql(true);
|
expect(isValidBase64('bG9yZW0gaXBzdW0= ')).to.eql(false);
|
||||||
expect(isValidBase64(' LTE=')).to.eql(true);
|
expect(isValidBase64(' LTE=')).to.eql(false);
|
||||||
expect(isValidBase64(' YQ== ')).to.eql(true);
|
expect(isValidBase64(' YQ== ')).to.eql(false);
|
||||||
expect(isValidBase64(' ')).to.eql(true);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+4
-7
@@ -1,9 +1,7 @@
|
|||||||
import { Base64 } from 'js-base64';
|
|
||||||
|
|
||||||
export { textToBase64, base64ToText, isValidBase64, removePotentialDataAndMimePrefix };
|
export { textToBase64, base64ToText, isValidBase64, removePotentialDataAndMimePrefix };
|
||||||
|
|
||||||
function textToBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boolean } = {}) {
|
function textToBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boolean } = {}) {
|
||||||
const encoded = Base64.encode(str);
|
const encoded = window.btoa(str);
|
||||||
return makeUrlSafe ? makeUriSafe(encoded) : encoded;
|
return makeUrlSafe ? makeUriSafe(encoded) : encoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,7 +16,7 @@ function base64ToText(str: string, { makeUrlSafe = false }: { makeUrlSafe?: bool
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return Base64.decode(cleanStr);
|
return window.atob(cleanStr);
|
||||||
}
|
}
|
||||||
catch (_) {
|
catch (_) {
|
||||||
throw new Error('Incorrect base64 string');
|
throw new Error('Incorrect base64 string');
|
||||||
@@ -36,11 +34,10 @@ function isValidBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const reEncodedBase64 = Base64.fromUint8Array(Base64.toUint8Array(cleanStr));
|
|
||||||
if (makeUrlSafe) {
|
if (makeUrlSafe) {
|
||||||
return removePotentialPadding(reEncodedBase64) === cleanStr;
|
return removePotentialPadding(window.btoa(window.atob(cleanStr))) === cleanStr;
|
||||||
}
|
}
|
||||||
return reEncodedBase64 === cleanStr.replace(/\s/g, '');
|
return window.btoa(window.atob(cleanStr)) === cleanStr;
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
Reference in new issue
Block a user