Compare commits

..
Author SHA1 Message Date
sharevb d02443a288 fix(json-to-csv): handle single object and flatten
Fix #1203
2024-09-01 19:55:42 +02:00
sharevbandCorentin THOMASSET 87984e2081 feat(new tool): Markdown to HTML (#916)
* feat(new tool): Markdown to HTML

Fix partially #538

* feat: add print button

* Update src/tools/markdown-to-html/index.ts

* Update src/tools/markdown-to-html/markdown-to-html.vue

---------

Co-authored-by: Corentin THOMASSET <corentin.thomasset74@gmail.com>
2024-08-25 20:57:07 +00:00
15 changed files with 195 additions and 766 deletions

No files matched your search

+2
View File
@@ -121,6 +121,7 @@ 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']
@@ -129,6 +130,7 @@ 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']
NCode: typeof import('naive-ui')['NCode']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
+3 -2
View File
@@ -35,7 +35,6 @@
"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",
"@sindresorhus/slugify": "^2.2.1",
@@ -43,6 +42,7 @@
"@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",
@@ -62,6 +62,7 @@
"emojilib": "^3.0.10",
"figlet": "^1.7.0",
"figue": "^1.2.0",
"flatten-anything": "^4.0.1",
"fuse.js": "^6.6.2",
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
@@ -71,6 +72,7 @@
"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",
@@ -91,7 +93,6 @@
"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-tsc": "^1.8.1",
"xml-formatter": "^3.3.2",
+80 -569
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -7,6 +7,7 @@ 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(
@@ -30,6 +31,7 @@ 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) };
+3 -7
View File
@@ -2,7 +2,6 @@ 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 mathOcr } from './math-ocr';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
@@ -10,6 +9,7 @@ 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 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';
@@ -113,6 +113,7 @@ export const toolsByCategory: ToolCategory[] = [
tomlToYaml,
xmlToJson,
jsonToXml,
markdownToHtml,
],
},
{
@@ -163,12 +164,7 @@ export const toolsByCategory: ToolCategory[] = [
},
{
name: 'Math',
components: [
mathEvaluator,
etaCalculator,
percentageCalculator,
mathOcr,
],
components: [mathEvaluator, etaCalculator, percentageCalculator],
},
{
name: 'Measurement',
+7
View File
@@ -0,0 +1,7 @@
declare module "flatten-anything" {
export function flatten(objectOrArray: {
[key in string]: any;
}, untilDepth?: number): {
[key in string]: any;
};
}
@@ -3,6 +3,10 @@ import { convertArrayToCsv, getHeaders } from './json-to-csv.service';
describe('json-to-csv service', () => {
describe('getHeaders', () => {
it('extracts all the keys from the array of nested objects', () => {
expect(getHeaders({ array: [{ a: { c: 1, d: 1 }, b: 2 }, { a: 3, c: 4 }] })).toEqual(['a.c', 'a.d', 'b', 'a', 'c']);
});
it('extracts all the keys from the array of objects', () => {
expect(getHeaders({ array: [{ a: 1, b: 2 }, { a: 3, c: 4 }] })).toEqual(['a', 'b', 'c']);
});
@@ -20,7 +24,7 @@ describe('json-to-csv service', () => {
];
expect(convertArrayToCsv({ array })).toMatchInlineSnapshot(`
expect(convertArrayToCsv({ arrayOrObject: array })).toMatchInlineSnapshot(`
"a,b
1,2
3,4"
@@ -33,7 +37,7 @@ describe('json-to-csv service', () => {
{ a: 3, c: 4 },
];
expect(convertArrayToCsv({ array })).toMatchInlineSnapshot(`
expect(convertArrayToCsv({ arrayOrObject: array })).toMatchInlineSnapshot(`
"a,b,c
1,2,
3,,4"
@@ -45,7 +49,7 @@ describe('json-to-csv service', () => {
{ a: null, b: 2 },
];
expect(convertArrayToCsv({ array })).toMatchInlineSnapshot(`
expect(convertArrayToCsv({ arrayOrObject: array })).toMatchInlineSnapshot(`
"a,b
null,2"
`);
@@ -57,7 +61,7 @@ describe('json-to-csv service', () => {
{ b: 3 },
];
expect(convertArrayToCsv({ array })).toMatchInlineSnapshot(`
expect(convertArrayToCsv({ arrayOrObject: array })).toMatchInlineSnapshot(`
"a,b
,2
,3"
@@ -69,7 +73,7 @@ describe('json-to-csv service', () => {
{ a: 'hello, world', b: 2 },
];
expect(convertArrayToCsv({ array })).toMatchInlineSnapshot(`
expect(convertArrayToCsv({ arrayOrObject: array })).toMatchInlineSnapshot(`
"a,b
\\"hello, world\\",2"
`);
@@ -80,10 +84,32 @@ describe('json-to-csv service', () => {
{ a: 'hello "world"', b: 2 },
];
expect(convertArrayToCsv({ array })).toMatchInlineSnapshot(`
expect(convertArrayToCsv({ arrayOrObject: array })).toMatchInlineSnapshot(`
"a,b
hello \\\\\\"world\\\\\\",2"
`);
});
it('converts an array of nested objects to a CSV string', () => {
const array = [
{ a: { c: 1, d: 1 }, b: 2 },
{ a: 3, c: 4 },
];
expect(convertArrayToCsv({ arrayOrObject: array })).toMatchInlineSnapshot(`
"a.c,a.d,b,a,c
1,1,2,,
,,,3,4"
`);
});
it('converts an object to a CSV string', () => {
const obj = { a: { c: 1, d: 1 }, b: 2 };
expect(convertArrayToCsv({ arrayOrObject: obj })).toMatchInlineSnapshot(`
"a.c,a.d,b
1,1,2"
`);
});
});
});
+7 -3
View File
@@ -1,9 +1,11 @@
import { flatten } from 'flatten-anything';
export { getHeaders, convertArrayToCsv };
function getHeaders({ array }: { array: Record<string, unknown>[] }): string[] {
const headers = new Set<string>();
array.forEach(item => Object.keys(item).forEach(key => headers.add(key)));
array.forEach(item => Object.keys(flatten(item)).forEach(key => headers.add(key)));
return Array.from(headers);
}
@@ -26,10 +28,12 @@ function serializeValue(value: unknown): string {
return valueAsString;
}
function convertArrayToCsv({ array }: { array: Record<string, unknown>[] }): string {
function convertArrayToCsv({ arrayOrObject }: { arrayOrObject: Record<string, unknown>[] | Record<string, unknown> }): string {
const array = !Array.isArray(arrayOrObject) ? [arrayOrObject] : arrayOrObject;
const headers = getHeaders({ array });
const rows = array.map(item => headers.map(header => serializeValue(item[header])));
const rows = array.map(item => headers.map(header => serializeValue(flatten(item)[header])));
return [headers.join(','), ...rows].join('\n');
}
+1 -1
View File
@@ -9,7 +9,7 @@ function transformer(value: string) {
if (value === '') {
return '';
}
return convertArrayToCsv({ array: JSON5.parse(value) });
return convertArrayToCsv({ arrayOrObject: JSON5.parse(value) });
}, '');
}
+12
View File
@@ -0,0 +1,12 @@
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'),
});
@@ -0,0 +1,44 @@
<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
@@ -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'),
});
-97
View File
@@ -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
View File
@@ -1,3 +0,0 @@
declare module "vue-mathjax-next" {
}
+2 -66
View File
@@ -5,12 +5,10 @@ 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<{
@@ -18,31 +16,11 @@ const emit = defineEmits<{
(event: 'fileUpload', file: File): void
}>();
const { multiple, pasteImage } = toRefs(props);
const { multiple } = 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();
@@ -61,30 +39,7 @@ function handleDrop(event: DragEvent) {
handleUpload(files);
}
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();
function handleUpload(files: FileList | null | undefined) {
if (_.isNil(files) || _.isEmpty(files)) {
return;
}
@@ -94,7 +49,6 @@ async function handleUpload(files: FileList | null | undefined) {
return;
}
await handlePreview(files[0]);
emit('fileUpload', files[0]);
}
</script>
@@ -106,7 +60,6 @@ async 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"
@@ -120,7 +73,6 @@ async function handleUpload(files: FileList | null | undefined) {
:accept="accept"
@change="handleFileInput"
>
<slot>
<span op-70>
{{ title }}
@@ -138,22 +90,6 @@ async 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>