IT-TOOLS-PRO v1 - 定制版开发者工具站
12个原创工具(批量条码/二维码识别/在线翻译/OCR/面单设计/AI修图/网站收藏/PDF工具/图片工具/文档转换等) + 卡密授权系统(CardAuth对接,30分钟试用,换卡/撤销) + 体验优化(中文默认/收藏/最近使用/菜单展开/宽屏/品牌页脚)
This commit is contained in:
commit
01ff133ac9
528 files changed
+50026
No files matched your search
@@ -0,0 +1,698 @@
|
||||
<script setup lang="ts">
|
||||
import { licenseHeaders } from '../license/license';
|
||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
||||
|
||||
const genHist = useGenHistory('ai-retouch');
|
||||
|
||||
interface TabDef {
|
||||
key: string;
|
||||
label: string;
|
||||
plugin?: string; // iopaint plugin name; undefined = lama inpaint
|
||||
}
|
||||
|
||||
const tabs: TabDef[] = [
|
||||
{ key: 'inpaint', label: '去水印/修复' },
|
||||
{ key: 'removebg', label: '抠图/去背景', plugin: 'RemoveBG' },
|
||||
{ key: 'esrgan', label: '超分辨率', plugin: 'RealESRGAN' },
|
||||
{ key: 'gfpgan', label: '人脸修复', plugin: 'GFPGAN' },
|
||||
];
|
||||
|
||||
const MAX_MB = 20;
|
||||
const WARN_KEY = 'ai-retouch-warning-acked';
|
||||
|
||||
const activeTab = ref(0);
|
||||
const warningAcked = ref(localStorage.getItem(WARN_KEY) === '1');
|
||||
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const canvasWrap = ref<HTMLElement>();
|
||||
const maskCanvas = ref<HTMLCanvasElement>();
|
||||
|
||||
const srcDataUrl = ref('');
|
||||
const imgNatural = ref({ w: 0, h: 0 });
|
||||
const fileName = ref('');
|
||||
const fileSize = ref(0);
|
||||
const dragActive = ref(false);
|
||||
const processing = ref(false);
|
||||
const elapsed = ref(0);
|
||||
const error = ref('');
|
||||
const resultUrl = ref('');
|
||||
const brushSize = ref(40); // px in image natural coords
|
||||
|
||||
let baseImg: HTMLImageElement | null = null;
|
||||
let drawing = false;
|
||||
let hasMask = ref(false);
|
||||
|
||||
const tab = computed(() => tabs[activeTab.value]);
|
||||
const canSubmit = computed(() => !!srcDataUrl.value && !processing.value
|
||||
&& (tab.value.key !== 'inpaint' || hasMask.value));
|
||||
|
||||
function ackWarning() {
|
||||
warningAcked.value = true;
|
||||
localStorage.setItem(WARN_KEY, '1');
|
||||
}
|
||||
|
||||
function pickFile() {
|
||||
fileInput.value?.click();
|
||||
}
|
||||
|
||||
function onInputChange(e: Event) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
handleFile(input.files?.[0]);
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
function onDrop(e: DragEvent) {
|
||||
dragActive.value = false;
|
||||
handleFile(e.dataTransfer?.files?.[0]);
|
||||
}
|
||||
|
||||
function handleFile(file?: File | null) {
|
||||
if (!file) return;
|
||||
if (!file.type.startsWith('image/')) {
|
||||
error.value = '请选择图片文件(png/jpg/webp 等)';
|
||||
return;
|
||||
}
|
||||
if (file.size > MAX_MB * 1024 * 1024) {
|
||||
error.value = `文件超过上限 ${MAX_MB} MB`;
|
||||
return;
|
||||
}
|
||||
error.value = '';
|
||||
resultUrl.value = '';
|
||||
fileName.value = file.name;
|
||||
fileSize.value = file.size;
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
srcDataUrl.value = String(reader.result ?? '');
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
baseImg = img;
|
||||
imgNatural.value = { w: img.naturalWidth, h: img.naturalHeight };
|
||||
nextTick(resetMaskCanvas);
|
||||
};
|
||||
img.src = srcDataUrl.value;
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
// ---------- mask painting (inpaint tab) ----------
|
||||
function resetMaskCanvas() {
|
||||
const c = maskCanvas.value;
|
||||
if (!c || !imgNatural.value.w) return;
|
||||
c.width = imgNatural.value.w;
|
||||
c.height = imgNatural.value.h;
|
||||
const ctx = c.getContext('2d')!;
|
||||
ctx.clearRect(0, 0, c.width, c.height);
|
||||
hasMask.value = false;
|
||||
}
|
||||
|
||||
function clearMask() {
|
||||
resetMaskCanvas();
|
||||
}
|
||||
|
||||
function pos(e: MouseEvent) {
|
||||
const c = maskCanvas.value!;
|
||||
const r = c.getBoundingClientRect();
|
||||
return {
|
||||
x: (e.clientX - r.left) * (c.width / r.width),
|
||||
y: (e.clientY - r.top) * (c.height / r.height),
|
||||
};
|
||||
}
|
||||
|
||||
function startDraw(e: MouseEvent) {
|
||||
if (tab.value.key !== 'inpaint') return;
|
||||
drawing = true;
|
||||
const c = maskCanvas.value!;
|
||||
const ctx = c.getContext('2d')!;
|
||||
const p = pos(e);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(p.x, p.y);
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
ctx.lineWidth = brushSize.value;
|
||||
ctx.strokeStyle = 'rgba(255, 60, 60, 0.55)';
|
||||
ctx.lineTo(p.x, p.y);
|
||||
ctx.stroke();
|
||||
hasMask.value = true;
|
||||
}
|
||||
|
||||
function moveDraw(e: MouseEvent) {
|
||||
if (!drawing) return;
|
||||
const c = maskCanvas.value!;
|
||||
const ctx = c.getContext('2d')!;
|
||||
const p = pos(e);
|
||||
ctx.lineTo(p.x, p.y);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
function endDraw() {
|
||||
drawing = false;
|
||||
}
|
||||
|
||||
function exportMask(): string {
|
||||
const c = maskCanvas.value!;
|
||||
const ctx = c.getContext('2d')!;
|
||||
const src = ctx.getImageData(0, 0, c.width, c.height);
|
||||
const out = document.createElement('canvas');
|
||||
out.width = c.width;
|
||||
out.height = c.height;
|
||||
const octx = out.getContext('2d')!;
|
||||
const imgData = octx.createImageData(c.width, c.height);
|
||||
for (let i = 0; i < src.data.length; i += 4) {
|
||||
const on = src.data[i + 3] > 20; // painted pixels
|
||||
const v = on ? 255 : 0;
|
||||
imgData.data[i] = v;
|
||||
imgData.data[i + 1] = v;
|
||||
imgData.data[i + 2] = v;
|
||||
imgData.data[i + 3] = 255;
|
||||
}
|
||||
octx.putImageData(imgData, 0, 0);
|
||||
return out.toDataURL('image/png');
|
||||
}
|
||||
|
||||
// ---------- submit ----------
|
||||
async function submit() {
|
||||
if (!canSubmit.value) return;
|
||||
processing.value = true;
|
||||
error.value = '';
|
||||
resultUrl.value = '';
|
||||
const start = performance.now();
|
||||
try {
|
||||
let url: string;
|
||||
if (tab.value.key === 'inpaint') {
|
||||
url = '/api/v1/inpaint';
|
||||
} else {
|
||||
url = '/api/v1/run_plugin_gen_image';
|
||||
}
|
||||
const body = tab.value.key === 'inpaint'
|
||||
? { image: srcDataUrl.value, mask: exportMask() }
|
||||
: {
|
||||
name: tab.value.plugin,
|
||||
image: srcDataUrl.value,
|
||||
clicks: [],
|
||||
...(tab.value.key === 'esrgan' ? { scale: 4 } : {}),
|
||||
};
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-retouch') },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.status === 403) {
|
||||
throw new Error('授权校验未通过:免费试用已结束,请购买授权或输入卡密');
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(`处理失败 HTTP ${res.status}`);
|
||||
}
|
||||
const blob = await res.blob();
|
||||
resultUrl.value = URL.createObjectURL(blob);
|
||||
if (tab.value.key === 'inpaint') clearMask();
|
||||
}
|
||||
catch (e: any) {
|
||||
error.value = e?.message ?? String(e);
|
||||
}
|
||||
finally {
|
||||
elapsed.value = Math.round(performance.now() - start);
|
||||
processing.value = false;
|
||||
if (resultUrl.value) {
|
||||
genHist.add({
|
||||
title: tab.value.label,
|
||||
detail: `原图 ${imgNatural.value.w}×${imgNatural.value.h} · 耗时 ${elapsed.value}ms`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function downloadResult() {
|
||||
if (!resultUrl.value) return;
|
||||
const a = document.createElement('a');
|
||||
a.href = resultUrl.value;
|
||||
const base = fileName.value.replace(/\.[^.]+$/, '') || 'image';
|
||||
const suffix = { inpaint: '-retouched', removebg: '-nobb', esrgan: '-4x', gfpgan: '-face' }[tab.value.key as string] ?? '';
|
||||
a.download = `${base}${suffix}.png`;
|
||||
a.click();
|
||||
}
|
||||
|
||||
function resetAll() {
|
||||
srcDataUrl.value = '';
|
||||
resultUrl.value = '';
|
||||
error.value = '';
|
||||
fileName.value = '';
|
||||
baseImg = null;
|
||||
imgNatural.value = { w: 0, h: 0 };
|
||||
}
|
||||
|
||||
function onTabChange(i: number) {
|
||||
activeTab.value = i;
|
||||
resultUrl.value = '';
|
||||
error.value = '';
|
||||
if (tabs[i].key === 'inpaint') nextTick(resetMaskCanvas);
|
||||
}
|
||||
|
||||
// fit viewport: no page scroll
|
||||
const rootEl = ref<HTMLElement>();
|
||||
const rootStyle = ref<Record<string, string>>({});
|
||||
|
||||
function fit() {
|
||||
const el = rootEl.value;
|
||||
if (!el) return;
|
||||
const top = el.getBoundingClientRect().top;
|
||||
const height = Math.max(340, window.innerHeight - top - 12);
|
||||
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
|
||||
}
|
||||
|
||||
let observer: ResizeObserver | undefined;
|
||||
onMounted(() => {
|
||||
fit();
|
||||
window.addEventListener('resize', fit);
|
||||
observer = new ResizeObserver(() => fit());
|
||||
if (rootEl.value) observer.observe(rootEl.value);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', fit);
|
||||
observer?.disconnect();
|
||||
if (resultUrl.value) URL.revokeObjectURL(resultUrl.value);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="rootEl" class="ar-root" :style="rootStyle">
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
style="display:none"
|
||||
@change="onInputChange"
|
||||
>
|
||||
|
||||
<!-- tabs -->
|
||||
<div class="ar-tabs">
|
||||
<button
|
||||
v-for="(t, i) in tabs"
|
||||
:key="t.key"
|
||||
class="ar-tab"
|
||||
:class="{ active: i === activeTab }"
|
||||
@click="onTabChange(i)"
|
||||
>
|
||||
{{ t.label }}
|
||||
</button>
|
||||
<div class="ar-tab-stats">
|
||||
<template v-if="fileName">
|
||||
{{ fileName }} · {{ (fileSize / 1024 / 1024).toFixed(1) }} MB<template v-if="elapsed"> · {{ elapsed }}ms</template>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- copyright warning (inpaint tab) -->
|
||||
<div v-if="activeTab === 0 && !warningAcked" class="ar-warn">
|
||||
<span class="ar-warn-icon">⚠️</span>
|
||||
<span class="ar-warn-text">
|
||||
去水印功能仅限用于您拥有版权或已获授权的图片,请勿用于去除他人水印或违法用途
|
||||
</span>
|
||||
<button class="ar-warn-btn" @click="ackWarning">
|
||||
我已了解
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="ar-body">
|
||||
<!-- left: upload / paint -->
|
||||
<div class="ar-left">
|
||||
<div
|
||||
class="ar-drop"
|
||||
:class="{ active: dragActive, hasImg: !!srcDataUrl }"
|
||||
@click="!srcDataUrl && pickFile()"
|
||||
@dragover.prevent="dragActive = true"
|
||||
@dragleave.prevent="dragActive = false"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<template v-if="srcDataUrl">
|
||||
<div class="ar-canvas-wrap" ref="canvasWrap">
|
||||
<img :src="srcDataUrl" draggable="false" alt="原图">
|
||||
<canvas
|
||||
ref="maskCanvas"
|
||||
class="ar-mask"
|
||||
:style="{ display: activeTab === 0 ? 'block' : 'none', cursor: activeTab === 0 ? 'crosshair' : 'default' }"
|
||||
@mousedown="startDraw"
|
||||
@mousemove="moveDraw"
|
||||
@mouseup="endDraw"
|
||||
@mouseleave="endDraw"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="ar-drop-hint">
|
||||
<div class="icon">
|
||||
⬆️
|
||||
</div>
|
||||
<div class="big">
|
||||
原图
|
||||
</div>
|
||||
<div class="sub">
|
||||
点击或拖拽文件到此处
|
||||
</div>
|
||||
<div class="sub">
|
||||
上限 {{ MAX_MB.toFixed(1) }} MB
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="srcDataUrl" class="ar-actions-left">
|
||||
<template v-if="activeTab === 0">
|
||||
<span class="ar-brush-hint">涂抹水印区域(红色)</span>
|
||||
<span class="ar-brush-label">笔刷 {{ brushSize }}</span>
|
||||
<input v-model.number="brushSize" class="ar-brush" type="range" min="10" max="120" step="5">
|
||||
<c-button size="small" @click="clearMask">
|
||||
清除涂抹
|
||||
</c-button>
|
||||
</template>
|
||||
<c-button size="small" @click="pickFile">
|
||||
换图
|
||||
</c-button>
|
||||
<c-button size="small" @click="resetAll">
|
||||
清空
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- right: result -->
|
||||
<div class="ar-right">
|
||||
<n-spin :show="processing">
|
||||
<div v-if="error" class="ar-error">
|
||||
{{ error }}
|
||||
</div>
|
||||
<div v-else-if="!resultUrl" class="ar-empty">
|
||||
<template v-if="processing">
|
||||
AI 处理中,大图可能需要 10-30 秒…
|
||||
</template>
|
||||
<template v-else>
|
||||
处理结果将显示在这里
|
||||
</template>
|
||||
</div>
|
||||
<div v-else class="ar-result">
|
||||
<figure class="ar-fig">
|
||||
<img :src="srcDataUrl" alt="原图">
|
||||
<figcaption>原图</figcaption>
|
||||
</figure>
|
||||
<figure class="ar-fig">
|
||||
<img :src="resultUrl" alt="结果">
|
||||
<figcaption>{{ tab.label }}结果</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</n-spin>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- bottom bar -->
|
||||
<div class="ar-bottom">
|
||||
<span class="ar-tip">
|
||||
{{ activeTab === 0 ? '先涂抹水印区域,再提交修复' : '上传图片后点击提交' }}
|
||||
</span>
|
||||
<c-button
|
||||
type="primary"
|
||||
class="ar-submit"
|
||||
:disabled="!canSubmit"
|
||||
:style="{ backgroundColor: canSubmit ? '#18a058' : undefined }"
|
||||
@click="submit"
|
||||
>
|
||||
{{ processing ? '处理中…' : '提交修复' }}
|
||||
</c-button>
|
||||
<c-button v-if="resultUrl" @click="downloadResult">
|
||||
下载结果
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<GenHistory tool="ai-retouch" position="right" label="修图记录" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.ar-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
box-sizing: border-box;
|
||||
background: #fff;
|
||||
border: 1px solid rgba(128, 128, 128, 0.2);
|
||||
border-radius: 12px;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
// ---- tabs ----
|
||||
.ar-tabs {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 10px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.ar-tab {
|
||||
padding: 7px 16px;
|
||||
border-radius: 999px;
|
||||
border: none;
|
||||
background: rgba(128, 128, 128, 0.12);
|
||||
color: #666;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
|
||||
&.active {
|
||||
background: #18a058;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&:not(.active):hover {
|
||||
background: rgba(128, 128, 128, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
.ar-tab-stats {
|
||||
margin-left: auto;
|
||||
font-size: 12.5px;
|
||||
opacity: 0.55;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- warning ----
|
||||
.ar-warn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: rgba(240, 160, 0, 0.1);
|
||||
border: 1px solid rgba(240, 160, 0, 0.45);
|
||||
border-radius: 8px;
|
||||
padding: 8px 12px;
|
||||
margin-bottom: 10px;
|
||||
flex-shrink: 0;
|
||||
font-size: 12.5px;
|
||||
|
||||
.ar-warn-text {
|
||||
flex: 1;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.ar-warn-btn {
|
||||
flex-shrink: 0;
|
||||
border: 1px solid #e09000;
|
||||
background: transparent;
|
||||
color: #c07800;
|
||||
border-radius: 5px;
|
||||
padding: 3px 12px;
|
||||
font-size: 12.5px;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover { background: rgba(240, 160, 0, 0.15); }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- body ----
|
||||
.ar-body {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@media (max-width: 760px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.ar-left {
|
||||
flex: 1 1 55%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.ar-right {
|
||||
flex: 1 1 45%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.ar-drop {
|
||||
flex: 1;
|
||||
min-height: 180px;
|
||||
border: 2px dashed rgba(128, 128, 128, 0.45);
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.2s, background-color 0.2s;
|
||||
box-sizing: border-box;
|
||||
|
||||
&:hover,
|
||||
&.active {
|
||||
border-color: #18a058;
|
||||
background: rgba(24, 160, 88, 0.05);
|
||||
}
|
||||
|
||||
&.hasImg {
|
||||
cursor: default;
|
||||
padding: 8px;
|
||||
background: repeating-conic-gradient(#f5f5f5 0% 25%, #fff 0% 50%) 50% / 20px 20px;
|
||||
}
|
||||
|
||||
.ar-drop-hint {
|
||||
text-align: center;
|
||||
opacity: 0.7;
|
||||
|
||||
.icon { font-size: 40px; }
|
||||
.big { font-size: 18px; font-weight: 600; margin-top: 6px; }
|
||||
.sub { font-size: 12.5px; opacity: 0.7; margin-top: 5px; }
|
||||
}
|
||||
}
|
||||
|
||||
.ar-canvas-wrap {
|
||||
position: relative;
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
line-height: 0;
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.ar-mask {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
touch-action: none;
|
||||
}
|
||||
}
|
||||
|
||||
.ar-actions-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
flex-shrink: 0;
|
||||
flex-wrap: wrap;
|
||||
font-size: 12.5px;
|
||||
|
||||
.ar-brush-hint { opacity: 0.6; }
|
||||
.ar-brush-label { opacity: 0.85; min-width: 66px; }
|
||||
|
||||
.ar-brush {
|
||||
width: 120px;
|
||||
accent-color: #18a058;
|
||||
}
|
||||
}
|
||||
|
||||
.ar-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
min-height: 160px;
|
||||
border: 1px solid rgba(128, 128, 128, 0.25);
|
||||
border-radius: 8px;
|
||||
opacity: 0.5;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.ar-error {
|
||||
color: #d03050;
|
||||
font-size: 13px;
|
||||
padding: 12px;
|
||||
border: 1px solid rgba(208, 48, 80, 0.35);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.ar-result {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
|
||||
@media (max-width: 760px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.ar-fig {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
border: 1px solid rgba(128, 128, 128, 0.25);
|
||||
border-radius: 8px;
|
||||
padding: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: repeating-conic-gradient(#f7f7f7 0% 25%, #fff 0% 50%) 50% / 16px 16px;
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
figcaption {
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
opacity: 0.6;
|
||||
margin-top: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- bottom ----
|
||||
.ar-bottom {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.ar-tip {
|
||||
margin-right: auto;
|
||||
font-size: 12.5px;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.ar-submit {
|
||||
background: #18a058 !important;
|
||||
color: #fff;
|
||||
min-width: 120px;
|
||||
font-weight: 600;
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Wand } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.ai-retouch.title'),
|
||||
path: '/ai-retouch',
|
||||
description: translate('tools.ai-retouch.description'),
|
||||
keywords: ['ai', 'retouch', 'watermark', 'remove', 'background', 'upscale', 'face', 'repair', 'inpaint', '抠图', '去水印', '超分', '修复', '去背景', '修图'],
|
||||
component: () => import('./ai-retouch.vue'),
|
||||
icon: Wand,
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
<script setup lang="ts">
|
||||
import figlet from 'figlet';
|
||||
import TextareaCopyable from '@/components/TextareaCopyable.vue';
|
||||
|
||||
const input = ref('Ascii ART');
|
||||
const font = useStorage('ascii-text-drawer:font', 'Standard');
|
||||
const width = useStorage('ascii-text-drawer:width', 80);
|
||||
const output = ref('');
|
||||
const errored = ref(false);
|
||||
const processing = ref(false);
|
||||
|
||||
figlet.defaults({ fontPath: '//unpkg.com/figlet@1.6.0/fonts/' });
|
||||
|
||||
watchEffect(async () => {
|
||||
processing.value = true;
|
||||
try {
|
||||
const options: figlet.Options = {
|
||||
font: font.value as figlet.Fonts,
|
||||
width: width.value,
|
||||
whitespaceBreak: true,
|
||||
};
|
||||
output.value = await (new Promise<string>((resolve, reject) =>
|
||||
figlet.text(input.value, options,
|
||||
(err, text) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(text ?? '');
|
||||
})));
|
||||
errored.value = false;
|
||||
}
|
||||
catch (e: any) {
|
||||
errored.value = true;
|
||||
}
|
||||
processing.value = false;
|
||||
});
|
||||
|
||||
const fonts = ['1Row', '3-D', '3D Diagonal', '3D-ASCII', '3x5', '4Max', '5 Line Oblique', 'AMC 3 Line', 'AMC 3 Liv1', 'AMC AAA01', 'AMC Neko', 'AMC Razor', 'AMC Razor2', 'AMC Slash', 'AMC Slider', 'AMC Thin', 'AMC Tubes', 'AMC Untitled', 'ANSI Shadow', 'ASCII New Roman', 'Acrobatic', 'Alligator', 'Alligator2', 'Alpha', 'Alphabet', 'Arrows', 'Avatar', 'B1FF', 'B1FF', 'Banner', 'Banner3-D', 'Banner3', 'Banner4', 'Barbwire', 'Basic', 'Bear', 'Bell', 'Benjamin', 'Big Chief', 'Big Money-ne', 'Big Money-nw', 'Big Money-se', 'Big Money-sw', 'Big', 'Bigfig', 'Binary', 'Block', 'Blocks', 'Bloody', 'Bolger', 'Braced', 'Bright', 'Broadway KB', 'Broadway', 'Bubble', 'Bulbhead', 'Caligraphy', 'Caligraphy2', 'Calvin S', 'Cards', 'Catwalk', 'Chiseled', 'Chunky', 'Coinstak', 'Cola', 'Colossal', 'Computer', 'Contessa', 'Contrast', 'Cosmike', 'Crawford', 'Crawford2', 'Crazy', 'Cricket', 'Cursive', 'Cyberlarge', 'Cybermedium', 'Cybersmall', 'Cygnet', 'DANC4', 'DOS Rebel', 'DWhistled', 'Dancing Font', 'Decimal', 'Def Leppard', 'Delta Corps Priest 1', 'Diamond', 'Diet Cola', 'Digital', 'Doh', 'Doom', 'Dot Matrix', 'Double Shorts', 'Double', 'Dr Pepper', 'Efti Chess', 'Efti Font', 'Efti Italic', 'Efti Piti', 'Efti Robot', 'Efti Wall', 'Efti Water', 'Electronic', 'Elite', 'Epic', 'Fender', 'Filter', 'Fire Font-k', 'Fire Font-s', 'Flipped', 'Flower Power', 'Four Tops', 'Fraktur', 'Fun Face', 'Fun Faces', 'Fuzzy', 'Georgi16', 'Georgia11', 'Ghost', 'Ghoulish', 'Glenyn', 'Goofy', 'Gothic', 'Graceful', 'Gradient', 'Graffiti', 'Greek', 'Heart Left', 'Heart Right', 'Henry 3D', 'Hex', 'Hieroglyphs', 'Hollywood', 'Horizontal Left', 'Horizontal Right', 'ICL-1900', 'Impossible', 'Invita', 'Isometric1', 'Isometric2', 'Isometric3', 'Isometric4', 'Italic', 'Ivrit', 'JS Block Letters', 'JS Bracket Letters', 'JS Capital Curves', 'JS Cursive', 'JS Stick Letters', 'Jacky', 'Jazmine', 'Jerusalem', 'Katakana', 'Kban', 'Keyboard', 'Knob', 'Konto Slant', 'Konto', 'LCD', 'Larry 3D 2', 'Larry 3D', 'Lean', 'Letters', 'Lil Devil', 'Line Blocks', 'Linux', 'Lockergnome', 'Madrid', 'Marquee', 'Maxfour', 'Merlin1', 'Merlin2', 'Mike', 'Mini', 'Mirror', 'Mnemonic', 'Modular', 'Morse', 'Morse2', 'Moscow', 'Mshebrew210', 'Muzzle', 'NScript', 'NT Greek', 'NV Script', 'Nancyj-Fancy', 'Nancyj-Improved', 'Nancyj-Underlined', 'Nancyj', 'Nipples', 'O8', 'OS2', 'Octal', 'Ogre', 'Old Banner', 'Patorjk\'s Cheese', 'Patorjk-HeX', 'Pawp', 'Peaks Slant', 'Peaks', 'Pebbles', 'Pepper', 'Poison', 'Puffy', 'Puzzle', 'Pyramid', 'Rammstein', 'Rectangles', 'Red Phoenix', 'Relief', 'Relief2', 'Reverse', 'Roman', 'Rot13', 'Rot13', 'Rotated', 'Rounded', 'Rowan Cap', 'Rozzo', 'Runic', 'Runyc', 'S Blood', 'SL Script', 'Santa Clara', 'Script', 'Serifcap', 'Shadow', 'Shimrod', 'Short', 'Slant Relief', 'Slant', 'Slide', 'Small Caps', 'Small Isometric1', 'Small Keyboard', 'Small Poison', 'Small Script', 'Small Shadow', 'Small Slant', 'Small Tengwar', 'Small', 'Soft', 'Speed', 'Spliff', 'Stacey', 'Stampate', 'Stampatello', 'Standard', 'Star Strips', 'Star Wars', 'Stellar', 'Stforek', 'Stick Letters', 'Stop', 'Straight', 'Stronger Than All', 'Sub-Zero', 'Swamp Land', 'Swan', 'Sweet', 'THIS', 'Tanja', 'Tengwar', 'Term', 'Test1', 'The Edge', 'Thick', 'Thin', 'Thorned', 'Three Point', 'Ticks Slant', 'Ticks', 'Tiles', 'Tinker-Toy', 'Tombstone', 'Train', 'Trek', 'Tsalagi', 'Tubular', 'Twisted', 'Two Point', 'USA Flag', 'Univers', 'Varsity', 'Wavy', 'Weird', 'Wet Letter', 'Whimsy', 'Wow'];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card style="max-width: 600px;">
|
||||
<c-input-text
|
||||
v-model:value="input"
|
||||
label="Your text:"
|
||||
placeholder="Your text to draw"
|
||||
raw-text
|
||||
multiline
|
||||
rows="4"
|
||||
/>
|
||||
|
||||
<n-divider />
|
||||
|
||||
<n-grid cols="4" x-gap="12" w-full>
|
||||
<n-gi span="2">
|
||||
<c-select
|
||||
v-model:value="font"
|
||||
label-position="top"
|
||||
label="Font:"
|
||||
:options="fonts"
|
||||
searchable="true"
|
||||
placeholder="Select font to use"
|
||||
/>
|
||||
</n-gi>
|
||||
<n-gi span="2">
|
||||
<n-form-item label="Width:" label-placement="top" label-width="100" :show-feedback="false">
|
||||
<n-input-number v-model:value="width" min="0" max="10000" w-full placeholder="Width of the text" />
|
||||
</n-form-item>
|
||||
</n-gi>
|
||||
</n-grid>
|
||||
|
||||
<n-divider />
|
||||
|
||||
<div v-if="processing" flex items-center justify-center>
|
||||
<n-spin size="medium" />
|
||||
<span class="ml-2">Loading font...</span>
|
||||
</div>
|
||||
|
||||
<c-alert v-if="errored" mt-1 text-center type="error">
|
||||
Current settings resulted in error.
|
||||
</c-alert>
|
||||
|
||||
<n-form-item v-if="!processing && !errored" label="Ascii Art text:">
|
||||
<TextareaCopyable
|
||||
:value="output"
|
||||
mb-1 mt-1
|
||||
copy-placement="outside"
|
||||
/>
|
||||
</n-form-item>
|
||||
</c-card>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Artboard } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: 'ASCII Art Text Generator',
|
||||
path: '/ascii-text-drawer',
|
||||
description: 'Create ASCII art text with many fonts and styles.',
|
||||
keywords: ['ascii', 'asciiart', 'text', 'drawer'],
|
||||
component: () => import('./ascii-text-drawer.vue'),
|
||||
icon: Artboard,
|
||||
createdAt: new Date('2024-03-03'),
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
<script setup lang="ts">
|
||||
import { useBase64 } from '@vueuse/core';
|
||||
import type { Ref } from 'vue';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
import { getExtensionFromMimeType, getMimeTypeFromBase64, previewImageFromBase64, useDownloadFileFromBase64Refs } from '@/composable/downloadBase64';
|
||||
import { useValidation } from '@/composable/validation';
|
||||
import { isValidBase64 } from '@/utils/base64';
|
||||
|
||||
const fileName = ref('file');
|
||||
const fileExtension = ref('');
|
||||
const base64Input = ref('');
|
||||
const { download } = useDownloadFileFromBase64Refs(
|
||||
{
|
||||
source: base64Input,
|
||||
filename: fileName,
|
||||
extension: fileExtension,
|
||||
});
|
||||
const base64InputValidation = useValidation({
|
||||
source: base64Input,
|
||||
rules: [
|
||||
{
|
||||
message: 'Invalid base 64 string',
|
||||
validator: value => isValidBase64(value.trim()),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
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() {
|
||||
if (!base64InputValidation.isValid) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
download();
|
||||
}
|
||||
catch (_) {
|
||||
//
|
||||
}
|
||||
}
|
||||
|
||||
const fileInput = ref() as Ref<File>;
|
||||
const { base64: fileBase64 } = useBase64(fileInput);
|
||||
const { copy: copyFileBase64 } = useCopy({ source: fileBase64, text: 'Base64 string copied to the clipboard' });
|
||||
|
||||
async function onUpload(file: File) {
|
||||
if (file) {
|
||||
fileInput.value = file;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<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
|
||||
v-model:value="base64Input"
|
||||
multiline
|
||||
placeholder="Put your base64 file string here..."
|
||||
rows="5"
|
||||
:validation="base64InputValidation"
|
||||
mb-2
|
||||
/>
|
||||
|
||||
<div flex justify-center py-2>
|
||||
<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()">
|
||||
Download file
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
|
||||
<c-card title="File to base64">
|
||||
<c-file-upload title="Drag and drop a file here, or click to select a file" @file-upload="onUpload" />
|
||||
<c-input-text :value="fileBase64" multiline readonly placeholder="File in base64 will be here" rows="5" my-2 />
|
||||
|
||||
<div flex justify-center>
|
||||
<c-button @click="copyFileBase64()">
|
||||
Copy
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
::v-deep(.n-upload-trigger) {
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { FileDigit } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.base64-file-converter.title'),
|
||||
path: '/base64-file-converter',
|
||||
description: translate('tools.base64-file-converter.description'),
|
||||
keywords: ['base64', 'converter', 'upload', 'image', 'file', 'conversion', 'web', 'data', 'format'],
|
||||
component: () => import('./base64-file-converter.vue'),
|
||||
icon: FileDigit,
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
<script setup lang="ts">
|
||||
import { useCopy } from '@/composable/copy';
|
||||
import { base64ToText, isValidBase64, textToBase64 } from '@/utils/base64';
|
||||
import { withDefaultOnError } from '@/utils/defaults';
|
||||
|
||||
const encodeUrlSafe = useStorage('base64-string-converter--encode-url-safe', false);
|
||||
const decodeUrlSafe = useStorage('base64-string-converter--decode-url-safe', false);
|
||||
|
||||
const textInput = ref('');
|
||||
const base64Output = computed(() => textToBase64(textInput.value, { makeUrlSafe: encodeUrlSafe.value }));
|
||||
const { copy: copyTextBase64 } = useCopy({ source: base64Output, text: 'Base64 string copied to the clipboard' });
|
||||
|
||||
const base64Input = ref('');
|
||||
const textOutput = computed(() =>
|
||||
withDefaultOnError(() => base64ToText(base64Input.value.trim(), { makeUrlSafe: decodeUrlSafe.value }), ''),
|
||||
);
|
||||
const { copy: copyText } = useCopy({ source: textOutput, text: 'String copied to the clipboard' });
|
||||
const b64ValidationRules = [
|
||||
{
|
||||
message: 'Invalid base64 string',
|
||||
validator: (value: string) => isValidBase64(value.trim(), { makeUrlSafe: decodeUrlSafe.value }),
|
||||
},
|
||||
];
|
||||
const b64ValidationWatch = [decodeUrlSafe];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card title="String to base64">
|
||||
<n-form-item label="Encode URL safe" label-placement="left">
|
||||
<n-switch v-model:value="encodeUrlSafe" />
|
||||
</n-form-item>
|
||||
<c-input-text
|
||||
v-model:value="textInput"
|
||||
multiline
|
||||
placeholder="Put your string here..."
|
||||
rows="5"
|
||||
label="String to encode"
|
||||
raw-text
|
||||
mb-5
|
||||
/>
|
||||
|
||||
<c-input-text
|
||||
label="Base64 of string"
|
||||
:value="base64Output"
|
||||
multiline
|
||||
readonly
|
||||
placeholder="The base64 encoding of your string will be here"
|
||||
rows="5"
|
||||
mb-5
|
||||
/>
|
||||
|
||||
<div flex justify-center>
|
||||
<c-button @click="copyTextBase64()">
|
||||
Copy base64
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
|
||||
<c-card title="Base64 to string">
|
||||
<n-form-item label="Decode URL safe" label-placement="left">
|
||||
<n-switch v-model:value="decodeUrlSafe" />
|
||||
</n-form-item>
|
||||
<c-input-text
|
||||
v-model:value="base64Input"
|
||||
multiline
|
||||
placeholder="Your base64 string..."
|
||||
rows="5"
|
||||
:validation-rules="b64ValidationRules"
|
||||
:validation-watch="b64ValidationWatch"
|
||||
label="Base64 string to decode"
|
||||
mb-5
|
||||
/>
|
||||
|
||||
<c-input-text
|
||||
v-model:value="textOutput"
|
||||
label="Decoded string"
|
||||
placeholder="The decoded string will be here"
|
||||
multiline
|
||||
rows="5"
|
||||
readonly
|
||||
mb-5
|
||||
/>
|
||||
|
||||
<div flex justify-center>
|
||||
<c-button @click="copyText()">
|
||||
Copy decoded string
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
</template>
|
||||
@@ -0,0 +1,13 @@
|
||||
import { FileDigit } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.base64-string-converter.title'),
|
||||
path: '/base64-string-converter',
|
||||
description: translate('tools.base64-string-converter.description'),
|
||||
keywords: ['base64', 'converter', 'conversion', 'web', 'data', 'format', 'atob', 'btoa'],
|
||||
component: () => import('./base64-string-converter.vue'),
|
||||
icon: FileDigit,
|
||||
redirectFrom: ['/file-to-base64', '/base64-converter'],
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import { useCopy } from '@/composable/copy';
|
||||
import { textToBase64 } from '@/utils/base64';
|
||||
|
||||
const username = ref('');
|
||||
const password = ref('');
|
||||
const header = computed(() => `Authorization: Basic ${textToBase64(`${username.value}:${password.value}`)}`);
|
||||
|
||||
const { copy } = useCopy({ source: header, text: 'Header copied to the clipboard' });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-input-text v-model:value="username" label="Username" placeholder="Your username..." clearable raw-text mb-5 />
|
||||
<c-input-text
|
||||
v-model:value="password"
|
||||
label="Password"
|
||||
placeholder="Your password..."
|
||||
clearable
|
||||
raw-text
|
||||
mb-2
|
||||
type="password"
|
||||
/>
|
||||
|
||||
<c-card>
|
||||
<n-statistic label="Authorization header:" class="header">
|
||||
<n-scrollbar x-scrollable style="max-width: 550px; margin-bottom: -10px; padding-bottom: 10px" trigger="none">
|
||||
{{ header }}
|
||||
</n-scrollbar>
|
||||
</n-statistic>
|
||||
</c-card>
|
||||
<div mt-5 flex justify-center>
|
||||
<c-button @click="copy()">
|
||||
Copy header
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
::v-deep(.n-statistic-value__content) {
|
||||
font-family: monospace;
|
||||
font-size: 17px !important;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,22 @@
|
||||
import { PasswordRound } from '@vicons/material';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.basic-auth-generator.title'),
|
||||
path: '/basic-auth-generator',
|
||||
description: translate('tools.basic-auth-generator.description'),
|
||||
keywords: [
|
||||
'basic',
|
||||
'auth',
|
||||
'generator',
|
||||
'username',
|
||||
'password',
|
||||
'base64',
|
||||
'authentication',
|
||||
'header',
|
||||
'authorization',
|
||||
],
|
||||
component: () => import('./basic-auth-generator.vue'),
|
||||
icon: PasswordRound,
|
||||
});
|
||||
@@ -0,0 +1,437 @@
|
||||
<script setup lang="ts">
|
||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
||||
|
||||
const genHist = useGenHistory('barcode-batch');
|
||||
import bwipjs from 'bwip-js';
|
||||
import { zipSync } from 'fflate';
|
||||
|
||||
interface BarcodeType {
|
||||
label: string;
|
||||
value: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
const barcodeTypes: BarcodeType[] = [
|
||||
{ label: 'EAN 8', value: 'ean8', hint: '7-8 位数字' },
|
||||
{ label: 'EAN 13', value: 'ean13', hint: '12-13 位数字' },
|
||||
{ label: 'UPC-A', value: 'upca', hint: '11-12 位数字' },
|
||||
{ label: 'standard 2 of 5 (industrial)', value: 'industrial2of5', hint: '纯数字' },
|
||||
{ label: 'interleaved 2 of 5', value: 'interleaved2of5', hint: '偶数位数字' },
|
||||
{ label: 'CODE11', value: 'code11' },
|
||||
{ label: 'CODE39', value: 'code39' },
|
||||
{ label: 'CODE93', value: 'code93' },
|
||||
{ label: 'CODE128', value: 'code128' },
|
||||
{ label: 'Codabar', value: 'rationalizedCodabar', hint: '如 A123456A' },
|
||||
{ label: 'MSI', value: 'msi', hint: '纯数字' },
|
||||
{ label: 'Data Matrix', value: 'datamatrix' },
|
||||
];
|
||||
|
||||
const MM = 72 / 25.4; // px per mm at 72dpi
|
||||
|
||||
const input = ref('');
|
||||
const barcodeType = ref('code128');
|
||||
const barcodeWidth = ref(2); // module scale
|
||||
const barcodeHeight = ref(80); // bar height in px
|
||||
const fontSize = ref(14); // text height in px
|
||||
const previewWidth = ref(280); // display width in px
|
||||
const foreColor = ref('#000000');
|
||||
const backgroundColor = ref('#ffffff');
|
||||
const showValue = ref(true);
|
||||
const trimBlank = ref(true);
|
||||
const doubleRow = ref(false);
|
||||
|
||||
const results = ref<{ text: string; url?: string; error?: string }[]>([]);
|
||||
const generating = ref(false);
|
||||
|
||||
const lines = computed(() => {
|
||||
const raw = input.value.split('\n');
|
||||
const list = trimBlank.value ? raw.map(l => l.trim()).filter(Boolean) : raw;
|
||||
return list.slice(0, 2000);
|
||||
});
|
||||
|
||||
function generateOne(text: string): { url?: string; error?: string } {
|
||||
try {
|
||||
const canvas = document.createElement('canvas');
|
||||
const scale = barcodeWidth.value;
|
||||
bwipjs.toCanvas(canvas, {
|
||||
bcid: barcodeType.value,
|
||||
text,
|
||||
scaleX: scale,
|
||||
scaleY: scale,
|
||||
height: barcodeHeight.value / (MM * scale),
|
||||
textsize: fontSize.value / scale,
|
||||
includetext: showValue.value,
|
||||
paddingwidth: 10,
|
||||
paddingtop: 4,
|
||||
paddingbottom: 4,
|
||||
barcolor: foreColor.value,
|
||||
background: backgroundColor.value,
|
||||
} as any);
|
||||
return { url: canvas.toDataURL('image/png') };
|
||||
}
|
||||
catch (e: any) {
|
||||
return { error: e?.message ?? String(e) };
|
||||
}
|
||||
}
|
||||
|
||||
function generate() {
|
||||
if (!lines.value.length) {
|
||||
results.value = [];
|
||||
return;
|
||||
}
|
||||
generating.value = true;
|
||||
// defer heavy loop so the UI can paint the loading state first
|
||||
setTimeout(() => {
|
||||
results.value = lines.value.map((text) => {
|
||||
const { url, error } = generateOne(text);
|
||||
return { text, url, error };
|
||||
});
|
||||
generating.value = false;
|
||||
}, 50);
|
||||
}
|
||||
|
||||
function downloadOne(item: { text: string; url?: string }) {
|
||||
if (!item.url) {
|
||||
return;
|
||||
}
|
||||
const a = document.createElement('a');
|
||||
a.href = item.url;
|
||||
a.download = `barcode-${sanitize(item.text)}.png`;
|
||||
a.click();
|
||||
genHist.add({ title: item.text.slice(0, 60), detail: '单个条码下载' });
|
||||
}
|
||||
|
||||
function sanitize(text: string) {
|
||||
return text.replace(/[^\w\u4e00-\u9fa5-]+/g, '_').slice(0, 60) || 'barcode';
|
||||
}
|
||||
|
||||
function downloadAll() {
|
||||
const valid = results.value.filter(r => r.url);
|
||||
if (!valid.length) {
|
||||
return;
|
||||
}
|
||||
const files: Record<string, Uint8Array> = {};
|
||||
valid.forEach((r, i) => {
|
||||
const base64 = r.url!.split(',')[1];
|
||||
const bin = atob(base64);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let j = 0; j < bin.length; j++) {
|
||||
bytes[j] = bin.charCodeAt(j);
|
||||
}
|
||||
files[`${String(i + 1).padStart(3, '0')}-${sanitize(r.text)}.png`] = bytes;
|
||||
});
|
||||
const zipped = zipSync(files, { level: 6 });
|
||||
const blob = new Blob([zipped], { type: 'application/zip' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'barcodes.zip';
|
||||
a.click();
|
||||
genHist.add({ title: `${valid.length} 个条码打包`, detail: `${valid[0]?.text.slice(0, 40)}…` });
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function loadExample() {
|
||||
barcodeType.value = 'code128';
|
||||
input.value = [
|
||||
'https://it-tools.tech',
|
||||
'IT-TOOLS-2024',
|
||||
'HELLO-WORLD',
|
||||
'BATCH-001',
|
||||
'11112222',
|
||||
].join('\n');
|
||||
generate();
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
input.value = '';
|
||||
results.value = [];
|
||||
}
|
||||
|
||||
// regenerate automatically when options change (debounced)
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
watch([input, barcodeType, barcodeWidth, barcodeHeight, fontSize, foreColor, backgroundColor, showValue, trimBlank], () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(generate, 400);
|
||||
});
|
||||
|
||||
// fit the page to the viewport: no page scrolling, panes scroll internally
|
||||
const rootEl = ref<HTMLElement>();
|
||||
const rootStyle = ref<Record<string, string>>({});
|
||||
|
||||
function fit() {
|
||||
const el = rootEl.value;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
const top = el.getBoundingClientRect().top;
|
||||
const height = Math.max(300, window.innerHeight - top - 12);
|
||||
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
|
||||
}
|
||||
|
||||
let observer: ResizeObserver | undefined;
|
||||
onMounted(() => {
|
||||
fit();
|
||||
window.addEventListener('resize', fit);
|
||||
observer = new ResizeObserver(() => fit());
|
||||
if (rootEl.value) {
|
||||
observer.observe(rootEl.value);
|
||||
}
|
||||
generate();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', fit);
|
||||
observer?.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="rootEl" class="batch-bc-root" :style="rootStyle">
|
||||
<!-- toolbar: actions pinned right -->
|
||||
<div class="toolbar">
|
||||
<div class="stats">
|
||||
<template v-if="results.length">
|
||||
共 {{ results.length }} 个条形码<template v-if="results.filter(r => r.error).length">,{{ results.filter(r => r.error).length }} 个失败</template>
|
||||
</template>
|
||||
</div>
|
||||
<c-button type="primary" @click="generate">
|
||||
生成条形码
|
||||
</c-button>
|
||||
<c-button @click="downloadAll">
|
||||
打包下载全部
|
||||
</c-button>
|
||||
<c-button @click="loadExample">
|
||||
举个例子
|
||||
</c-button>
|
||||
<c-button @click="clearAll">
|
||||
清空
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<div class="body">
|
||||
<!-- left: form -->
|
||||
<div class="form-pane">
|
||||
<c-input-text
|
||||
v-model:value="input"
|
||||
label="条形码数值(每行一个)"
|
||||
multiline
|
||||
:rows="3"
|
||||
placeholder="每行一个条形码数值,点「举个例子」看格式"
|
||||
mb-8px
|
||||
/>
|
||||
<div class="form-grid">
|
||||
<n-form-item label="码制" size="small" class="span2">
|
||||
<c-select
|
||||
v-model:value="barcodeType"
|
||||
:options="barcodeTypes.map(t => ({ label: t.label + (t.hint ? ` (${t.hint})` : ''), value: t.value }))"
|
||||
/>
|
||||
</n-form-item>
|
||||
<n-form-item label="条码宽度" size="small">
|
||||
<n-input-number v-model:value="barcodeWidth" :min="1" :max="6" style="width:100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="条码高度" size="small">
|
||||
<n-input-number v-model:value="barcodeHeight" :min="30" :max="200" :step="10" style="width:100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="文字大小" size="small">
|
||||
<n-input-number v-model:value="fontSize" :min="8" :max="32" style="width:100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="预览宽度" size="small">
|
||||
<n-slider v-model:value="previewWidth" :min="120" :max="600" :step="10" />
|
||||
</n-form-item>
|
||||
<n-form-item label="前景色" size="small">
|
||||
<n-color-picker v-model:value="foreColor" :modes="['hex']" :show-alpha="false" />
|
||||
</n-form-item>
|
||||
<n-form-item label="背景色" size="small">
|
||||
<n-color-picker v-model:value="backgroundColor" :modes="['hex']" :show-alpha="false" />
|
||||
</n-form-item>
|
||||
<n-form-item label="显示数值" size="small">
|
||||
<n-switch v-model:value="showValue" size="small" />
|
||||
</n-form-item>
|
||||
<n-form-item label="去空白行" size="small">
|
||||
<n-switch v-model:value="trimBlank" size="small" />
|
||||
</n-form-item>
|
||||
<n-form-item label="一行两个" size="small">
|
||||
<n-switch v-model:value="doubleRow" size="small" />
|
||||
</n-form-item>
|
||||
<div class="span2 hint">
|
||||
条码宽度=模块精细度,条码高度=条纹像素高,改完自动重新生成
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- right: results -->
|
||||
<div class="result-pane">
|
||||
<n-spin :show="generating">
|
||||
<div v-if="!results.length" class="empty">
|
||||
输入数值后自动生成,或点击「举个例子」
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="result-grid"
|
||||
:style="{ gridTemplateColumns: `repeat(${doubleRow ? 2 : 1}, minmax(0, 1fr))` }"
|
||||
>
|
||||
<div v-for="(item, idx) in results" :key="idx" class="result-item">
|
||||
<template v-if="item.url">
|
||||
<img
|
||||
:src="item.url"
|
||||
:style="{ width: previewWidth + 'px', maxWidth: '100%', height: 'auto' }"
|
||||
:alt="item.text"
|
||||
>
|
||||
<div class="item-actions">
|
||||
<span class="item-text">{{ item.text }}</span>
|
||||
<c-button size="small" @click="downloadOne(item)">
|
||||
下载
|
||||
</c-button>
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="item-error">
|
||||
{{ item.text }}:{{ item.error }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</n-spin>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<GenHistory tool="barcode-batch" position="bottom" label="生成记录" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.batch-bc-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
padding-bottom: 12px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.stats {
|
||||
margin-right: auto;
|
||||
font-size: 13px;
|
||||
opacity: 0.65;
|
||||
}
|
||||
}
|
||||
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 16px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@media (max-width: 760px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.form-pane {
|
||||
flex: 0 0 400px;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
|
||||
@media (max-width: 760px) {
|
||||
flex: 0 0 auto;
|
||||
overflow-y: visible;
|
||||
}
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0 12px;
|
||||
|
||||
.span2 {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
opacity: 0.55;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
// compact form items
|
||||
:deep(.n-form-item) {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
:deep(.n-form-item-label) {
|
||||
padding-bottom: 4px !important;
|
||||
font-size: 12px;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.result-pane {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
min-height: 120px;
|
||||
opacity: 0.55;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.result-grid {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.result-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border: 1px solid rgba(128, 128, 128, 0.25);
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
box-sizing: border-box;
|
||||
|
||||
img {
|
||||
display: block;
|
||||
object-fit: contain;
|
||||
}
|
||||
}
|
||||
|
||||
.item-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.item-text {
|
||||
font-size: 12px;
|
||||
opacity: 0.7;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.item-error {
|
||||
font-size: 12px;
|
||||
color: #d03050;
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Barcode } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.barcode-batch-generator.title'),
|
||||
path: '/barcode-batch-generator',
|
||||
description: translate('tools.barcode-batch-generator.description'),
|
||||
keywords: ['barcode', 'batch', 'code128', 'code39', 'ean', 'upc', 'product', 'label', 'print', 'generator', '条形码', '批量', '条码', '码'],
|
||||
component: () => import('./barcode-batch-generator.vue'),
|
||||
icon: Barcode,
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
<script setup lang="ts">
|
||||
import { compareSync, hashSync } from 'bcryptjs';
|
||||
import { useThemeVars } from 'naive-ui';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
|
||||
const themeVars = useThemeVars();
|
||||
|
||||
const input = ref('');
|
||||
const saltCount = ref(10);
|
||||
const hashed = computed(() => hashSync(input.value, saltCount.value));
|
||||
const { copy } = useCopy({ source: hashed, text: 'Hashed string copied to the clipboard' });
|
||||
|
||||
const compareString = ref('');
|
||||
const compareHash = ref('');
|
||||
const compareMatch = computed(() => compareSync(compareString.value, compareHash.value));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card title="Hash">
|
||||
<c-input-text
|
||||
v-model:value="input"
|
||||
placeholder="Your string to bcrypt..."
|
||||
raw-text
|
||||
label="Your string: "
|
||||
label-position="left"
|
||||
label-align="right"
|
||||
label-width="120px"
|
||||
mb-2
|
||||
/>
|
||||
<n-form-item label="Salt count: " label-placement="left" label-width="120">
|
||||
<n-input-number v-model:value="saltCount" placeholder="Salt rounds..." :max="100" :min="0" w-full />
|
||||
</n-form-item>
|
||||
|
||||
<c-input-text :value="hashed" readonly text-center />
|
||||
|
||||
<div mt-5 flex justify-center>
|
||||
<c-button @click="copy()">
|
||||
Copy hash
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
|
||||
<c-card title="Compare string with hash">
|
||||
<n-form label-width="120">
|
||||
<n-form-item label="Your string: " label-placement="left">
|
||||
<c-input-text v-model:value="compareString" placeholder="Your string to compare..." raw-text />
|
||||
</n-form-item>
|
||||
<n-form-item label="Your hash: " label-placement="left">
|
||||
<c-input-text v-model:value="compareHash" placeholder="Your hash to compare..." raw-text />
|
||||
</n-form-item>
|
||||
<n-form-item label="Do they match ? " label-placement="left" :show-feedback="false">
|
||||
<div class="compare-result" :class="{ positive: compareMatch }">
|
||||
{{ compareMatch ? 'Yes' : 'No' }}
|
||||
</div>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</c-card>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.compare-result {
|
||||
color: v-bind('themeVars.errorColor');
|
||||
|
||||
&.positive {
|
||||
color: v-bind('themeVars.successColor');
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { LockSquare } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.bcrypt.title'),
|
||||
path: '/bcrypt',
|
||||
description: translate('tools.bcrypt.description'),
|
||||
keywords: ['bcrypt', 'hash', 'compare', 'password', 'salt', 'round', 'storage', 'crypto'],
|
||||
component: () => import('./bcrypt.vue'),
|
||||
icon: LockSquare,
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import _ from 'lodash';
|
||||
|
||||
export { computeAverage, computeVariance, arrayToMarkdownTable };
|
||||
|
||||
function computeAverage({ data }: { data: number[] }) {
|
||||
if (data.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return _.sum(data) / data.length;
|
||||
}
|
||||
|
||||
function computeVariance({ data }: { data: number[] }) {
|
||||
const mean = computeAverage({ data });
|
||||
|
||||
const squaredDiffs = data.map(value => (value - mean) ** 2);
|
||||
|
||||
return computeAverage({ data: squaredDiffs });
|
||||
}
|
||||
|
||||
function arrayToMarkdownTable({ data, headerMap = {} }: { data: Record<string, unknown>[]; headerMap?: Record<string, string> }) {
|
||||
if (!Array.isArray(data) || data.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const headers = Object.keys(data[0]);
|
||||
const rows = data.map(obj => Object.values(obj));
|
||||
|
||||
const headerRow = `| ${headers.map(header => headerMap[header] ?? header).join(' | ')} |`;
|
||||
const separatorRow = `| ${headers.map(() => '---').join(' | ')} |`;
|
||||
const dataRows = rows.map(row => `| ${row.join(' | ')} |`).join('\n');
|
||||
|
||||
return `${headerRow}\n${separatorRow}\n${dataRows}`;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<script setup lang="ts">
|
||||
import { Plus, Trash } from '@vicons/tabler';
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import _ from 'lodash';
|
||||
|
||||
import { arrayToMarkdownTable, computeAverage, computeVariance } from './benchmark-builder.models';
|
||||
import DynamicValues from './dynamic-values.vue';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
|
||||
const suites = useStorage('benchmark-builder:suites', [
|
||||
{ title: 'Suite 1', data: [5, 10] },
|
||||
{ title: 'Suite 2', data: [8, 12] },
|
||||
]);
|
||||
|
||||
const unit = useStorage('benchmark-builder:unit', '');
|
||||
|
||||
const round = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
const results = computed(() => {
|
||||
return suites.value
|
||||
.map(({ data: dirtyData, title }) => {
|
||||
const data = dirtyData.filter(_.isNumber);
|
||||
|
||||
return {
|
||||
title,
|
||||
size: data.length,
|
||||
mean: computeAverage({ data }),
|
||||
variance: computeVariance({ data }),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => a.mean - b.mean)
|
||||
.map(({ mean, variance, size, title }, index, suites) => {
|
||||
const cleanUnit = unit.value.trim();
|
||||
const bestMean: number = suites[0].mean;
|
||||
const deltaWithBestMean = mean - bestMean;
|
||||
const ratioWithBestMean = bestMean === 0 ? '∞' : round(mean / bestMean);
|
||||
|
||||
const comparisonValues: string
|
||||
= (index !== 0 && bestMean !== mean) ? ` (+${round(deltaWithBestMean)}${cleanUnit} ; x${ratioWithBestMean})` : '';
|
||||
|
||||
return {
|
||||
position: index + 1,
|
||||
title,
|
||||
mean: `${round(mean)}${cleanUnit}${comparisonValues}`,
|
||||
variance: `${round(variance)}${cleanUnit}${cleanUnit ? '²' : ''}`,
|
||||
size,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
const { copy } = useCopy({ createToast: false });
|
||||
|
||||
const header = {
|
||||
position: 'Position',
|
||||
title: 'Suite',
|
||||
size: 'Samples',
|
||||
mean: 'Mean',
|
||||
variance: 'Variance',
|
||||
};
|
||||
|
||||
function copyAsMarkdown() {
|
||||
copy(arrayToMarkdownTable({ data: results.value, headerMap: header }));
|
||||
}
|
||||
|
||||
function copyAsBulletList() {
|
||||
const bulletList = results.value
|
||||
.flatMap(({ title, ...sections }) => {
|
||||
return [
|
||||
` - ${title}`,
|
||||
...Object.entries(sections).map(
|
||||
([key, value]) => ` - ${header[key as keyof typeof header] ?? key}: ${value}`,
|
||||
),
|
||||
];
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
copy(bulletList);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<n-scrollbar style="flex: 1" x-scrollable>
|
||||
<div mb-5 flex flex-1 flex-nowrap justify-center gap-12px>
|
||||
<div v-for="(suite, index) of suites" :key="index">
|
||||
<c-card style="width: 294px">
|
||||
<c-input-text
|
||||
v-model:value="suite.title"
|
||||
label-position="left"
|
||||
label="Suite name"
|
||||
placeholder="Suite name..."
|
||||
clearable
|
||||
/>
|
||||
|
||||
<n-divider />
|
||||
<n-form-item label="Suite values" :show-feedback="false">
|
||||
<DynamicValues v-model:values="suite.data" />
|
||||
</n-form-item>
|
||||
</c-card>
|
||||
|
||||
<div flex justify-center>
|
||||
<c-button v-if="suites.length > 1" variant="text" @click="suites.splice(index, 1)">
|
||||
<n-icon :component="Trash" depth="3" mr-2 size="18" />
|
||||
Delete suite
|
||||
</c-button>
|
||||
<c-button
|
||||
variant="text"
|
||||
@click="suites.splice(index + 1, 0, { data: [0], title: `Suite ${suites.length + 1}` })"
|
||||
>
|
||||
<n-icon :component="Plus" depth="3" mr-2 size="18" />
|
||||
Add suite
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</n-scrollbar>
|
||||
|
||||
<div style="flex: 0 0 100%">
|
||||
<div style="max-width: 600px; margin: 0 auto">
|
||||
<div mx-auto max-w-sm flex justify-center gap-3>
|
||||
<c-input-text v-model:value="unit" placeholder="Unit (eg: ms)" label="Unit" label-position="left" mb-4 />
|
||||
|
||||
<c-button
|
||||
@click="
|
||||
suites = [
|
||||
{ title: 'Suite 1', data: [] },
|
||||
{ title: 'Suite 2', data: [] },
|
||||
]
|
||||
"
|
||||
>
|
||||
Reset suites
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<c-table :data="results" :headers="header" />
|
||||
|
||||
<div mt-5 flex justify-center gap-3>
|
||||
<c-button @click="copyAsMarkdown()">
|
||||
Copy as markdown table
|
||||
</c-button>
|
||||
<c-button @click="copyAsBulletList()">
|
||||
Copy as bullet list
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
import { Plus, Trash } from '@vicons/tabler';
|
||||
import { useTemplateRefsList, useVModel } from '@vueuse/core';
|
||||
import { NInputNumber } from 'naive-ui';
|
||||
import { nextTick } from 'vue';
|
||||
|
||||
const props = defineProps<{ values: (number | null)[] }>();
|
||||
|
||||
const emit = defineEmits(['update:values']);
|
||||
|
||||
const refs = useTemplateRefsList<typeof NInputNumber>();
|
||||
|
||||
const values = useVModel(props, 'values', emit);
|
||||
|
||||
async function addValue() {
|
||||
values.value.push(null);
|
||||
await nextTick();
|
||||
refs.value.at(-1)?.focus();
|
||||
}
|
||||
|
||||
function onInputEnter(index: number) {
|
||||
if (index === values.value.length - 1) {
|
||||
addValue();
|
||||
return;
|
||||
}
|
||||
|
||||
refs.value.at(index + 1)?.focus();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div v-for="(value, index) of values" :key="index" mb-2 flex flex-nowrap gap-2>
|
||||
<NInputNumber
|
||||
:ref="refs.set"
|
||||
v-model:value="values[index]"
|
||||
:show-button="false"
|
||||
placeholder="Set your measure..."
|
||||
autofocus
|
||||
@keydown.enter="onInputEnter(index)"
|
||||
/>
|
||||
<c-tooltip tooltip="Delete this value">
|
||||
<c-button circle variant="text" @click="values.splice(index, 1)">
|
||||
<n-icon :component="Trash" depth="3" size="18" />
|
||||
</c-button>
|
||||
</c-tooltip>
|
||||
</div>
|
||||
|
||||
<c-button @click="addValue">
|
||||
<n-icon :component="Plus" depth="3" mr-2 size="18" />
|
||||
Add a measure
|
||||
</c-button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,13 @@
|
||||
import { SpeedFilled } from '@vicons/material';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.benchmark-builder.title'),
|
||||
path: '/benchmark-builder',
|
||||
description: translate('tools.benchmark-builder.description'),
|
||||
keywords: ['benchmark', 'builder', 'execution', 'duration', 'mean', 'variance'],
|
||||
component: () => import('./benchmark-builder.vue'),
|
||||
icon: SpeedFilled,
|
||||
createdAt: new Date('2023-04-05'),
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
chineseSimplifiedWordList,
|
||||
chineseTraditionalWordList,
|
||||
czechWordList,
|
||||
englishWordList,
|
||||
entropyToMnemonic,
|
||||
frenchWordList,
|
||||
generateEntropy,
|
||||
italianWordList,
|
||||
japaneseWordList,
|
||||
koreanWordList,
|
||||
mnemonicToEntropy,
|
||||
portugueseWordList,
|
||||
spanishWordList,
|
||||
} from '@it-tools/bip39';
|
||||
import { Copy, Refresh } from '@vicons/tabler';
|
||||
|
||||
import { useCopy } from '@/composable/copy';
|
||||
import { useValidation } from '@/composable/validation';
|
||||
import { isNotThrowing } from '@/utils/boolean';
|
||||
import { withDefaultOnError } from '@/utils/defaults';
|
||||
|
||||
const languages = {
|
||||
'English': englishWordList,
|
||||
'Chinese simplified': chineseSimplifiedWordList,
|
||||
'Chinese traditional': chineseTraditionalWordList,
|
||||
'Czech': czechWordList,
|
||||
'French': frenchWordList,
|
||||
'Italian': italianWordList,
|
||||
'Japanese': japaneseWordList,
|
||||
'Korean': koreanWordList,
|
||||
'Portuguese': portugueseWordList,
|
||||
'Spanish': spanishWordList,
|
||||
};
|
||||
|
||||
const entropy = ref(generateEntropy());
|
||||
const passphraseInput = ref('');
|
||||
|
||||
const language = ref<keyof typeof languages>('English');
|
||||
const passphrase = computed({
|
||||
get() {
|
||||
return withDefaultOnError(() => entropyToMnemonic(entropy.value, languages[language.value]), passphraseInput.value);
|
||||
},
|
||||
set(value: string) {
|
||||
passphraseInput.value = value;
|
||||
entropy.value = withDefaultOnError(() => mnemonicToEntropy(value, languages[language.value]), '');
|
||||
},
|
||||
});
|
||||
|
||||
const entropyValidation = useValidation({
|
||||
source: entropy,
|
||||
rules: [
|
||||
{
|
||||
validator: value => value === '' || (value.length <= 32 && value.length >= 16 && value.length % 4 === 0),
|
||||
message: 'Entropy length should be >= 16, <= 32 and be a multiple of 4',
|
||||
},
|
||||
{
|
||||
validator: value => /^[a-fA-F0-9]*$/.test(value),
|
||||
message: 'Entropy should be an hexadecimal string',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const mnemonicValidation = useValidation({
|
||||
source: passphrase,
|
||||
rules: [
|
||||
{
|
||||
validator: value => isNotThrowing(() => mnemonicToEntropy(value, languages[language.value])),
|
||||
message: 'Invalid mnemonic',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function refreshEntropy() {
|
||||
entropy.value = generateEntropy();
|
||||
}
|
||||
|
||||
const { copy: copyEntropy } = useCopy({ source: entropy, text: 'Entropy copied to the clipboard' });
|
||||
const { copy: copyPassphrase } = useCopy({ source: passphrase, text: 'Passphrase copied to the clipboard' });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<n-grid cols="3" x-gap="12">
|
||||
<n-gi span="1">
|
||||
<c-select
|
||||
v-model:value="language"
|
||||
searchable
|
||||
label="Language:"
|
||||
:options="Object.keys(languages)"
|
||||
/>
|
||||
</n-gi>
|
||||
<n-gi span="2">
|
||||
<n-form-item
|
||||
label="Entropy (seed):"
|
||||
:feedback="entropyValidation.message"
|
||||
:validation-status="entropyValidation.status"
|
||||
>
|
||||
<n-input-group>
|
||||
<c-input-text v-model:value="entropy" placeholder="Your string..." />
|
||||
|
||||
<c-button @click="refreshEntropy()">
|
||||
<n-icon size="22">
|
||||
<Refresh />
|
||||
</n-icon>
|
||||
</c-button>
|
||||
<c-button @click="copyEntropy()">
|
||||
<n-icon size="22">
|
||||
<Copy />
|
||||
</n-icon>
|
||||
</c-button>
|
||||
</n-input-group>
|
||||
</n-form-item>
|
||||
</n-gi>
|
||||
</n-grid>
|
||||
<n-form-item
|
||||
label="Passphrase (mnemonic):"
|
||||
:feedback="mnemonicValidation.message"
|
||||
:validation-status="mnemonicValidation.status"
|
||||
>
|
||||
<n-input-group>
|
||||
<c-input-text v-model:value="passphrase" placeholder="Your mnemonic..." raw-text />
|
||||
|
||||
<c-button @click="copyPassphrase()">
|
||||
<n-icon size="22" :component="Copy" />
|
||||
</c-button>
|
||||
</n-input-group>
|
||||
</n-form-item>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { AlignJustified } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.bip39-generator.title'),
|
||||
path: '/bip39-generator',
|
||||
description: translate('tools.bip39-generator.description'),
|
||||
keywords: ['BIP39', 'passphrase', 'generator', 'mnemonic', 'entropy'],
|
||||
component: () => import('./bip39-generator.vue'),
|
||||
icon: AlignJustified,
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
<script setup lang="ts">
|
||||
import _ from 'lodash';
|
||||
|
||||
import { useMediaRecorder } from './useMediaRecorder';
|
||||
|
||||
interface Media { type: 'image' | 'video'; value: string; createdAt: Date }
|
||||
|
||||
const {
|
||||
videoInputs: cameras,
|
||||
audioInputs: microphones,
|
||||
permissionGranted,
|
||||
isSupported,
|
||||
ensurePermissions,
|
||||
} = useDevicesList({
|
||||
requestPermissions: true,
|
||||
constraints: { video: true, audio: true },
|
||||
onUpdated() {
|
||||
refreshCurrentDevices();
|
||||
},
|
||||
});
|
||||
|
||||
const video = ref<HTMLVideoElement>();
|
||||
const medias = ref<Media[]>([]);
|
||||
const currentCamera = ref(cameras.value[0]?.deviceId);
|
||||
const currentMicrophone = ref(microphones.value[0]?.deviceId);
|
||||
const permissionCannotBePrompted = ref(false);
|
||||
|
||||
const {
|
||||
stream,
|
||||
start,
|
||||
stop,
|
||||
enabled: isMediaStreamAvailable,
|
||||
} = useUserMedia({
|
||||
constraints: computed(() => ({
|
||||
video: { deviceId: currentCamera.value },
|
||||
...(currentMicrophone.value ? { audio: { deviceId: currentMicrophone.value } } : {}),
|
||||
})),
|
||||
autoSwitch: true,
|
||||
});
|
||||
|
||||
const {
|
||||
isRecordingSupported,
|
||||
onRecordAvailable,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
pauseRecording,
|
||||
recordingState,
|
||||
resumeRecording,
|
||||
} = useMediaRecorder({
|
||||
stream,
|
||||
});
|
||||
|
||||
onRecordAvailable((value) => {
|
||||
medias.value.unshift({ type: 'video', value, createdAt: new Date() });
|
||||
});
|
||||
|
||||
function refreshCurrentDevices() {
|
||||
if (_.isNil(currentCamera) || !cameras.value.find(i => i.deviceId === currentCamera.value)) {
|
||||
currentCamera.value = cameras.value[0]?.deviceId;
|
||||
}
|
||||
|
||||
if (_.isNil(microphones) || !microphones.value.find(i => i.deviceId === currentMicrophone.value)) {
|
||||
currentMicrophone.value = microphones.value[0]?.deviceId;
|
||||
}
|
||||
}
|
||||
|
||||
function takeScreenshot() {
|
||||
if (!video.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = video.value.videoWidth;
|
||||
canvas.height = video.value.videoHeight;
|
||||
canvas.getContext('2d')?.drawImage(video.value, 0, 0);
|
||||
const image = canvas.toDataURL('image/png');
|
||||
|
||||
medias.value.unshift({ type: 'image', value: image, createdAt: new Date() });
|
||||
}
|
||||
|
||||
watchEffect(() => {
|
||||
if (video.value && stream.value) {
|
||||
video.value.srcObject = stream.value;
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => stop());
|
||||
|
||||
async function requestPermissions() {
|
||||
try {
|
||||
await ensurePermissions();
|
||||
}
|
||||
catch (e) {
|
||||
permissionCannotBePrompted.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadMedia({ type, value, createdAt }: Media) {
|
||||
const link = document.createElement('a');
|
||||
link.href = value;
|
||||
link.download = `${type}-${createdAt.getTime()}.${type === 'image' ? 'png' : 'webm'}`;
|
||||
link.click();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-card v-if="!isSupported">
|
||||
Your browser does not support recording video from camera
|
||||
</c-card>
|
||||
|
||||
<c-card v-else-if="!permissionGranted" text-center>
|
||||
You need to grant permission to use your camera and microphone
|
||||
|
||||
<c-alert v-if="permissionCannotBePrompted" mt-4 text-left>
|
||||
Your browser has blocked permission request or does not support it. You need to grant permission manually in
|
||||
your browser settings (usually the lock icon in the address bar).
|
||||
</c-alert>
|
||||
|
||||
<div v-else mt-4 flex justify-center>
|
||||
<c-button @click="requestPermissions">
|
||||
Grant permission
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
|
||||
<c-card v-else>
|
||||
<div flex flex-col gap-2>
|
||||
<c-select
|
||||
v-model:value="currentCamera"
|
||||
label-position="left"
|
||||
label-width="60px"
|
||||
label="Video:"
|
||||
:options="cameras.map(({ deviceId, label }) => ({ value: deviceId, label }))"
|
||||
placeholder="Select camera"
|
||||
/>
|
||||
<c-select
|
||||
v-if="currentMicrophone && microphones.length > 0"
|
||||
v-model:value="currentMicrophone"
|
||||
label="Audio:"
|
||||
label-position="left"
|
||||
label-width="60px"
|
||||
:options="microphones.map(({ deviceId, label }) => ({ value: deviceId, label }))"
|
||||
placeholder="Select microphone"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="!isMediaStreamAvailable" mt-3 flex justify-center>
|
||||
<c-button type="primary" @click="start">
|
||||
Start webcam
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div my-2>
|
||||
<video ref="video" autoplay controls playsinline max-h-full w-full />
|
||||
</div>
|
||||
|
||||
<div flex items-center justify-between gap-2>
|
||||
<c-button :disabled="!isMediaStreamAvailable" @click="takeScreenshot">
|
||||
<span mr-2> <icon-mdi-camera /></span>
|
||||
Take screenshot
|
||||
</c-button>
|
||||
|
||||
<div v-if="isRecordingSupported" flex justify-center gap-2>
|
||||
<c-button v-if="recordingState === 'stopped'" @click="startRecording">
|
||||
<span mr-2> <icon-mdi-video /></span>
|
||||
Start recording
|
||||
</c-button>
|
||||
|
||||
<c-button v-if="recordingState === 'recording'" @click="pauseRecording">
|
||||
<span mr-2> <icon-mdi-pause /></span>
|
||||
Pause
|
||||
</c-button>
|
||||
|
||||
<c-button v-if="recordingState === 'paused'" @click="resumeRecording">
|
||||
<span mr-2> <icon-mdi-play /></span>
|
||||
Resume
|
||||
</c-button>
|
||||
|
||||
<c-button v-if="recordingState !== 'stopped'" type="error" @click="stopRecording">
|
||||
<span mr-2> <icon-mdi-record /></span>
|
||||
Stop
|
||||
</c-button>
|
||||
</div>
|
||||
<div v-else italic op-60>
|
||||
Video recording is not supported in your browser
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</c-card>
|
||||
|
||||
<div grid grid-cols-2 mt-5 gap-2>
|
||||
<c-card v-for="({ type, value, createdAt }, index) in medias" :key="index">
|
||||
<img v-if="type === 'image'" :src="value" max-h-full w-full alt="screenshot">
|
||||
|
||||
<video v-else :src="value" controls max-h-full w-full />
|
||||
|
||||
<div flex items-center justify-between>
|
||||
<div font-bold>
|
||||
{{ type === 'image' ? 'Screenshot' : 'Video' }}
|
||||
</div>
|
||||
|
||||
<div flex gap-2>
|
||||
<c-button @click="downloadMedia({ type, value, createdAt })">
|
||||
<icon-mdi-download />
|
||||
</c-button>
|
||||
|
||||
<c-button @click="medias = medias.filter((_ignored, i) => i !== index)">
|
||||
<icon-mdi-delete-outline />
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Camera } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.camera-recorder.title'),
|
||||
path: '/camera-recorder',
|
||||
description: translate('tools.camera-recorder.description'),
|
||||
keywords: ['camera', 'recoder'],
|
||||
component: () => import('./camera-recorder.vue'),
|
||||
icon: Camera,
|
||||
createdAt: new Date('2023-05-15'),
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { type Ref, computed, ref } from 'vue';
|
||||
|
||||
export { useMediaRecorder };
|
||||
|
||||
function useMediaRecorder({ stream }: { stream: Ref<MediaStream | undefined> }): {
|
||||
isRecordingSupported: Ref<boolean>
|
||||
recordingState: Ref<'stopped' | 'recording' | 'paused'>
|
||||
startRecording: () => void
|
||||
stopRecording: () => void
|
||||
pauseRecording: () => void
|
||||
resumeRecording: () => void
|
||||
onRecordAvailable: (cb: (url: string) => void) => void
|
||||
} {
|
||||
const isRecordingSupported = computed(() => MediaRecorder.isTypeSupported('video/webm'));
|
||||
const mediaRecorder = ref<MediaRecorder | null>(null);
|
||||
const recordedChunks = ref<Blob[]>([]);
|
||||
const recordAvailable = createEventHook();
|
||||
const recordingState = ref<'stopped' | 'recording' | 'paused'>('stopped');
|
||||
|
||||
const createVideo = () => {
|
||||
const blob = new Blob(recordedChunks.value, { type: 'video/webm' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
recordedChunks.value = [];
|
||||
return url;
|
||||
};
|
||||
|
||||
const startRecording = () => {
|
||||
if (!isRecordingSupported.value) {
|
||||
return;
|
||||
}
|
||||
if (!stream.value) {
|
||||
return;
|
||||
}
|
||||
if (recordingState.value !== 'stopped') {
|
||||
return;
|
||||
}
|
||||
|
||||
mediaRecorder.value = new MediaRecorder(stream.value, { mimeType: 'video/webm' });
|
||||
|
||||
mediaRecorder.value.ondataavailable = (e) => {
|
||||
if (e.data.size > 0) {
|
||||
recordedChunks.value.push(e.data);
|
||||
}
|
||||
};
|
||||
|
||||
mediaRecorder.value.onstop = () => {
|
||||
recordAvailable.trigger(createVideo());
|
||||
};
|
||||
|
||||
if (mediaRecorder.value.state !== 'inactive') {
|
||||
return;
|
||||
}
|
||||
|
||||
mediaRecorder.value.start();
|
||||
recordingState.value = 'recording';
|
||||
};
|
||||
|
||||
const stopRecording = () => {
|
||||
if (!isRecordingSupported.value) {
|
||||
return;
|
||||
}
|
||||
if (!mediaRecorder.value) {
|
||||
return;
|
||||
}
|
||||
if (recordingState.value === 'stopped') {
|
||||
return;
|
||||
}
|
||||
|
||||
mediaRecorder.value.stop();
|
||||
recordingState.value = 'stopped';
|
||||
};
|
||||
|
||||
const pauseRecording = () => {
|
||||
if (!isRecordingSupported.value) {
|
||||
return;
|
||||
}
|
||||
if (!mediaRecorder.value) {
|
||||
return;
|
||||
}
|
||||
if (recordingState.value !== 'recording') {
|
||||
return;
|
||||
}
|
||||
|
||||
mediaRecorder.value.pause();
|
||||
recordingState.value = 'paused';
|
||||
};
|
||||
|
||||
const resumeRecording = () => {
|
||||
if (!isRecordingSupported.value) {
|
||||
return;
|
||||
}
|
||||
if (!mediaRecorder.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (recordingState.value !== 'paused') {
|
||||
return;
|
||||
}
|
||||
|
||||
mediaRecorder.value.resume();
|
||||
recordingState.value = 'recording';
|
||||
};
|
||||
|
||||
return {
|
||||
isRecordingSupported,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
pauseRecording,
|
||||
resumeRecording,
|
||||
recordingState,
|
||||
|
||||
onRecordAvailable: recordAvailable.on,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
camelCase,
|
||||
capitalCase,
|
||||
constantCase,
|
||||
dotCase,
|
||||
headerCase,
|
||||
noCase,
|
||||
paramCase,
|
||||
pascalCase,
|
||||
pathCase,
|
||||
sentenceCase,
|
||||
snakeCase,
|
||||
} from 'change-case';
|
||||
import InputCopyable from '../../components/InputCopyable.vue';
|
||||
|
||||
const baseConfig = {
|
||||
stripRegexp: /[^A-Za-zÀ-ÖØ-öø-ÿ]+/gi,
|
||||
};
|
||||
|
||||
const input = ref('lorem ipsum dolor sit amet');
|
||||
|
||||
const formats = computed(() => [
|
||||
{
|
||||
label: 'Lowercase:',
|
||||
value: input.value.toLocaleLowerCase(),
|
||||
},
|
||||
{
|
||||
label: 'Uppercase:',
|
||||
value: input.value.toLocaleUpperCase(),
|
||||
},
|
||||
{
|
||||
label: 'Camelcase:',
|
||||
value: camelCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Capitalcase:',
|
||||
value: capitalCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Constantcase:',
|
||||
value: constantCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Dotcase:',
|
||||
value: dotCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Headercase:',
|
||||
value: headerCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Nocase:',
|
||||
value: noCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Paramcase:',
|
||||
value: paramCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Pascalcase:',
|
||||
value: pascalCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Pathcase:',
|
||||
value: pathCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Sentencecase:',
|
||||
value: sentenceCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Snakecase:',
|
||||
value: snakeCase(input.value, baseConfig),
|
||||
},
|
||||
{
|
||||
label: 'Mockingcase:',
|
||||
value: input.value
|
||||
.split('')
|
||||
.map((char, index) => (index % 2 === 0 ? char.toUpperCase() : char.toLowerCase()))
|
||||
.join(''),
|
||||
},
|
||||
]);
|
||||
|
||||
const inputLabelAlignmentConfig = {
|
||||
labelPosition: 'left',
|
||||
labelWidth: '120px',
|
||||
labelAlign: 'right',
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card>
|
||||
<c-input-text
|
||||
v-model:value="input"
|
||||
label="Your string:"
|
||||
placeholder="Your string..."
|
||||
raw-text
|
||||
v-bind="inputLabelAlignmentConfig"
|
||||
/>
|
||||
|
||||
<div my-16px divider />
|
||||
|
||||
<InputCopyable
|
||||
v-for="format in formats"
|
||||
:key="format.label"
|
||||
:value="format.value"
|
||||
:label="format.label"
|
||||
v-bind="inputLabelAlignmentConfig"
|
||||
mb-1
|
||||
/>
|
||||
</c-card>
|
||||
</template>
|
||||
@@ -0,0 +1,26 @@
|
||||
import { LetterCaseToggle } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.case-converter.title'),
|
||||
path: '/case-converter',
|
||||
description: translate('tools.case-converter.description'),
|
||||
keywords: [
|
||||
'case',
|
||||
'converter',
|
||||
'camelCase',
|
||||
'capitalCase',
|
||||
'constantCase',
|
||||
'dotCase',
|
||||
'headerCase',
|
||||
'noCase',
|
||||
'paramCase',
|
||||
'pascalCase',
|
||||
'pathCase',
|
||||
'sentenceCase',
|
||||
'snakeCase',
|
||||
],
|
||||
component: () => import('./case-converter.vue'),
|
||||
icon: LetterCaseToggle,
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { computeChmodOctalRepresentation, computeChmodSymbolicRepresentation } from './chmod-calculator.service';
|
||||
|
||||
describe('chmod-calculator', () => {
|
||||
describe('computeChmodOctalRepresentation', () => {
|
||||
it('get the octal representation from permissions', () => {
|
||||
expect(
|
||||
computeChmodOctalRepresentation({
|
||||
permissions: {
|
||||
owner: { read: true, write: true, execute: true },
|
||||
group: { read: true, write: true, execute: true },
|
||||
public: { read: true, write: true, execute: true },
|
||||
},
|
||||
}),
|
||||
).to.eql('777');
|
||||
|
||||
expect(
|
||||
computeChmodOctalRepresentation({
|
||||
permissions: {
|
||||
owner: { read: false, write: false, execute: false },
|
||||
group: { read: false, write: false, execute: false },
|
||||
public: { read: false, write: false, execute: false },
|
||||
},
|
||||
}),
|
||||
).to.eql('000');
|
||||
|
||||
expect(
|
||||
computeChmodOctalRepresentation({
|
||||
permissions: {
|
||||
owner: { read: false, write: true, execute: false },
|
||||
group: { read: false, write: true, execute: true },
|
||||
public: { read: true, write: false, execute: true },
|
||||
},
|
||||
}),
|
||||
).to.eql('235');
|
||||
|
||||
expect(
|
||||
computeChmodOctalRepresentation({
|
||||
permissions: {
|
||||
owner: { read: true, write: false, execute: false },
|
||||
group: { read: false, write: true, execute: false },
|
||||
public: { read: false, write: false, execute: true },
|
||||
},
|
||||
}),
|
||||
).to.eql('421');
|
||||
|
||||
expect(
|
||||
computeChmodOctalRepresentation({
|
||||
permissions: {
|
||||
owner: { read: false, write: false, execute: true },
|
||||
group: { read: false, write: true, execute: false },
|
||||
public: { read: true, write: false, execute: false },
|
||||
},
|
||||
}),
|
||||
).to.eql('124');
|
||||
|
||||
expect(
|
||||
computeChmodOctalRepresentation({
|
||||
permissions: {
|
||||
owner: { read: false, write: true, execute: false },
|
||||
group: { read: false, write: true, execute: false },
|
||||
public: { read: false, write: true, execute: false },
|
||||
},
|
||||
}),
|
||||
).to.eql('222');
|
||||
});
|
||||
|
||||
it('get the symbolic representation from permissions', () => {
|
||||
expect(
|
||||
computeChmodSymbolicRepresentation({
|
||||
permissions: {
|
||||
owner: { read: true, write: true, execute: true },
|
||||
group: { read: true, write: true, execute: true },
|
||||
public: { read: true, write: true, execute: true },
|
||||
},
|
||||
}),
|
||||
).to.eql('rwxrwxrwx');
|
||||
|
||||
expect(
|
||||
computeChmodSymbolicRepresentation({
|
||||
permissions: {
|
||||
owner: { read: false, write: false, execute: false },
|
||||
group: { read: false, write: false, execute: false },
|
||||
public: { read: false, write: false, execute: false },
|
||||
},
|
||||
}),
|
||||
).to.eql('---------');
|
||||
|
||||
expect(
|
||||
computeChmodSymbolicRepresentation({
|
||||
permissions: {
|
||||
owner: { read: false, write: true, execute: false },
|
||||
group: { read: false, write: true, execute: true },
|
||||
public: { read: true, write: false, execute: true },
|
||||
},
|
||||
}),
|
||||
).to.eql('-w--wxr-x');
|
||||
|
||||
expect(
|
||||
computeChmodSymbolicRepresentation({
|
||||
permissions: {
|
||||
owner: { read: true, write: false, execute: false },
|
||||
group: { read: false, write: true, execute: false },
|
||||
public: { read: false, write: false, execute: true },
|
||||
},
|
||||
}),
|
||||
).to.eql('r---w---x');
|
||||
|
||||
expect(
|
||||
computeChmodSymbolicRepresentation({
|
||||
permissions: {
|
||||
owner: { read: false, write: false, execute: true },
|
||||
group: { read: false, write: true, execute: false },
|
||||
public: { read: true, write: false, execute: false },
|
||||
},
|
||||
}),
|
||||
).to.eql('--x-w-r--');
|
||||
|
||||
expect(
|
||||
computeChmodSymbolicRepresentation({
|
||||
permissions: {
|
||||
owner: { read: false, write: true, execute: false },
|
||||
group: { read: false, write: true, execute: false },
|
||||
public: { read: false, write: true, execute: false },
|
||||
},
|
||||
}),
|
||||
).to.eql('-w--w--w-');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import _ from 'lodash';
|
||||
import type { GroupPermissions, Permissions } from './chmod-calculator.types';
|
||||
|
||||
export { computeChmodOctalRepresentation, computeChmodSymbolicRepresentation };
|
||||
|
||||
function computeChmodOctalRepresentation({ permissions }: { permissions: Permissions }): string {
|
||||
const permissionValue = { read: 4, write: 2, execute: 1 };
|
||||
|
||||
const getGroupPermissionValue = (permission: GroupPermissions) =>
|
||||
_.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(permissionValue, key, 0) : 0), 0);
|
||||
|
||||
return [
|
||||
getGroupPermissionValue(permissions.owner),
|
||||
getGroupPermissionValue(permissions.group),
|
||||
getGroupPermissionValue(permissions.public),
|
||||
].join('');
|
||||
}
|
||||
|
||||
function computeChmodSymbolicRepresentation({ permissions }: { permissions: Permissions }): string {
|
||||
const permissionValue = { read: 'r', write: 'w', execute: 'x' };
|
||||
|
||||
const getGroupPermissionValue = (permission: GroupPermissions) =>
|
||||
_.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(permissionValue, key, '') : '-'), '');
|
||||
|
||||
return [
|
||||
getGroupPermissionValue(permissions.owner),
|
||||
getGroupPermissionValue(permissions.group),
|
||||
getGroupPermissionValue(permissions.public),
|
||||
].join('');
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export type Scope = 'read' | 'write' | 'execute';
|
||||
export type Group = 'owner' | 'group' | 'public';
|
||||
|
||||
export type GroupPermissions = {
|
||||
[k in Scope]: boolean;
|
||||
};
|
||||
|
||||
export type Permissions = {
|
||||
[k in Group]: GroupPermissions;
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
<script setup lang="ts">
|
||||
import { useThemeVars } from 'naive-ui';
|
||||
|
||||
import InputCopyable from '../../components/InputCopyable.vue';
|
||||
import { computeChmodOctalRepresentation, computeChmodSymbolicRepresentation } from './chmod-calculator.service';
|
||||
|
||||
import type { Group, Scope } from './chmod-calculator.types';
|
||||
|
||||
const themeVars = useThemeVars();
|
||||
|
||||
const scopes: { scope: Scope; title: string }[] = [
|
||||
{ scope: 'read', title: 'Read (4)' },
|
||||
{ scope: 'write', title: 'Write (2)' },
|
||||
{ scope: 'execute', title: 'Execute (1)' },
|
||||
];
|
||||
const groups: Group[] = ['owner', 'group', 'public'];
|
||||
|
||||
const permissions = ref({
|
||||
owner: { read: false, write: false, execute: false },
|
||||
group: { read: false, write: false, execute: false },
|
||||
public: { read: false, write: false, execute: false },
|
||||
});
|
||||
|
||||
const octal = computed(() => computeChmodOctalRepresentation({ permissions: permissions.value }));
|
||||
const symbolic = computed(() => computeChmodSymbolicRepresentation({ permissions: permissions.value }));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<n-table :bordered="false" :bottom-bordered="false" single-column class="permission-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="text-center" scope="col" />
|
||||
<th class="text-center" scope="col">
|
||||
Owner (u)
|
||||
</th>
|
||||
<th class="text-center" scope="col">
|
||||
Group (g)
|
||||
</th>
|
||||
<th class="text-center" scope="col">
|
||||
Public (o)
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="{ scope, title } of scopes" :key="scope">
|
||||
<td class="line-header">
|
||||
{{ title }}
|
||||
</td>
|
||||
<td v-for="group of groups" :key="group" class="text-center">
|
||||
<!-- <n-switch v-model:value="permissions[group][scope]" /> -->
|
||||
<n-checkbox v-model:checked="permissions[group][scope]" size="large" />
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</n-table>
|
||||
|
||||
<div class="octal-result">
|
||||
{{ octal }}
|
||||
</div>
|
||||
<div class="octal-result">
|
||||
{{ symbolic }}
|
||||
</div>
|
||||
|
||||
<InputCopyable :value="`chmod ${octal} path`" readonly />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.octal-result {
|
||||
text-align: center;
|
||||
font-size: 50px;
|
||||
font-family: monospace;
|
||||
color: v-bind('themeVars.primaryColor');
|
||||
margin: 20px 0;
|
||||
}
|
||||
.permission-table {
|
||||
td,
|
||||
th {
|
||||
padding: 15px;
|
||||
|
||||
@media screen and (max-width: 600px) {
|
||||
padding: 5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
.line-header {
|
||||
font-weight: bold;
|
||||
text-align: right;
|
||||
max-width: 80px;
|
||||
}
|
||||
.text-center {
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,23 @@
|
||||
import { FileInvoice } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.chmod-calculator.title'),
|
||||
path: '/chmod-calculator',
|
||||
description: translate('tools.chmod-calculator.description'),
|
||||
keywords: [
|
||||
'chmod',
|
||||
'calculator',
|
||||
'file',
|
||||
'permission',
|
||||
'files',
|
||||
'directory',
|
||||
'folder',
|
||||
'recursive',
|
||||
'generator',
|
||||
'octal',
|
||||
],
|
||||
component: () => import('./chmod-calculator.vue'),
|
||||
icon: FileInvoice,
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatMs } from './chronometer.service';
|
||||
|
||||
describe('chronometer', () => {
|
||||
describe('formatChronometerTime', () => {
|
||||
it('format the elapsed time', () => {
|
||||
expect(formatMs(0)).toEqual('00:00.000');
|
||||
expect(formatMs(1)).toEqual('00:00.001');
|
||||
expect(formatMs(123456)).toEqual('02:03.456');
|
||||
expect(formatMs(12345600)).toEqual('03:25:45.600');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
export function formatMs(msTotal: number) {
|
||||
const ms = msTotal % 1000;
|
||||
const secs = ((msTotal - ms) / 1000) % 60;
|
||||
const mins = (((msTotal - ms) / 1000 - secs) / 60) % 60;
|
||||
const hrs = (((msTotal - ms) / 1000 - secs) / 60 - mins) / 60;
|
||||
const hrsString = hrs > 0 ? `${hrs.toString().padStart(2, '0')}:` : '';
|
||||
|
||||
return `${hrsString}${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${ms
|
||||
.toString()
|
||||
.padStart(3, '0')}`;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<script setup lang="ts">
|
||||
import { useRafFn } from '@vueuse/core';
|
||||
|
||||
import { formatMs } from './chronometer.service';
|
||||
|
||||
const isRunning = ref(false);
|
||||
const counter = ref(0);
|
||||
|
||||
let previousRafDate = Date.now();
|
||||
const { pause: pauseRaf, resume: resumeRaf } = useRafFn(
|
||||
() => {
|
||||
const deltaMs = Date.now() - previousRafDate;
|
||||
previousRafDate = Date.now();
|
||||
counter.value += deltaMs;
|
||||
},
|
||||
{ immediate: false },
|
||||
);
|
||||
|
||||
function resume() {
|
||||
previousRafDate = Date.now();
|
||||
resumeRaf();
|
||||
isRunning.value = true;
|
||||
}
|
||||
|
||||
function pause() {
|
||||
pauseRaf();
|
||||
isRunning.value = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-card>
|
||||
<div class="duration">
|
||||
{{ formatMs(counter) }}
|
||||
</div>
|
||||
</c-card>
|
||||
<div mt-5 flex justify-center gap-3>
|
||||
<c-button v-if="!isRunning" type="primary" @click="resume">
|
||||
Start
|
||||
</c-button>
|
||||
<c-button v-else type="warning" @click="pause">
|
||||
Stop
|
||||
</c-button>
|
||||
|
||||
<c-button @click="counter = 0">
|
||||
Reset
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.duration {
|
||||
text-align: center;
|
||||
font-size: 40px;
|
||||
font-family: monospace;
|
||||
margin: 20px 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { TimerOutlined } from '@vicons/material';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.chronometer.title'),
|
||||
path: '/chronometer',
|
||||
description: translate('tools.chronometer.description'),
|
||||
keywords: ['chronometer', 'time', 'lap', 'duration', 'measure', 'pause', 'resume', 'stopwatch'],
|
||||
component: () => import('./chronometer.vue'),
|
||||
icon: TimerOutlined,
|
||||
});
|
||||
@@ -0,0 +1,472 @@
|
||||
<script setup lang="ts">
|
||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
||||
|
||||
const genHist = useGenHistory('code-reader');
|
||||
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
|
||||
import wasmUrl from 'zxing-wasm/reader/zxing_reader.wasm?url';
|
||||
|
||||
// load wasm from our own bundle instead of jsdelivr CDN (works offline / in CN)
|
||||
prepareZXingModule({
|
||||
overrides: {
|
||||
locateFile: () => wasmUrl,
|
||||
},
|
||||
fireImmediately: true,
|
||||
});
|
||||
|
||||
interface CodeResult {
|
||||
format: string;
|
||||
symbology: string;
|
||||
contentType: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const imageSrc = ref('');
|
||||
const fileName = ref('');
|
||||
const results = ref<CodeResult[]>([]);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const dragActive = ref(false);
|
||||
const elapsed = ref(0);
|
||||
|
||||
function pickFile() {
|
||||
fileInput.value?.click();
|
||||
}
|
||||
|
||||
async function handleFile(file?: File | null) {
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
if (!file.type.startsWith('image/')) {
|
||||
error.value = '请选择图片文件(png/jpg/webp/bmp 等)';
|
||||
return;
|
||||
}
|
||||
error.value = '';
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
imageSrc.value = String(reader.result ?? '');
|
||||
fileName.value = file.name;
|
||||
recognize(file);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function onInputChange(e: Event) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
handleFile(input.files?.[0]);
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
function onDrop(e: DragEvent) {
|
||||
dragActive.value = false;
|
||||
handleFile(e.dataTransfer?.files?.[0]);
|
||||
}
|
||||
|
||||
// paste image from clipboard
|
||||
function onPaste(e: ClipboardEvent) {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) {
|
||||
return;
|
||||
}
|
||||
for (const item of items) {
|
||||
if (item.type.startsWith('image/')) {
|
||||
handleFile(item.getAsFile());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// flatten onto a white canvas first: ZXing handles transparent PNGs poorly
|
||||
async function toFlattenedBlob(file: File | Blob): Promise<Blob> {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = bitmap.width;
|
||||
canvas.height = bitmap.height;
|
||||
const ctx = canvas.getContext('2d')!;
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.drawImage(bitmap, 0, 0);
|
||||
bitmap.close();
|
||||
return new Promise(resolve => canvas.toBlob(b => resolve(b!), 'image/png'));
|
||||
}
|
||||
|
||||
async function recognize(file: File | Blob) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
results.value = [];
|
||||
const start = performance.now();
|
||||
try {
|
||||
const flattened = await toFlattenedBlob(file);
|
||||
const found = await readBarcodes(flattened, {
|
||||
tryHarder: true,
|
||||
tryRotate: true,
|
||||
tryInvert: true,
|
||||
maxNumberOfSymbols: 0, // no limit
|
||||
});
|
||||
results.value = found.map(r => ({
|
||||
format: r.format,
|
||||
symbology: r.symbology,
|
||||
contentType: r.contentType,
|
||||
text: r.text,
|
||||
}));
|
||||
if (!found.length) {
|
||||
error.value = '未识别到条码/二维码,可尝试更清晰、完整(含留白)的图片';
|
||||
}
|
||||
else {
|
||||
genHist.add({
|
||||
title: found[0].text.slice(0, 60),
|
||||
detail: `${found[0].format}${found.length > 1 ? ` 等 ${found.length} 个` : ''}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (e: any) {
|
||||
error.value = `识别失败:${e?.message ?? e}`;
|
||||
}
|
||||
finally {
|
||||
elapsed.value = Math.round(performance.now() - start);
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function reRecognize() {
|
||||
if (!imageSrc.value) {
|
||||
return;
|
||||
}
|
||||
fetch(imageSrc.value)
|
||||
.then(r => r.blob())
|
||||
.then(blob => recognize(blob));
|
||||
}
|
||||
|
||||
const allText = computed(() => results.value.map(r => r.text).join('\n'));
|
||||
|
||||
async function copyText(text: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
}
|
||||
catch {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
document.execCommand('copy');
|
||||
ta.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function downloadTxt() {
|
||||
if (!allText.value) {
|
||||
return;
|
||||
}
|
||||
const blob = new Blob([allText.value], { type: 'text/plain;charset=utf-8' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'code-results.txt';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
imageSrc.value = '';
|
||||
fileName.value = '';
|
||||
results.value = [];
|
||||
error.value = '';
|
||||
}
|
||||
|
||||
// fit viewport: no page scroll
|
||||
const rootEl = ref<HTMLElement>();
|
||||
const rootStyle = ref<Record<string, string>>({});
|
||||
|
||||
function fit() {
|
||||
const el = rootEl.value;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
const top = el.getBoundingClientRect().top;
|
||||
const height = Math.max(300, window.innerHeight - top - 12);
|
||||
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
|
||||
}
|
||||
|
||||
let observer: ResizeObserver | undefined;
|
||||
onMounted(() => {
|
||||
fit();
|
||||
window.addEventListener('resize', fit);
|
||||
window.addEventListener('paste', onPaste);
|
||||
observer = new ResizeObserver(() => fit());
|
||||
if (rootEl.value) {
|
||||
observer.observe(rootEl.value);
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', fit);
|
||||
window.removeEventListener('paste', onPaste);
|
||||
observer?.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="rootEl" class="cr-root" :style="rootStyle">
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
style="display:none"
|
||||
@change="onInputChange"
|
||||
>
|
||||
|
||||
<div class="toolbar">
|
||||
<div class="stats">
|
||||
<template v-if="results.length">
|
||||
识别到 {{ results.length }} 个码 · {{ elapsed }}ms
|
||||
</template>
|
||||
</div>
|
||||
<c-button :disabled="!imageSrc || loading" @click="reRecognize">
|
||||
重新识别
|
||||
</c-button>
|
||||
<c-button :disabled="!results.length" @click="copyText(allText)">
|
||||
复制全部
|
||||
</c-button>
|
||||
<c-button :disabled="!results.length" @click="downloadTxt">
|
||||
下载TXT
|
||||
</c-button>
|
||||
<c-button @click="clearAll">
|
||||
清空
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<div class="body">
|
||||
<!-- left: image -->
|
||||
<div class="pane">
|
||||
<div
|
||||
class="dropzone"
|
||||
:class="{ active: dragActive, hasImage: !!imageSrc }"
|
||||
@click="pickFile"
|
||||
@dragover.prevent="dragActive = true"
|
||||
@dragleave.prevent="dragActive = false"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<img v-if="imageSrc" :src="imageSrc" alt="待识别图片">
|
||||
<div v-else class="drop-hint">
|
||||
<div class="icon">
|
||||
🔍
|
||||
</div>
|
||||
<div>点击选择图片</div>
|
||||
<div class="sub">或拖拽图片到此处 / Ctrl+V 粘贴截图</div>
|
||||
<div class="sub">支持二维码、条形码混合识别</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="fileName" class="hint">
|
||||
{{ fileName }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- right: results -->
|
||||
<div class="pane">
|
||||
<n-spin :show="loading">
|
||||
<div v-if="error && !results.length" class="cr-error">
|
||||
{{ error }}
|
||||
</div>
|
||||
<div v-else-if="!results.length" class="empty">
|
||||
识别结果将显示在这里
|
||||
</div>
|
||||
<div v-else class="results">
|
||||
<div v-for="(r, i) in results" :key="i" class="result-item">
|
||||
<div class="result-head">
|
||||
<span class="badge">{{ r.format }}</span>
|
||||
<span class="meta">{{ r.contentType }} · {{ r.symbology }}</span>
|
||||
<c-button size="small" @click="copyText(r.text)">
|
||||
复制
|
||||
</c-button>
|
||||
</div>
|
||||
<div class="result-text">
|
||||
{{ r.text }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</n-spin>
|
||||
<div v-if="error && results.length" class="warn">
|
||||
{{ error }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<GenHistory tool="code-reader" position="bottom" label="识别记录" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.cr-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
padding-bottom: 12px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.stats {
|
||||
margin-right: auto;
|
||||
font-size: 13px;
|
||||
opacity: 0.65;
|
||||
}
|
||||
}
|
||||
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 16px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@media (max-width: 760px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.pane {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.dropzone {
|
||||
flex: 1;
|
||||
min-height: 180px;
|
||||
border: 2px dashed rgba(128, 128, 128, 0.45);
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
transition: border-color 0.2s, background-color 0.2s;
|
||||
box-sizing: border-box;
|
||||
|
||||
&:hover,
|
||||
&.active {
|
||||
border-color: #18a058;
|
||||
background-color: rgba(24, 160, 88, 0.06);
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.drop-hint {
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
opacity: 0.75;
|
||||
|
||||
.icon {
|
||||
font-size: 40px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.sub {
|
||||
font-size: 12px;
|
||||
opacity: 0.6;
|
||||
margin-top: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
opacity: 0.55;
|
||||
margin-top: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
min-height: 150px;
|
||||
border: 1px solid rgba(128, 128, 128, 0.3);
|
||||
border-radius: 6px;
|
||||
opacity: 0.5;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.cr-error {
|
||||
color: #d03050;
|
||||
font-size: 13px;
|
||||
padding: 12px;
|
||||
border: 1px solid rgba(208, 48, 80, 0.35);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.warn {
|
||||
font-size: 12px;
|
||||
color: #d03050;
|
||||
margin-top: 8px;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.results {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
border: 1px solid rgba(128, 128, 128, 0.3);
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.result-item {
|
||||
border: 1px solid rgba(128, 128, 128, 0.22);
|
||||
border-radius: 6px;
|
||||
padding: 8px 10px;
|
||||
user-select: text;
|
||||
|
||||
.result-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
|
||||
.badge {
|
||||
background: rgba(24, 160, 88, 0.14);
|
||||
color: #18a058;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
padding: 1px 8px;
|
||||
border-radius: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.meta {
|
||||
font-size: 11px;
|
||||
opacity: 0.5;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.result-text {
|
||||
font-size: 13.5px;
|
||||
line-height: 1.6;
|
||||
word-break: break-all;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Scan } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.code-reader.title'),
|
||||
path: '/code-reader',
|
||||
description: translate('tools.code-reader.description'),
|
||||
keywords: ['scan', 'reader', 'decode', 'qr', 'barcode', 'zxing', 'camera', 'image', '识别', '扫码', '读取', '解码', '二维码', '条码'],
|
||||
component: () => import('./code-reader.vue'),
|
||||
icon: Scan,
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test.describe('Tool - Color converter', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/color-converter');
|
||||
});
|
||||
|
||||
test('Has title', async ({ page }) => {
|
||||
await expect(page).toHaveTitle('Color converter - IT Tools');
|
||||
});
|
||||
|
||||
test('Color is converted from its name to other formats', async ({ page }) => {
|
||||
await page.getByTestId('input-name').fill('olive');
|
||||
|
||||
expect(await page.getByTestId('input-name').inputValue()).toEqual('olive');
|
||||
expect(await page.getByTestId('input-hex').inputValue()).toEqual('#808000');
|
||||
expect(await page.getByTestId('input-rgb').inputValue()).toEqual('rgb(128, 128, 0)');
|
||||
expect(await page.getByTestId('input-hsl').inputValue()).toEqual('hsl(60, 100%, 25%)');
|
||||
expect(await page.getByTestId('input-hwb').inputValue()).toEqual('hwb(60 0% 50%)');
|
||||
expect(await page.getByTestId('input-cmyk').inputValue()).toEqual('device-cmyk(0% 0% 100% 50%)');
|
||||
expect(await page.getByTestId('input-lch').inputValue()).toEqual('lch(52.15% 56.81 99.57)');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { removeAlphaChannelWhenOpaque } from './color-converter.models';
|
||||
|
||||
describe('color-converter models', () => {
|
||||
describe('removeAlphaChannelWhenOpaque', () => {
|
||||
it('remove alpha channel of an hex color when it is opaque (alpha = 1)', () => {
|
||||
expect(removeAlphaChannelWhenOpaque('#000000ff')).toBe('#000000');
|
||||
expect(removeAlphaChannelWhenOpaque('#ffffffFF')).toBe('#ffffff');
|
||||
expect(removeAlphaChannelWhenOpaque('#000000FE')).toBe('#000000FE');
|
||||
expect(removeAlphaChannelWhenOpaque('#00000000')).toBe('#00000000');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { type Colord, colord } from 'colord';
|
||||
import { withDefaultOnError } from '@/utils/defaults';
|
||||
import { useValidation } from '@/composable/validation';
|
||||
|
||||
export { removeAlphaChannelWhenOpaque, buildColorFormat };
|
||||
|
||||
function removeAlphaChannelWhenOpaque(hexColor: string) {
|
||||
return hexColor.replace(/^(#(?:[0-9a-f]{3}){1,2})ff$/i, '$1');
|
||||
}
|
||||
|
||||
function buildColorFormat({
|
||||
label,
|
||||
parse = value => colord(value),
|
||||
format,
|
||||
placeholder,
|
||||
invalidMessage = `Invalid ${label.toLowerCase()} format.`,
|
||||
type = 'text',
|
||||
}: {
|
||||
label: string
|
||||
parse?: (value: string) => Colord
|
||||
format: (value: Colord) => string
|
||||
placeholder?: string
|
||||
invalidMessage?: string
|
||||
type?: 'text' | 'color-picker'
|
||||
}) {
|
||||
const value = ref('');
|
||||
|
||||
return {
|
||||
type,
|
||||
label,
|
||||
parse: (v: string) => withDefaultOnError(() => parse(v), undefined),
|
||||
format,
|
||||
placeholder,
|
||||
value,
|
||||
validation: useValidation({
|
||||
source: value,
|
||||
rules: [
|
||||
{
|
||||
message: invalidMessage,
|
||||
validator: v => withDefaultOnError(() => {
|
||||
if (v === '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return parse(v).isValid();
|
||||
}, false),
|
||||
},
|
||||
],
|
||||
}),
|
||||
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<script setup lang="ts">
|
||||
import type { Colord } from 'colord';
|
||||
import { colord, extend } from 'colord';
|
||||
import _ from 'lodash';
|
||||
import cmykPlugin from 'colord/plugins/cmyk';
|
||||
import hwbPlugin from 'colord/plugins/hwb';
|
||||
import namesPlugin from 'colord/plugins/names';
|
||||
import lchPlugin from 'colord/plugins/lch';
|
||||
import { buildColorFormat } from './color-converter.models';
|
||||
|
||||
extend([cmykPlugin, hwbPlugin, namesPlugin, lchPlugin]);
|
||||
|
||||
const formats = {
|
||||
picker: buildColorFormat({
|
||||
label: 'color picker',
|
||||
format: (v: Colord) => v.toHex(),
|
||||
type: 'color-picker',
|
||||
}),
|
||||
hex: buildColorFormat({
|
||||
label: 'hex',
|
||||
format: (v: Colord) => v.toHex(),
|
||||
placeholder: 'e.g. #ff0000',
|
||||
}),
|
||||
rgb: buildColorFormat({
|
||||
label: 'rgb',
|
||||
format: (v: Colord) => v.toRgbString(),
|
||||
placeholder: 'e.g. rgb(255, 0, 0)',
|
||||
}),
|
||||
hsl: buildColorFormat({
|
||||
label: 'hsl',
|
||||
format: (v: Colord) => v.toHslString(),
|
||||
placeholder: 'e.g. hsl(0, 100%, 50%)',
|
||||
}),
|
||||
hwb: buildColorFormat({
|
||||
label: 'hwb',
|
||||
format: (v: Colord) => v.toHwbString(),
|
||||
placeholder: 'e.g. hwb(0, 0%, 0%)',
|
||||
}),
|
||||
lch: buildColorFormat({
|
||||
label: 'lch',
|
||||
format: (v: Colord) => v.toLchString(),
|
||||
placeholder: 'e.g. lch(53.24, 104.55, 40.85)',
|
||||
}),
|
||||
cmyk: buildColorFormat({
|
||||
label: 'cmyk',
|
||||
format: (v: Colord) => v.toCmykString(),
|
||||
placeholder: 'e.g. cmyk(0, 100%, 100%, 0)',
|
||||
}),
|
||||
name: buildColorFormat({
|
||||
label: 'name',
|
||||
format: (v: Colord) => v.toName({ closest: true }) ?? 'Unknown',
|
||||
placeholder: 'e.g. red',
|
||||
}),
|
||||
};
|
||||
|
||||
updateColorValue(colord('#1ea54c'));
|
||||
|
||||
function updateColorValue(value: Colord | undefined, omitLabel?: string) {
|
||||
if (value === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!value.isValid()) {
|
||||
return;
|
||||
}
|
||||
|
||||
_.forEach(formats, ({ value: valueRef, format }, key) => {
|
||||
if (key !== omitLabel) {
|
||||
valueRef.value = format(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card>
|
||||
<template v-for="({ label, parse, placeholder, validation, type }, key) in formats" :key="key">
|
||||
<input-copyable
|
||||
v-if="type === 'text'"
|
||||
v-model:value="formats[key].value.value"
|
||||
:test-id="`input-${key}`"
|
||||
:label="`${label}:`"
|
||||
label-position="left"
|
||||
label-width="100px"
|
||||
label-align="right"
|
||||
:placeholder="placeholder"
|
||||
:validation="validation"
|
||||
raw-text
|
||||
clearable
|
||||
mt-2
|
||||
@update:value="(v:string) => updateColorValue(parse(v), key)"
|
||||
/>
|
||||
|
||||
<n-form-item v-else-if="type === 'color-picker'" :label="`${label}:`" label-width="100" label-placement="left" :show-feedback="false">
|
||||
<n-color-picker
|
||||
v-model:value="formats[key].value.value"
|
||||
placement="bottom-end"
|
||||
@update:value="(v:string) => updateColorValue(parse(v), key)"
|
||||
/>
|
||||
</n-form-item>
|
||||
</template>
|
||||
</c-card>
|
||||
</template>
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Palette } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.color-converter.title'),
|
||||
path: '/color-converter',
|
||||
description: translate('tools.color-converter.description'),
|
||||
keywords: ['color', 'converter'],
|
||||
component: () => import('./color-converter.vue'),
|
||||
icon: Palette,
|
||||
redirectFrom: ['/color-picker-converter'],
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
<script setup lang="ts">
|
||||
import cronstrue from 'cronstrue';
|
||||
import { isValidCron } from 'cron-validator';
|
||||
import { useStyleStore } from '@/stores/style.store';
|
||||
|
||||
function isCronValid(v: string) {
|
||||
return isValidCron(v, { allowBlankDay: true, alias: true, seconds: true });
|
||||
}
|
||||
|
||||
const styleStore = useStyleStore();
|
||||
|
||||
const cron = ref('40 * * * *');
|
||||
const cronstrueConfig = reactive({
|
||||
verbose: true,
|
||||
dayOfWeekStartIndexZero: true,
|
||||
use24HourTimeFormat: true,
|
||||
throwExceptionOnParseError: true,
|
||||
});
|
||||
|
||||
const helpers = [
|
||||
{
|
||||
symbol: '*',
|
||||
meaning: 'Any value',
|
||||
example: '* * * *',
|
||||
equivalent: 'Every minute',
|
||||
},
|
||||
{
|
||||
symbol: '-',
|
||||
meaning: 'Range of values',
|
||||
example: '1-10 * * *',
|
||||
equivalent: 'Minutes 1 through 10',
|
||||
},
|
||||
{
|
||||
symbol: ',',
|
||||
meaning: 'List of values',
|
||||
example: '1,10 * * *',
|
||||
equivalent: 'At minutes 1 and 10',
|
||||
},
|
||||
{
|
||||
symbol: '/',
|
||||
meaning: 'Step values',
|
||||
example: '*/10 * * *',
|
||||
equivalent: 'Every 10 minutes',
|
||||
},
|
||||
{
|
||||
symbol: '@yearly',
|
||||
meaning: 'Once every year at midnight of 1 January',
|
||||
example: '@yearly',
|
||||
equivalent: '0 0 1 1 *',
|
||||
},
|
||||
{
|
||||
symbol: '@annually',
|
||||
meaning: 'Same as @yearly',
|
||||
example: '@annually',
|
||||
equivalent: '0 0 1 1 *',
|
||||
},
|
||||
{
|
||||
symbol: '@monthly',
|
||||
meaning: 'Once a month at midnight on the first day',
|
||||
example: '@monthly',
|
||||
equivalent: '0 0 1 * *',
|
||||
},
|
||||
{
|
||||
symbol: '@weekly',
|
||||
meaning: 'Once a week at midnight on Sunday morning',
|
||||
example: '@weekly',
|
||||
equivalent: '0 0 * * 0',
|
||||
},
|
||||
{
|
||||
symbol: '@daily',
|
||||
meaning: 'Once a day at midnight',
|
||||
example: '@daily',
|
||||
equivalent: '0 0 * * *',
|
||||
},
|
||||
{
|
||||
symbol: '@midnight',
|
||||
meaning: 'Same as @daily',
|
||||
example: '@midnight',
|
||||
equivalent: '0 0 * * *',
|
||||
},
|
||||
{
|
||||
symbol: '@hourly',
|
||||
meaning: 'Once an hour at the beginning of the hour',
|
||||
example: '@hourly',
|
||||
equivalent: '0 * * * *',
|
||||
},
|
||||
{
|
||||
symbol: '@reboot',
|
||||
meaning: 'Run at startup',
|
||||
example: '',
|
||||
equivalent: '',
|
||||
},
|
||||
];
|
||||
|
||||
const cronString = computed(() => {
|
||||
if (isCronValid(cron.value)) {
|
||||
return cronstrue.toString(cron.value, cronstrueConfig);
|
||||
}
|
||||
return ' ';
|
||||
});
|
||||
|
||||
const cronValidationRules = [
|
||||
{
|
||||
validator: (value: string) => isCronValid(value),
|
||||
message: 'This cron is invalid',
|
||||
},
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card>
|
||||
<div mx-auto max-w-sm>
|
||||
<c-input-text
|
||||
v-model:value="cron"
|
||||
size="large"
|
||||
placeholder="* * * * *"
|
||||
:validation-rules="cronValidationRules"
|
||||
mb-3
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="cron-string">
|
||||
{{ cronString }}
|
||||
</div>
|
||||
|
||||
<n-divider />
|
||||
|
||||
<div flex justify-center>
|
||||
<n-form :show-feedback="false" label-width="170" label-placement="left">
|
||||
<n-form-item label="Verbose">
|
||||
<n-switch v-model:value="cronstrueConfig.verbose" />
|
||||
</n-form-item>
|
||||
<n-form-item label="Use 24 hour time format">
|
||||
<n-switch v-model:value="cronstrueConfig.use24HourTimeFormat" />
|
||||
</n-form-item>
|
||||
<n-form-item label="Days start at 0">
|
||||
<n-switch v-model:value="cronstrueConfig.dayOfWeekStartIndexZero" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</div>
|
||||
</c-card>
|
||||
<c-card>
|
||||
<pre>
|
||||
┌──────────── [optional] seconds (0 - 59)
|
||||
| ┌────────── minute (0 - 59)
|
||||
| | ┌──────── hour (0 - 23)
|
||||
| | | ┌────── day of month (1 - 31)
|
||||
| | | | ┌──── month (1 - 12) OR jan,feb,mar,apr ...
|
||||
| | | | | ┌── day of week (0 - 6, sunday=0) OR sun,mon ...
|
||||
| | | | | |
|
||||
* * * * * * command</pre>
|
||||
|
||||
<div v-if="styleStore.isSmallScreen">
|
||||
<c-card v-for="{ symbol, meaning, example, equivalent } in helpers" :key="symbol" mb-3 important:border-none>
|
||||
<div>
|
||||
Symbol: <strong>{{ symbol }}</strong>
|
||||
</div>
|
||||
<div>
|
||||
Meaning: <strong>{{ meaning }}</strong>
|
||||
</div>
|
||||
<div>
|
||||
Example:
|
||||
<strong><code>{{ example }}</code></strong>
|
||||
</div>
|
||||
<div>
|
||||
Equivalent: <strong>{{ equivalent }}</strong>
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
|
||||
<c-table v-else :data="helpers" />
|
||||
</c-card>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
::v-deep(input) {
|
||||
font-size: 30px;
|
||||
font-family: monospace;
|
||||
padding: 5px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cron-string {
|
||||
text-align: center;
|
||||
font-size: 22px;
|
||||
opacity: 0.8;
|
||||
margin: 5px 0 15px;
|
||||
}
|
||||
|
||||
pre {
|
||||
overflow: auto;
|
||||
padding: 10px 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Alarm } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.crontab-generator.title'),
|
||||
path: '/crontab-generator',
|
||||
description: translate('tools.crontab-generator.description'),
|
||||
keywords: [
|
||||
'crontab',
|
||||
'generator',
|
||||
'cronjob',
|
||||
'cron',
|
||||
'schedule',
|
||||
'parse',
|
||||
'expression',
|
||||
'year',
|
||||
'month',
|
||||
'week',
|
||||
'day',
|
||||
'minute',
|
||||
'second',
|
||||
],
|
||||
component: () => import('./crontab-generator.vue'),
|
||||
icon: Alarm,
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test.describe('Date time converter - json to yaml', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/date-converter');
|
||||
});
|
||||
|
||||
test('Has correct title', async ({ page }) => {
|
||||
await expect(page).toHaveTitle('Date-time converter - IT Tools');
|
||||
});
|
||||
|
||||
test('Format is auto detected from a date and the date is correctly converted', async ({ page }) => {
|
||||
const initialFormat = await page.getByTestId('date-time-converter-format-select').innerText();
|
||||
expect(initialFormat.trim()).toEqual('Timestamp');
|
||||
|
||||
await page.getByTestId('date-time-converter-input').fill('2023-04-12T23:10:24+02:00');
|
||||
|
||||
const detectedFormat = await page.getByTestId('date-time-converter-format-select').innerText();
|
||||
expect(detectedFormat.trim()).toEqual('ISO 8601');
|
||||
|
||||
expect((await page.getByTestId('JS locale date string').inputValue()).trim()).toEqual(
|
||||
'Wed Apr 12 2023 23:10:24 GMT+0200 (Central European Summer Time)',
|
||||
);
|
||||
expect((await page.getByTestId('ISO 8601').inputValue()).trim()).toEqual('2023-04-12T23:10:24+02:00');
|
||||
expect((await page.getByTestId('ISO 9075').inputValue()).trim()).toEqual('2023-04-12 23:10:24');
|
||||
expect((await page.getByTestId('Unix timestamp').inputValue()).trim()).toEqual('1681333824');
|
||||
expect((await page.getByTestId('RFC 7231').inputValue()).trim()).toEqual('Wed, 12 Apr 2023 21:10:24 GMT');
|
||||
expect((await page.getByTestId('RFC 3339').inputValue()).trim()).toEqual('2023-04-12T23:10:24+02:00');
|
||||
expect((await page.getByTestId('Timestamp').inputValue()).trim()).toEqual('1681333824000');
|
||||
expect((await page.getByTestId('UTC format').inputValue()).trim()).toEqual('Wed, 12 Apr 2023 21:10:24 GMT');
|
||||
expect((await page.getByTestId('Mongo ObjectID').inputValue()).trim()).toEqual('64371e400000000000000000');
|
||||
expect((await page.getByTestId('Excel date/time').inputValue()).trim()).toEqual('45028.88222222222');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import {
|
||||
dateToExcelFormat,
|
||||
excelFormatToDate,
|
||||
isExcelFormat,
|
||||
isISO8601DateTimeString,
|
||||
isISO9075DateString,
|
||||
isMongoObjectId,
|
||||
isRFC3339DateString,
|
||||
isRFC7231DateString,
|
||||
isTimestamp,
|
||||
isUTCDateString,
|
||||
isUnixTimestamp,
|
||||
} from './date-time-converter.models';
|
||||
|
||||
describe('date-time-converter models', () => {
|
||||
describe('isISO8601DateTimeString', () => {
|
||||
test('should return true for valid ISO 8601 date strings', () => {
|
||||
expect(isISO8601DateTimeString('2021-01-01T00:00:00.000Z')).toBe(true);
|
||||
expect(isISO8601DateTimeString('2023-04-12T14:56:00+01:00')).toBe(true);
|
||||
expect(isISO8601DateTimeString('20230412T145600+0100')).toBe(true);
|
||||
expect(isISO8601DateTimeString('20230412T145600Z')).toBe(true);
|
||||
expect(isISO8601DateTimeString('2016-02-01')).toBe(true);
|
||||
expect(isISO8601DateTimeString('2016')).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for invalid ISO 8601 date strings', () => {
|
||||
expect(isISO8601DateTimeString()).toBe(false);
|
||||
expect(isISO8601DateTimeString('')).toBe(false);
|
||||
expect(isISO8601DateTimeString('qsdqsd')).toBe(false);
|
||||
expect(isISO8601DateTimeString('2016-02-01-')).toBe(false);
|
||||
expect(isISO8601DateTimeString('2021-01-01T00:00:00.')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isISO9075DateString', () => {
|
||||
test('should return true for valid ISO 9075 date strings', () => {
|
||||
expect(isISO9075DateString('2022-01-01 12:00:00Z')).toBe(true);
|
||||
expect(isISO9075DateString('2022-01-01 12:00:00.123456Z')).toBe(true);
|
||||
expect(isISO9075DateString('2022-01-01 12:00:00+01:00')).toBe(true);
|
||||
expect(isISO9075DateString('2022-01-01 12:00:00-05:00')).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for invalid ISO 9075 date strings', () => {
|
||||
expect(isISO9075DateString('2022/01/01T12:00:00Z')).toBe(false);
|
||||
expect(isISO9075DateString('2022-01-01 12:00:00.123456789Z')).toBe(false);
|
||||
expect(isISO9075DateString('2022-01-01 12:00:00+1:00')).toBe(false);
|
||||
expect(isISO9075DateString('2022-01-01 12:00:00-05:')).toBe(false);
|
||||
expect(isISO9075DateString('2022-01-01 12:00:00-05:00:00')).toBe(false);
|
||||
expect(isISO9075DateString('2022-01-01')).toBe(false);
|
||||
expect(isISO9075DateString('12:00:00Z')).toBe(false);
|
||||
expect(isISO9075DateString('2022-01-01T12:00:00Zfoo')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isRFC3339DateString', () => {
|
||||
test('should return true for valid RFC 3339 date strings', () => {
|
||||
expect(isRFC3339DateString('2022-01-01T12:00:00Z')).toBe(true);
|
||||
expect(isRFC3339DateString('2022-01-01T12:00:00.123456789Z')).toBe(true);
|
||||
expect(isRFC3339DateString('2022-01-01T12:00:00.123456789+01:00')).toBe(true);
|
||||
expect(isRFC3339DateString('2022-01-01T12:00:00-05:00')).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for invalid RFC 3339 date strings', () => {
|
||||
expect(isRFC3339DateString('2022/01/01T12:00:00Z')).toBe(false);
|
||||
expect(isRFC3339DateString('2022-01-01T12:00:00.123456789+1:00')).toBe(false);
|
||||
expect(isRFC3339DateString('2022-01-01T12:00:00-05:')).toBe(false);
|
||||
expect(isRFC3339DateString('2022-01-01T12:00:00-05:00:00')).toBe(false);
|
||||
expect(isRFC3339DateString('2022-01-01')).toBe(false);
|
||||
expect(isRFC3339DateString('12:00:00Z')).toBe(false);
|
||||
expect(isRFC3339DateString('2022-01-01T12:00:00Zfoo')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isRFC7231DateString', () => {
|
||||
test('should return true for valid RFC 7231 date strings', () => {
|
||||
expect(isRFC7231DateString('Sun, 06 Nov 1994 08:49:37 GMT')).toBe(true);
|
||||
expect(isRFC7231DateString('Tue, 22 Apr 2014 07:00:00 GMT')).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for invalid RFC 7231 date strings', () => {
|
||||
expect(isRFC7231DateString('06 Nov 1994 08:49:37 GMT')).toBe(false);
|
||||
expect(isRFC7231DateString('Sun, 06 Nov 94 08:49:37 GMT')).toBe(false);
|
||||
expect(isRFC7231DateString('Sun, 06 Nov 1994 8:49:37 GMT')).toBe(false);
|
||||
expect(isRFC7231DateString('Sun, 06 Nov 1994 08:49:37 GMT-0500')).toBe(false);
|
||||
expect(isRFC7231DateString('Sun, 06 November 1994 08:49:37 GMT')).toBe(false);
|
||||
expect(isRFC7231DateString('Sunday, 06 Nov 1994 08:49:37 GMT')).toBe(false);
|
||||
expect(isRFC7231DateString('06 Nov 1994')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isUnixTimestamp', () => {
|
||||
test('should return true for valid Unix timestamps', () => {
|
||||
expect(isUnixTimestamp('1649789394')).toBe(true);
|
||||
expect(isUnixTimestamp('1234567890')).toBe(true);
|
||||
expect(isUnixTimestamp('0')).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for invalid Unix timestamps', () => {
|
||||
expect(isUnixTimestamp('foo')).toBe(false);
|
||||
expect(isUnixTimestamp('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isTimestamp', () => {
|
||||
test('should return true for valid Unix timestamps in milliseconds', () => {
|
||||
expect(isTimestamp('1649792026123')).toBe(true);
|
||||
expect(isTimestamp('1234567890000')).toBe(true);
|
||||
expect(isTimestamp('0')).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for invalid Unix timestamps in milliseconds', () => {
|
||||
expect(isTimestamp('foo')).toBe(false);
|
||||
expect(isTimestamp('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isUTCDateString', () => {
|
||||
test('should return true for valid UTC date strings', () => {
|
||||
expect(isUTCDateString('Sun, 06 Nov 1994 08:49:37 GMT')).toBe(true);
|
||||
expect(isUTCDateString('Tue, 22 Apr 2014 07:00:00 GMT')).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for invalid UTC date strings', () => {
|
||||
expect(isUTCDateString('06 Nov 1994 08:49:37 GMT')).toBe(false);
|
||||
expect(isUTCDateString('16497920261')).toBe(false);
|
||||
expect(isUTCDateString('foo')).toBe(false);
|
||||
expect(isUTCDateString('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isMongoObjectId', () => {
|
||||
test('should return true for valid Mongo ObjectIds', () => {
|
||||
expect(isMongoObjectId('507f1f77bcf86cd799439011')).toBe(true);
|
||||
expect(isMongoObjectId('507f1f77bcf86cd799439012')).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for invalid Mongo ObjectIds', () => {
|
||||
expect(isMongoObjectId('507f1f77bcf86cd79943901')).toBe(false);
|
||||
expect(isMongoObjectId('507f1f77bcf86cd79943901z')).toBe(false);
|
||||
expect(isMongoObjectId('foo')).toBe(false);
|
||||
expect(isMongoObjectId('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isExcelFormat', () => {
|
||||
test('an Excel format string is a floating number that can be negative', () => {
|
||||
expect(isExcelFormat('0')).toBe(true);
|
||||
expect(isExcelFormat('1')).toBe(true);
|
||||
expect(isExcelFormat('1.1')).toBe(true);
|
||||
expect(isExcelFormat('-1.1')).toBe(true);
|
||||
expect(isExcelFormat('-1')).toBe(true);
|
||||
|
||||
expect(isExcelFormat('')).toBe(false);
|
||||
expect(isExcelFormat('foo')).toBe(false);
|
||||
expect(isExcelFormat('1.1.1')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dateToExcelFormat', () => {
|
||||
test('a date in Excel format is the number of days since 01/01/1900', () => {
|
||||
expect(dateToExcelFormat(new Date('2016-05-20T00:00:00.000Z'))).toBe('42510');
|
||||
expect(dateToExcelFormat(new Date('2016-05-20T12:00:00.000Z'))).toBe('42510.5');
|
||||
expect(dateToExcelFormat(new Date('2023-10-31T09:26:06.421Z'))).toBe('45230.39312987268');
|
||||
expect(dateToExcelFormat(new Date('1970-01-01T00:00:00.000Z'))).toBe('25569');
|
||||
expect(dateToExcelFormat(new Date('1800-01-01T00:00:00.000Z'))).toBe('-36522');
|
||||
});
|
||||
});
|
||||
|
||||
describe('excelFormatToDate', () => {
|
||||
test('a date in Excel format is the number of days since 01/01/1900', () => {
|
||||
expect(excelFormatToDate('0')).toEqual(new Date('1899-12-30T00:00:00.000Z'));
|
||||
expect(excelFormatToDate('1')).toEqual(new Date('1899-12-31T00:00:00.000Z'));
|
||||
expect(excelFormatToDate('2')).toEqual(new Date('1900-01-01T00:00:00.000Z'));
|
||||
expect(excelFormatToDate('4242.4242')).toEqual(new Date('1911-08-12T10:10:50.880Z'));
|
||||
expect(excelFormatToDate('42738.22626859954')).toEqual(new Date('2017-01-03T05:25:49.607Z'));
|
||||
expect(excelFormatToDate('-1000')).toEqual(new Date('1897-04-04T00:00:00.000Z'));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import _ from 'lodash';
|
||||
|
||||
export {
|
||||
isISO8601DateTimeString,
|
||||
isISO9075DateString,
|
||||
isRFC3339DateString,
|
||||
isRFC7231DateString,
|
||||
isUnixTimestamp,
|
||||
isTimestamp,
|
||||
isUTCDateString,
|
||||
isMongoObjectId,
|
||||
dateToExcelFormat,
|
||||
excelFormatToDate,
|
||||
isExcelFormat,
|
||||
};
|
||||
|
||||
const ISO8601_REGEX
|
||||
= /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
|
||||
const ISO9075_REGEX
|
||||
= /^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]{1,6})?(([+-])([0-9]{2}):([0-9]{2})|Z)?$/;
|
||||
|
||||
const RFC3339_REGEX
|
||||
= /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]{1,9})?(([+-])([0-9]{2}):([0-9]{2})|Z)$/;
|
||||
|
||||
const RFC7231_REGEX = /^[A-Za-z]{3},\s[0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\sGMT$/;
|
||||
|
||||
const EXCEL_FORMAT_REGEX = /^-?\d+(\.\d+)?$/;
|
||||
|
||||
function createRegexMatcher(regex: RegExp) {
|
||||
return (date?: string) => !_.isNil(date) && regex.test(date);
|
||||
}
|
||||
|
||||
const isISO8601DateTimeString = createRegexMatcher(ISO8601_REGEX);
|
||||
const isISO9075DateString = createRegexMatcher(ISO9075_REGEX);
|
||||
const isRFC3339DateString = createRegexMatcher(RFC3339_REGEX);
|
||||
const isRFC7231DateString = createRegexMatcher(RFC7231_REGEX);
|
||||
const isUnixTimestamp = createRegexMatcher(/^[0-9]{1,10}$/);
|
||||
const isTimestamp = createRegexMatcher(/^[0-9]{1,13}$/);
|
||||
const isMongoObjectId = createRegexMatcher(/^[0-9a-fA-F]{24}$/);
|
||||
|
||||
const isExcelFormat = createRegexMatcher(EXCEL_FORMAT_REGEX);
|
||||
|
||||
function isUTCDateString(date?: string) {
|
||||
if (_.isNil(date)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return new Date(date).toUTCString() === date;
|
||||
}
|
||||
catch (_ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function dateToExcelFormat(date: Date) {
|
||||
return String(((date.getTime()) / (1000 * 60 * 60 * 24)) + 25569);
|
||||
}
|
||||
|
||||
function excelFormatToDate(excelFormat: string | number) {
|
||||
return new Date((Number(excelFormat) - 25569) * 86400 * 1000);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export type ToDateMapper = (value: string) => Date;
|
||||
|
||||
export interface DateFormat {
|
||||
name: string
|
||||
fromDate: (date: Date) => string
|
||||
toDate: (value: string) => Date
|
||||
formatMatcher: (dateString: string) => boolean
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
formatISO,
|
||||
formatISO9075,
|
||||
formatRFC3339,
|
||||
formatRFC7231,
|
||||
fromUnixTime,
|
||||
getTime,
|
||||
getUnixTime,
|
||||
isDate,
|
||||
isValid,
|
||||
parseISO,
|
||||
parseJSON,
|
||||
} from 'date-fns';
|
||||
import type { DateFormat, ToDateMapper } from './date-time-converter.types';
|
||||
import {
|
||||
dateToExcelFormat,
|
||||
excelFormatToDate,
|
||||
isExcelFormat,
|
||||
isISO8601DateTimeString,
|
||||
isISO9075DateString,
|
||||
isMongoObjectId,
|
||||
isRFC3339DateString,
|
||||
isRFC7231DateString,
|
||||
isTimestamp,
|
||||
isUTCDateString,
|
||||
isUnixTimestamp,
|
||||
} from './date-time-converter.models';
|
||||
import { withDefaultOnError } from '@/utils/defaults';
|
||||
import { useValidation } from '@/composable/validation';
|
||||
|
||||
const inputDate = ref('');
|
||||
|
||||
const toDate: ToDateMapper = date => new Date(date);
|
||||
|
||||
const formats: DateFormat[] = [
|
||||
{
|
||||
name: 'JS locale date string',
|
||||
fromDate: date => date.toString(),
|
||||
toDate,
|
||||
formatMatcher: () => false,
|
||||
},
|
||||
{
|
||||
name: 'ISO 8601',
|
||||
fromDate: formatISO,
|
||||
toDate: parseISO,
|
||||
formatMatcher: date => isISO8601DateTimeString(date),
|
||||
},
|
||||
{
|
||||
name: 'ISO 9075',
|
||||
fromDate: formatISO9075,
|
||||
toDate: parseISO,
|
||||
formatMatcher: date => isISO9075DateString(date),
|
||||
},
|
||||
{
|
||||
name: 'RFC 3339',
|
||||
fromDate: formatRFC3339,
|
||||
toDate,
|
||||
formatMatcher: date => isRFC3339DateString(date),
|
||||
},
|
||||
{
|
||||
name: 'RFC 7231',
|
||||
fromDate: formatRFC7231,
|
||||
toDate,
|
||||
formatMatcher: date => isRFC7231DateString(date),
|
||||
},
|
||||
{
|
||||
name: 'Unix timestamp',
|
||||
fromDate: date => String(getUnixTime(date)),
|
||||
toDate: sec => fromUnixTime(+sec),
|
||||
formatMatcher: date => isUnixTimestamp(date),
|
||||
},
|
||||
{
|
||||
name: 'Timestamp',
|
||||
fromDate: date => String(getTime(date)),
|
||||
toDate: ms => parseJSON(+ms),
|
||||
formatMatcher: date => isTimestamp(date),
|
||||
},
|
||||
{
|
||||
name: 'UTC format',
|
||||
fromDate: date => date.toUTCString(),
|
||||
toDate,
|
||||
formatMatcher: date => isUTCDateString(date),
|
||||
},
|
||||
{
|
||||
name: 'Mongo ObjectID',
|
||||
fromDate: date => `${Math.floor(date.getTime() / 1000).toString(16)}0000000000000000`,
|
||||
toDate: objectId => new Date(Number.parseInt(objectId.substring(0, 8), 16) * 1000),
|
||||
formatMatcher: date => isMongoObjectId(date),
|
||||
},
|
||||
{
|
||||
name: 'Excel date/time',
|
||||
fromDate: date => dateToExcelFormat(date),
|
||||
toDate: excelFormatToDate,
|
||||
formatMatcher: isExcelFormat,
|
||||
},
|
||||
];
|
||||
|
||||
const formatIndex = ref(6);
|
||||
const now = useNow();
|
||||
|
||||
const normalizedDate = computed(() => {
|
||||
if (!inputDate.value) {
|
||||
return now.value;
|
||||
}
|
||||
|
||||
const { toDate } = formats[formatIndex.value];
|
||||
|
||||
try {
|
||||
return toDate(inputDate.value);
|
||||
}
|
||||
catch (_ignored) {
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
|
||||
function onDateInputChanged(value: string) {
|
||||
const matchingIndex = formats.findIndex(({ formatMatcher }) => formatMatcher(value));
|
||||
if (matchingIndex !== -1) {
|
||||
formatIndex.value = matchingIndex;
|
||||
}
|
||||
}
|
||||
|
||||
const validation = useValidation({
|
||||
source: inputDate,
|
||||
watch: [formatIndex],
|
||||
rules: [
|
||||
{
|
||||
message: 'This date is invalid for this format',
|
||||
validator: value =>
|
||||
withDefaultOnError(() => {
|
||||
if (value === '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
const maybeDate = formats[formatIndex.value].toDate(value);
|
||||
return isDate(maybeDate) && isValid(maybeDate);
|
||||
}, false),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function formatDateUsingFormatter(formatter: (date: Date) => string, date?: Date) {
|
||||
if (!date || !validation.isValid) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return withDefaultOnError(() => formatter(date), '');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div flex gap-2>
|
||||
<c-input-text
|
||||
v-model:value="inputDate"
|
||||
autofocus
|
||||
placeholder="Put your date string here..."
|
||||
clearable
|
||||
test-id="date-time-converter-input"
|
||||
:validation="validation"
|
||||
@update:value="onDateInputChanged"
|
||||
/>
|
||||
|
||||
<c-select
|
||||
v-model:value="formatIndex"
|
||||
style="flex: 0 0 170px"
|
||||
:options="formats.map(({ name }, i) => ({ label: name, value: i }))"
|
||||
data-test-id="date-time-converter-format-select"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<n-divider />
|
||||
|
||||
<input-copyable
|
||||
v-for="{ name, fromDate } in formats"
|
||||
:key="name"
|
||||
:label="name"
|
||||
label-width="150px"
|
||||
label-position="left"
|
||||
label-align="right"
|
||||
:value="formatDateUsingFormatter(fromDate, normalizedDate)"
|
||||
placeholder="Invalid date..."
|
||||
:test-id="name"
|
||||
readonly
|
||||
mt-2
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Calendar } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.date-converter.title'),
|
||||
path: '/date-converter',
|
||||
description: translate('tools.date-converter.description'),
|
||||
keywords: ['date', 'time', 'converter', 'iso', 'utc', 'timezone', 'year', 'month', 'day', 'minute', 'seconde'],
|
||||
component: () => import('./date-time-converter.vue'),
|
||||
icon: Calendar,
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
<script setup lang="ts">
|
||||
import { useWindowSize } from '@vueuse/core';
|
||||
|
||||
const { width, height } = useWindowSize();
|
||||
|
||||
const sections = [
|
||||
{
|
||||
name: 'Screen',
|
||||
information: [
|
||||
{
|
||||
label: 'Screen size',
|
||||
value: computed(() => `${window.screen.availWidth} x ${window.screen.availHeight}`),
|
||||
},
|
||||
{
|
||||
label: 'Orientation',
|
||||
value: computed(() => window.screen.orientation.type),
|
||||
},
|
||||
{
|
||||
label: 'Orientation angle',
|
||||
value: computed(() => `${window.screen.orientation.angle}°`),
|
||||
},
|
||||
{
|
||||
label: 'Color depth',
|
||||
value: computed(() => `${window.screen.colorDepth} bits`),
|
||||
},
|
||||
{
|
||||
label: 'Pixel ratio',
|
||||
value: computed(() => `${window.devicePixelRatio} dppx`),
|
||||
},
|
||||
{
|
||||
label: 'Window size',
|
||||
value: computed(() => `${width.value} x ${height.value}`),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Device',
|
||||
information: [
|
||||
{
|
||||
label: 'Browser vendor',
|
||||
value: computed(() => navigator.vendor),
|
||||
},
|
||||
{
|
||||
label: 'Languages',
|
||||
value: computed(() => navigator.languages.join(', ')),
|
||||
},
|
||||
{
|
||||
label: 'Platform',
|
||||
value: computed(() => navigator.platform),
|
||||
},
|
||||
{
|
||||
label: 'User agent',
|
||||
value: computed(() => navigator.userAgent),
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card v-for="{ name, information } in sections" :key="name" :title="name">
|
||||
<n-grid cols="1 400:2" x-gap="12" y-gap="12">
|
||||
<n-gi v-for="{ label, value: { value } } in information" :key="label" class="information">
|
||||
<div class="label">
|
||||
{{ label }}
|
||||
</div>
|
||||
|
||||
<div class="value">
|
||||
<n-ellipsis v-if="value">
|
||||
{{ value }}
|
||||
</n-ellipsis>
|
||||
<div v-else class="undefined-value">
|
||||
unknown
|
||||
</div>
|
||||
</div>
|
||||
</n-gi>
|
||||
</n-grid>
|
||||
</c-card>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.information {
|
||||
padding: 14px 16px;
|
||||
border-radius: 4px;
|
||||
background-color: #aaaaaa11;
|
||||
|
||||
.label {
|
||||
font-size: 14px;
|
||||
opacity: 0.8;
|
||||
line-height: 1;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.value {
|
||||
font-size: 20px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.undefined-value {
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,24 @@
|
||||
import { DeviceDesktop } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.device-information.title'),
|
||||
path: '/device-information',
|
||||
description: translate('tools.device-information.description'),
|
||||
keywords: [
|
||||
'device',
|
||||
'information',
|
||||
'screen',
|
||||
'pixel',
|
||||
'ratio',
|
||||
'status',
|
||||
'data',
|
||||
'computer',
|
||||
'size',
|
||||
'user',
|
||||
'agent',
|
||||
],
|
||||
component: () => import('./device-information.vue'),
|
||||
icon: DeviceDesktop,
|
||||
});
|
||||
@@ -0,0 +1,592 @@
|
||||
<script setup lang="ts">
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import { licenseHeaders } from '../license/license';
|
||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
||||
|
||||
const genHist = useGenHistory('doc-convert');
|
||||
|
||||
interface FmtGroup { label: string; items: { key: string; label: string; ext: string }[] }
|
||||
|
||||
const FORMAT_GROUPS: FmtGroup[] = [
|
||||
{
|
||||
label: '文档',
|
||||
items: [
|
||||
{ key: 'pdf', label: 'PDF', ext: '.pdf' },
|
||||
{ key: 'docx', label: 'DOCX', ext: '.docx' },
|
||||
{ key: 'txt', label: 'TXT', ext: '.txt' },
|
||||
{ key: 'rtf', label: 'RTF', ext: '.rtf' },
|
||||
{ key: 'odt', label: 'ODT', ext: '.odt' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '电子书',
|
||||
items: [
|
||||
{ key: 'epub', label: 'EPUB', ext: '.epub' },
|
||||
{ key: 'mobi', label: 'MOBI', ext: '.mobi' },
|
||||
{ key: 'azw3', label: 'AZW3', ext: '.azw3' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '网页',
|
||||
items: [{ key: 'html', label: 'HTML', ext: '.html' }],
|
||||
},
|
||||
];
|
||||
|
||||
const ALL_FMTS = FORMAT_GROUPS.flatMap(g => g.items.map(i => i.key));
|
||||
|
||||
const batchMode = useStorage('doc-convert:batch', false);
|
||||
const targetFmt = useStorage('doc-convert:fmt', 'pdf');
|
||||
|
||||
const MAX_MB = 100;
|
||||
const files = ref<File[]>([]);
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const dragActive = ref(false);
|
||||
const busy = ref(false);
|
||||
const statusMsg = ref('');
|
||||
const errorMsg = ref('');
|
||||
const resultUrl = ref('');
|
||||
const resultName = ref('');
|
||||
const resultSize = ref(0);
|
||||
|
||||
function pickFiles() {
|
||||
fileInput.value?.click();
|
||||
}
|
||||
|
||||
function onInputChange(e: Event) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
addFiles(Array.from(input.files ?? []));
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
function onDrop(e: DragEvent) {
|
||||
dragActive.value = false;
|
||||
addFiles(Array.from(e.dataTransfer?.files ?? []));
|
||||
}
|
||||
|
||||
function addFiles(list: File[]) {
|
||||
if (!list.length) {
|
||||
return;
|
||||
}
|
||||
for (const f of list) {
|
||||
if (f.size > MAX_MB * 1024 * 1024) {
|
||||
errorMsg.value = `${f.name} 超过 ${MAX_MB}MB 上限`;
|
||||
return;
|
||||
}
|
||||
const ext = f.name.toLowerCase().split('.').pop() ?? '';
|
||||
if (!ALL_FMTS.includes(ext) && !['doc', 'wps', 'chm', 'fb2', 'pdb'].includes(ext)) {
|
||||
errorMsg.value = `${f.name} 不是支持的文档格式`;
|
||||
return;
|
||||
}
|
||||
}
|
||||
errorMsg.value = '';
|
||||
clearResult();
|
||||
files.value = batchMode.value ? [...files.value, ...list] : list.slice(0, 1);
|
||||
}
|
||||
|
||||
function removeFile(i: number) {
|
||||
files.value.splice(i, 1);
|
||||
}
|
||||
|
||||
function toggleBatch(v: boolean) {
|
||||
batchMode.value = v;
|
||||
if (!v && files.value.length > 1) {
|
||||
files.value = files.value.slice(0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
function clearResult() {
|
||||
if (resultUrl.value) {
|
||||
URL.revokeObjectURL(resultUrl.value);
|
||||
}
|
||||
resultUrl.value = '';
|
||||
resultName.value = '';
|
||||
resultSize.value = 0;
|
||||
}
|
||||
|
||||
function fmtSize(n: number): string {
|
||||
return n > 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;
|
||||
}
|
||||
|
||||
async function execute() {
|
||||
errorMsg.value = '';
|
||||
if (!files.value.length) {
|
||||
errorMsg.value = '请先选择文件';
|
||||
return;
|
||||
}
|
||||
const fmtObj = FORMAT_GROUPS.flatMap(g => g.items).find(i => i.key === targetFmt.value)!;
|
||||
busy.value = true;
|
||||
statusMsg.value = `正在转换为 ${fmtObj.label}…(服务端处理,大文件需要一点时间)`;
|
||||
clearResult();
|
||||
const start = performance.now();
|
||||
try {
|
||||
const fd = new FormData();
|
||||
for (const f of files.value) {
|
||||
fd.append('files', f, f.name);
|
||||
}
|
||||
fd.append('format', targetFmt.value);
|
||||
const res = await fetch('/relay/convert', { method: 'POST', body: fd, headers: licenseHeaders('doc-convert') });
|
||||
if (res.status === 403) {
|
||||
throw new Error('授权校验未通过:免费试用已结束,请购买授权或输入卡密');
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `转换失败 HTTP ${res.status}`;
|
||||
try {
|
||||
const j = await res.json();
|
||||
if (j?.message) {
|
||||
msg = j.message;
|
||||
}
|
||||
}
|
||||
catch { /* ignore */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
const blob = await res.blob();
|
||||
const cd = res.headers.get('Content-Disposition') ?? '';
|
||||
const m = cd.match(/filename\*=UTF-8''([^;]+)/);
|
||||
const name = m ? decodeURIComponent(m[1]) : `converted.${fmtObj.ext.replace('.', '')}`;
|
||||
resultUrl.value = URL.createObjectURL(blob);
|
||||
resultName.value = name;
|
||||
resultSize.value = blob.size;
|
||||
const ms = Math.round(performance.now() - start);
|
||||
statusMsg.value = `转换完成,用时 ${(ms / 1000).toFixed(1)}s`;
|
||||
genHist.add({
|
||||
title: `${files.value.length > 1 ? `${files.value.length} 个文件 → ` : ''}${fmtObj.label}`,
|
||||
detail: files.value.map(f => f.name).join('、').slice(0, 60) + ` · ${fmtSize(blob.size)}`,
|
||||
});
|
||||
}
|
||||
catch (e: any) {
|
||||
errorMsg.value = e?.message ?? String(e);
|
||||
statusMsg.value = '';
|
||||
}
|
||||
finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function download() {
|
||||
if (!resultUrl.value) {
|
||||
return;
|
||||
}
|
||||
const a = document.createElement('a');
|
||||
a.href = resultUrl.value;
|
||||
a.download = resultName.value;
|
||||
a.click();
|
||||
}
|
||||
|
||||
// fit viewport
|
||||
const rootEl = ref<HTMLElement>();
|
||||
const rootStyle = ref<Record<string, string>>({});
|
||||
|
||||
function fit() {
|
||||
const el = rootEl.value;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
const top = el.getBoundingClientRect().top;
|
||||
const height = Math.max(360, window.innerHeight - top - 12);
|
||||
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fit();
|
||||
window.addEventListener('resize', fit);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', fit);
|
||||
clearResult();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="rootEl" class="dc-root" :style="rootStyle">
|
||||
<input ref="fileInput" type="file" :multiple="batchMode" accept=".pdf,.docx,.doc,.txt,.rtf,.odt,.epub,.mobi,.azw3,.html,.wps,.fb2" style="display:none" @change="onInputChange">
|
||||
|
||||
<!-- head -->
|
||||
<div class="dc-head">
|
||||
<span class="dc-title">文档格式转换</span>
|
||||
<span class="dc-badge">⚙ 自建服务</span>
|
||||
<span v-if="files.length" class="dc-count">{{ files.length }} 个文件 · {{ (files.reduce((s, f) => s + f.size, 0) / 1024 / 1024).toFixed(1) }} MB</span>
|
||||
</div>
|
||||
|
||||
<div class="dc-card">
|
||||
<!-- batch toggle -->
|
||||
<div class="dc-moderow">
|
||||
<div class="dc-modelabels">
|
||||
<span :class="{ on: batchMode }">批量转换</span>
|
||||
<span :class="{ on: !batchMode }">单文件转换</span>
|
||||
</div>
|
||||
<button class="dc-switch" :class="{ on: batchMode }" @click="toggleBatch(!batchMode)">
|
||||
<span class="dc-knob" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- upload -->
|
||||
<div
|
||||
class="dc-upload"
|
||||
:class="{ active: dragActive, has: files.length }"
|
||||
@click="!files.length && pickFiles()"
|
||||
@dragover.prevent="dragActive = true"
|
||||
@dragleave.prevent="dragActive = false"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<template v-if="files.length">
|
||||
<div class="dc-files">
|
||||
<div v-for="(f, i) in files" :key="i" class="dc-file">
|
||||
<span class="dc-file-name">📄 {{ f.name }}</span>
|
||||
<span class="dc-file-size">{{ (f.size / 1024 / 1024).toFixed(2) }} MB</span>
|
||||
<a href="javascript:;" class="dc-file-del" @click.stop="removeFile(i)">✕</a>
|
||||
</div>
|
||||
<a v-if="batchMode" href="javascript:;" class="dc-add-more" @click.stop="pickFiles">+ 继续添加</a>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="dc-upload-icon">⬆️</div>
|
||||
<div class="dc-upload-big">
|
||||
选择文件
|
||||
</div>
|
||||
<div class="dc-upload-sub">
|
||||
点击或拖拽文件到此处
|
||||
</div>
|
||||
<div class="dc-upload-sub">
|
||||
上限 {{ MAX_MB.toFixed(1) }} MB
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- target formats -->
|
||||
<div class="dc-fmts">
|
||||
<div v-for="g in FORMAT_GROUPS" :key="g.label" class="dc-fmt-group">
|
||||
<span class="dc-fmt-label">{{ g.label }}</span>
|
||||
<div class="dc-fmt-btns">
|
||||
<button
|
||||
v-for="it in g.items"
|
||||
:key="it.key"
|
||||
class="dc-fmt"
|
||||
:class="{ on: targetFmt === it.key }"
|
||||
@click="targetFmt = it.key"
|
||||
>
|
||||
{{ it.label }} <span class="dc-ext">({{ it.ext }})</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="statusMsg" class="dc-status">
|
||||
{{ statusMsg }}
|
||||
</div>
|
||||
<div v-if="errorMsg" class="dc-error">
|
||||
{{ errorMsg }}
|
||||
</div>
|
||||
|
||||
<!-- bottom -->
|
||||
<div class="dc-bottom">
|
||||
<GenHistory tool="doc-convert" position="bottom" label="转换记录" />
|
||||
<div class="dc-actions">
|
||||
<c-button v-if="resultUrl" @click="download">
|
||||
⬇ 下载 {{ resultName }}({{ fmtSize(resultSize) }})
|
||||
</c-button>
|
||||
<c-button type="primary" class="dc-exec" :disabled="busy || !files.length" @click="execute">
|
||||
{{ busy ? '转换中…' : '⇧ 执行' }}
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.dc-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
box-sizing: border-box;
|
||||
background: #fff;
|
||||
border: 1px solid rgba(128, 128, 128, 0.2);
|
||||
border-radius: 12px;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.dc-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 10px;
|
||||
|
||||
.dc-title {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.dc-badge {
|
||||
font-size: 11.5px;
|
||||
color: #18a058;
|
||||
background: rgba(24, 160, 88, 0.1);
|
||||
border-radius: 999px;
|
||||
padding: 2px 12px;
|
||||
}
|
||||
|
||||
.dc-count {
|
||||
margin-left: auto;
|
||||
font-size: 12px;
|
||||
opacity: 0.55;
|
||||
}
|
||||
}
|
||||
|
||||
.dc-card {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
// ---- mode row ----
|
||||
.dc-moderow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.dc-modelabels {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
|
||||
span {
|
||||
opacity: 0.45;
|
||||
|
||||
&.on {
|
||||
opacity: 1;
|
||||
font-weight: 600;
|
||||
color: #18a058;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.dc-switch {
|
||||
margin-left: auto;
|
||||
width: 44px;
|
||||
height: 24px;
|
||||
border-radius: 999px;
|
||||
border: none;
|
||||
background: rgba(128, 128, 128, 0.35);
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
|
||||
&.on {
|
||||
background: #18a058;
|
||||
}
|
||||
|
||||
.dc-knob {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
left: 3px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
transition: left 0.2s;
|
||||
}
|
||||
|
||||
&.on .dc-knob {
|
||||
left: 23px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- upload ----
|
||||
.dc-upload {
|
||||
flex-shrink: 0;
|
||||
min-height: 150px;
|
||||
border: 2px dashed rgba(128, 128, 128, 0.4);
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s;
|
||||
box-sizing: border-box;
|
||||
|
||||
&:hover,
|
||||
&.active {
|
||||
border-color: #18a058;
|
||||
}
|
||||
|
||||
&.has {
|
||||
cursor: default;
|
||||
justify-content: flex-start;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.dc-upload-icon {
|
||||
font-size: 34px;
|
||||
}
|
||||
|
||||
.dc-upload-big {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.dc-upload-sub {
|
||||
font-size: 12px;
|
||||
opacity: 0.55;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.dc-files {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
|
||||
.dc-file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: rgba(24, 160, 88, 0.06);
|
||||
border-radius: 7px;
|
||||
padding: 6px 12px;
|
||||
|
||||
.dc-file-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.dc-file-size {
|
||||
font-size: 12px;
|
||||
opacity: 0.55;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.dc-file-del {
|
||||
color: #999;
|
||||
text-decoration: none;
|
||||
font-size: 12px;
|
||||
|
||||
&:hover {
|
||||
color: #d03050;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.dc-add-more {
|
||||
align-self: flex-start;
|
||||
color: #18a058;
|
||||
text-decoration: none;
|
||||
font-size: 12.5px;
|
||||
padding: 2px 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- formats ----
|
||||
.dc-fmts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.dc-fmt-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
|
||||
.dc-fmt-label {
|
||||
flex-shrink: 0;
|
||||
width: 46px;
|
||||
font-size: 13px;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.dc-fmt-btns {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.dc-fmt {
|
||||
border: 1px solid rgba(128, 128, 128, 0.35);
|
||||
background: #fff;
|
||||
border-radius: 7px;
|
||||
padding: 6px 16px;
|
||||
font-size: 13px;
|
||||
color: #444;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
|
||||
.dc-ext {
|
||||
font-size: 11px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
&.on {
|
||||
background: #18a058;
|
||||
border-color: #18a058;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
|
||||
.dc-ext {
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
&:not(.on):hover {
|
||||
border-color: #18a058;
|
||||
color: #18a058;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.dc-status {
|
||||
flex-shrink: 0;
|
||||
font-size: 12.5px;
|
||||
color: #18a058;
|
||||
}
|
||||
|
||||
.dc-error {
|
||||
flex-shrink: 0;
|
||||
font-size: 12.5px;
|
||||
color: #d03050;
|
||||
}
|
||||
|
||||
// ---- bottom ----
|
||||
.dc-bottom {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 12px;
|
||||
padding-top: 4px;
|
||||
|
||||
.dc-actions {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
|
||||
.dc-exec {
|
||||
background: #18a058 !important;
|
||||
color: #fff;
|
||||
min-width: 110px;
|
||||
font-weight: 600;
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { FileExport } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.doc-convert.title'),
|
||||
path: '/doc-convert',
|
||||
description: translate('tools.doc-convert.description'),
|
||||
keywords: ['doc', 'convert', 'pdf', 'docx', 'epub', 'mobi', 'azw3', 'word', '文档', '转换', '格式', '电子书'],
|
||||
component: () => import('./doc-convert.vue'),
|
||||
icon: FileExport,
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
declare module 'composerize' {
|
||||
const composerize: (arg: string) => string;
|
||||
export default composerize;
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
<script setup lang="ts">
|
||||
import { MessageType, composerize } from 'composerize-ts';
|
||||
import { withDefaultOnError } from '@/utils/defaults';
|
||||
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';
|
||||
import { textToBase64 } from '@/utils/base64';
|
||||
import TextareaCopyable from '@/components/TextareaCopyable.vue';
|
||||
|
||||
const dockerRun = ref(
|
||||
'docker run -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro --restart always --log-opt max-size=1g nginx',
|
||||
);
|
||||
|
||||
const conversionResult = computed(() =>
|
||||
withDefaultOnError(() => composerize(dockerRun.value.trim()), { yaml: '', messages: [] }),
|
||||
);
|
||||
const dockerCompose = computed(() => conversionResult.value.yaml);
|
||||
const notImplemented = computed(() =>
|
||||
conversionResult.value.messages.filter(msg => msg.type === MessageType.notImplemented).map(msg => msg.value),
|
||||
);
|
||||
const notComposable = computed(() =>
|
||||
conversionResult.value.messages.filter(msg => msg.type === MessageType.notTranslatable).map(msg => msg.value),
|
||||
);
|
||||
const errors = computed(() =>
|
||||
conversionResult.value.messages
|
||||
.filter(msg => msg.type === MessageType.errorDuringConversion)
|
||||
.map(msg => msg.value),
|
||||
);
|
||||
const dockerComposeBase64 = computed(() => `data:application/yaml;base64,${textToBase64(dockerCompose.value)}`);
|
||||
const { download } = useDownloadFileFromBase64({ source: dockerComposeBase64, filename: 'docker-compose.yml' });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-input-text
|
||||
v-model:value="dockerRun"
|
||||
label="Your docker run command:"
|
||||
style="font-family: monospace"
|
||||
multiline
|
||||
raw-text
|
||||
monospace
|
||||
placeholder="Your docker run command to convert..."
|
||||
rows="3"
|
||||
/>
|
||||
|
||||
<n-divider />
|
||||
|
||||
<TextareaCopyable :value="dockerCompose" language="yaml" />
|
||||
|
||||
<div mt-5 flex justify-center>
|
||||
<c-button :disabled="dockerCompose === ''" secondary @click="download">
|
||||
Download docker-compose.yml
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<div v-if="notComposable.length > 0">
|
||||
<n-alert title="This options are not translatable to docker-compose" type="info" mt-5>
|
||||
<ul>
|
||||
<li v-for="(message, index) of notComposable" :key="index">
|
||||
{{ message }}
|
||||
</li>
|
||||
</ul>
|
||||
</n-alert>
|
||||
</div>
|
||||
|
||||
<div v-if="notImplemented.length > 0">
|
||||
<n-alert
|
||||
title="This options are not yet implemented and therefore haven't been translated to docker-compose"
|
||||
type="warning"
|
||||
mt-5
|
||||
>
|
||||
<ul>
|
||||
<li v-for="(message, index) of notImplemented" :key="index">
|
||||
{{ message }}
|
||||
</li>
|
||||
</ul>
|
||||
</n-alert>
|
||||
</div>
|
||||
|
||||
<div v-if="errors.length > 0">
|
||||
<n-alert title="The following errors occured" type="error" mt-5>
|
||||
<ul>
|
||||
<li v-for="(message, index) of errors" :key="index">
|
||||
{{ message }}
|
||||
</li>
|
||||
</ul>
|
||||
</n-alert>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { BrandDocker } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.docker-run-to-docker-compose-converter.title'),
|
||||
path: '/docker-run-to-docker-compose-converter',
|
||||
description: translate('tools.docker-run-to-docker-compose-converter.description'),
|
||||
keywords: ['docker', 'run', 'compose', 'yaml', 'yml', 'convert', 'deamon'],
|
||||
component: () => import('./docker-run-to-docker-compose-converter.vue'),
|
||||
icon: BrandDocker,
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
<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>
|
||||
@@ -0,0 +1,12 @@
|
||||
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'),
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
import type { EmojiInfo } from './emoji.types';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
|
||||
const props = (defineProps<{ emojiInfo: EmojiInfo }>());
|
||||
const { emojiInfo } = toRefs(props);
|
||||
|
||||
const { copy } = useCopy();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card flex items-center gap-3 important:py-8px important:pl-10px important:pr-5px>
|
||||
<div cursor-pointer text-30px @click="copy(emojiInfo.emoji, { notificationMessage: `Emoji ${emojiInfo.emoji} copied to the clipboard` })">
|
||||
{{ emojiInfo.emoji }}
|
||||
</div>
|
||||
|
||||
<div min-w-0 flex-1>
|
||||
<div truncate font-bold>
|
||||
{{ emojiInfo.title }}
|
||||
</div>
|
||||
|
||||
<!-- <div>
|
||||
<c-link>
|
||||
{{ emojiInfo.codePoints }}
|
||||
</c-link>
|
||||
</div>
|
||||
<div />
|
||||
<div rounded op-70>
|
||||
Unicode: <span border="1px solid current op-30" b-rd-xl px-12px py-4px>{{ emojiInfo.unicode }}</span>
|
||||
</div> -->
|
||||
|
||||
<div flex gap-2 text-xs font-mono op-70>
|
||||
<span cursor-pointer transition hover:text-primary @click="copy(emojiInfo.codePoints, { notificationMessage: `Code points '${emojiInfo.codePoints}' copied to the clipboard` })">
|
||||
{{ emojiInfo.codePoints }}
|
||||
</span>
|
||||
<span cursor-pointer truncate transition hover:text-primary @click="copy(emojiInfo.unicode, { notificationMessage: `Unicode '${emojiInfo.unicode}' copied to the clipboard` })">
|
||||
{{ emojiInfo.unicode }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</c-card>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import type { EmojiInfo } from './emoji.types';
|
||||
|
||||
const props = withDefaults(defineProps<{ emojiInfos?: EmojiInfo[] }>(), { emojiInfos: () => [] });
|
||||
const { emojiInfos } = toRefs(props);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div grid grid-cols-1 gap-2 lg:grid-cols-4 md:grid-cols-3 sm:grid-cols-2 xl:grid-cols-6>
|
||||
<emoji-card v-for="emojiInfo in emojiInfos" :key="emojiInfo.name" :emoji-info="emojiInfo" flex items-center gap-3 />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
import emojiUnicodeData from 'unicode-emoji-json';
|
||||
import emojiKeywords from 'emojilib';
|
||||
import _ from 'lodash';
|
||||
import type { EmojiInfo } from './emoji.types';
|
||||
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 getEmojiCodePoints = ({ emoji }: { emoji: string }) => emoji.codePointAt(0) ? `0x${emoji.codePointAt(0)?.toString(16)}` : undefined;
|
||||
|
||||
const emojis = _.map(emojiUnicodeData, (emojiInfo, emoji) => ({
|
||||
...emojiInfo,
|
||||
emoji,
|
||||
title: _.capitalize(emojiInfo.name),
|
||||
keywords: emojiKeywords[emoji as keyof typeof emojiKeywords],
|
||||
codePoints: getEmojiCodePoints({ emoji }),
|
||||
unicode: escapeUnicode({ emoji }),
|
||||
}));
|
||||
|
||||
const emojisGroups: { emojiInfos: EmojiInfo[]; group: string }[] = _
|
||||
.chain(emojis)
|
||||
.groupBy('group')
|
||||
.map((emojiInfos, group) => ({ group, emojiInfos }))
|
||||
.value();
|
||||
|
||||
const searchQuery = useDebouncedRef('', 500);
|
||||
|
||||
const { searchResult } = useFuzzySearch({
|
||||
search: searchQuery,
|
||||
data: emojis,
|
||||
options: {
|
||||
keys: ['group', { name: 'name', weight: 3 }, 'keywords', 'unicode', 'codePoints', 'emoji'],
|
||||
threshold: 0.3,
|
||||
useExtendedSearch: true,
|
||||
isCaseSensitive: false,
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div mx-auto max-w-2400px important:flex-1>
|
||||
<div flex items-center gap-3>
|
||||
<c-input-text
|
||||
v-model:value="searchQuery"
|
||||
placeholder="Search emojis (e.g. 'smile')..."
|
||||
mx-auto max-w-600px
|
||||
>
|
||||
<template #prefix>
|
||||
<icon-mdi-search mr-6px color-black op-70 dark:color-white />
|
||||
</template>
|
||||
</c-input-text>
|
||||
</div>
|
||||
|
||||
<div v-if="searchQuery.trim().length > 0">
|
||||
<div
|
||||
v-if="searchResult.length === 0"
|
||||
mt-4
|
||||
text-20px
|
||||
font-bold
|
||||
>
|
||||
No results
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div mt-4 text-20px font-bold>
|
||||
Search result
|
||||
</div>
|
||||
|
||||
<emoji-grid :emoji-infos="searchResult" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="{ group, emojiInfos } in emojisGroups"
|
||||
v-else
|
||||
:key="group"
|
||||
>
|
||||
<div mt-4 text-20px font-bold>
|
||||
{{ group }}
|
||||
</div>
|
||||
|
||||
<emoji-grid :emoji-infos="emojiInfos" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,8 @@
|
||||
import type emojiUnicodeData from 'unicode-emoji-json';
|
||||
|
||||
export type EmojiInfo = {
|
||||
title: string
|
||||
emoji: string
|
||||
codePoints: string | undefined
|
||||
unicode: string
|
||||
} & typeof emojiUnicodeData[string];
|
||||
@@ -0,0 +1,13 @@
|
||||
import { MoodSmile } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.emoji-picker.title'),
|
||||
path: '/emoji-picker',
|
||||
description: translate('tools.emoji-picker.description'),
|
||||
keywords: ['emoji', 'picker', 'unicode', 'copy', 'paste'],
|
||||
component: () => import('./emoji-picker.vue'),
|
||||
icon: MoodSmile,
|
||||
createdAt: new Date('2023-08-07'),
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup lang="ts">
|
||||
import { AES, RC4, Rabbit, TripleDES, enc } from 'crypto-js';
|
||||
import { computedCatch } from '@/composable/computed/catchedComputed';
|
||||
|
||||
const algos = { AES, TripleDES, Rabbit, RC4 };
|
||||
|
||||
const cypherInput = ref('Lorem ipsum dolor sit amet');
|
||||
const cypherAlgo = ref<keyof typeof algos>('AES');
|
||||
const cypherSecret = ref('my secret key');
|
||||
const cypherOutput = computed(() => algos[cypherAlgo.value].encrypt(cypherInput.value, cypherSecret.value).toString());
|
||||
|
||||
const decryptInput = ref('U2FsdGVkX1/EC3+6P5dbbkZ3e1kQ5o2yzuU0NHTjmrKnLBEwreV489Kr0DIB+uBs');
|
||||
const decryptAlgo = ref<keyof typeof algos>('AES');
|
||||
const decryptSecret = ref('my secret key');
|
||||
const [decryptOutput, decryptError] = computedCatch(() => algos[decryptAlgo.value].decrypt(decryptInput.value, decryptSecret.value).toString(enc.Utf8), {
|
||||
defaultValue: '',
|
||||
defaultErrorMessage: 'Unable to decrypt your text',
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card title="Encrypt">
|
||||
<div flex gap-3>
|
||||
<c-input-text
|
||||
v-model:value="cypherInput"
|
||||
label="Your text:"
|
||||
placeholder="The string to cypher"
|
||||
rows="4"
|
||||
multiline raw-text monospace autosize flex-1
|
||||
/>
|
||||
<div flex flex-1 flex-col gap-2>
|
||||
<c-input-text v-model:value="cypherSecret" label="Your secret key:" clearable raw-text />
|
||||
|
||||
<c-select
|
||||
v-model:value="cypherAlgo"
|
||||
label="Encryption algorithm:"
|
||||
:options="Object.keys(algos).map((label) => ({ label, value: label }))"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<c-input-text
|
||||
label="Your text encrypted:"
|
||||
:value="cypherOutput"
|
||||
rows="3"
|
||||
placeholder="Your string hash"
|
||||
multiline monospace readonly autosize mt-5
|
||||
/>
|
||||
</c-card>
|
||||
<c-card title="Decrypt">
|
||||
<div flex gap-3>
|
||||
<c-input-text
|
||||
v-model:value="decryptInput"
|
||||
label="Your encrypted text:"
|
||||
placeholder="The string to cypher"
|
||||
rows="4"
|
||||
multiline raw-text monospace autosize flex-1
|
||||
/>
|
||||
<div flex flex-1 flex-col gap-2>
|
||||
<c-input-text v-model:value="decryptSecret" label="Your secret key:" clearable raw-text />
|
||||
|
||||
<c-select
|
||||
v-model:value="decryptAlgo"
|
||||
label="Encryption algorithm:"
|
||||
:options="Object.keys(algos).map((label) => ({ label, value: label }))"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<c-alert v-if="decryptError" type="error" mt-12 title="Error while decrypting">
|
||||
{{ decryptError }}
|
||||
</c-alert>
|
||||
<c-input-text
|
||||
v-else
|
||||
label="Your decrypted text:"
|
||||
:value="decryptOutput"
|
||||
placeholder="Your string hash"
|
||||
rows="3"
|
||||
multiline monospace readonly autosize mt-5
|
||||
/>
|
||||
</c-card>
|
||||
</template>
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Lock } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.encryption.title'),
|
||||
path: '/encryption',
|
||||
description: translate('tools.encryption.description'),
|
||||
keywords: ['cypher', 'encipher', 'text', 'AES', 'TripleDES', 'Rabbit', 'RC4'],
|
||||
component: () => import('./encryption.vue'),
|
||||
icon: Lock,
|
||||
redirectFrom: ['/cypher'],
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { formatDuration } from 'date-fns';
|
||||
|
||||
export function formatMsDuration(duration: number) {
|
||||
const ms = Math.floor(duration % 1000);
|
||||
const secs = Math.floor(((duration - ms) / 1000) % 60);
|
||||
const mins = Math.floor((((duration - ms) / 1000 - secs) / 60) % 60);
|
||||
const hrs = Math.floor((((duration - ms) / 1000 - secs) / 60 - mins) / 60);
|
||||
|
||||
return (
|
||||
formatDuration({
|
||||
hours: hrs,
|
||||
minutes: mins,
|
||||
seconds: secs,
|
||||
}) + (ms > 0 ? ` ${ms} ms` : '')
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<script setup lang="ts">
|
||||
// Duplicate issue with sub directory
|
||||
|
||||
import { addMilliseconds, formatRelative } from 'date-fns';
|
||||
|
||||
import { enGB } from 'date-fns/locale';
|
||||
|
||||
import { formatMsDuration } from './eta-calculator.service';
|
||||
|
||||
const unitCount = ref(3 * 62);
|
||||
const unitPerTimeSpan = ref(3);
|
||||
const timeSpan = ref(5);
|
||||
const timeSpanUnitMultiplier = ref(60000);
|
||||
const startedAt = ref(Date.now());
|
||||
|
||||
const durationMs = computed(() => {
|
||||
const timeSpanMs = timeSpan.value * timeSpanUnitMultiplier.value;
|
||||
|
||||
return unitCount.value / (unitPerTimeSpan.value / timeSpanMs);
|
||||
});
|
||||
const endAt = computed(() =>
|
||||
formatRelative(addMilliseconds(startedAt.value, durationMs.value), Date.now(), { locale: enGB }),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div text-justify op-70>
|
||||
With a concrete example, if you wash 5 plates in 3 minutes and you have 500 plates to wash, it will take you 5
|
||||
hours to wash them all.
|
||||
</div>
|
||||
<n-divider />
|
||||
<div flex gap-2>
|
||||
<n-form-item label="Amount of element to consume" flex-1>
|
||||
<n-input-number v-model:value="unitCount" :min="1" />
|
||||
</n-form-item>
|
||||
<n-form-item label="The consumption started at" flex-1>
|
||||
<n-date-picker v-model:value="startedAt" type="datetime" />
|
||||
</n-form-item>
|
||||
</div>
|
||||
|
||||
<p>Amount of unit consumed by time span</p>
|
||||
<div flex flex-col items-baseline gap-y-2 md:flex-row>
|
||||
<n-input-number v-model:value="unitPerTimeSpan" :min="1" />
|
||||
<div flex items-baseline gap-2>
|
||||
<span ml-2>in</span>
|
||||
<n-input-number v-model:value="timeSpan" min-w-130px :min="1" />
|
||||
<c-select
|
||||
v-model:value="timeSpanUnitMultiplier"
|
||||
min-w-130px
|
||||
:options="[
|
||||
{ label: 'milliseconds', value: 1 },
|
||||
{ label: 'seconds', value: 1000 },
|
||||
{ label: 'minutes', value: 1000 * 60 },
|
||||
{ label: 'hours', value: 1000 * 60 * 60 },
|
||||
{ label: 'days', value: 1000 * 60 * 60 * 24 },
|
||||
]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<n-divider />
|
||||
<c-card mb-2>
|
||||
<n-statistic label="Total duration">
|
||||
{{ formatMsDuration(durationMs) }}
|
||||
</n-statistic>
|
||||
</c-card>
|
||||
<c-card>
|
||||
<n-statistic label="It will end ">
|
||||
{{ endAt }}
|
||||
</n-statistic>
|
||||
</c-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.n-input-number,
|
||||
.n-date-picker {
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Hourglass } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.eta-calculator.title'),
|
||||
path: '/eta-calculator',
|
||||
description: translate('tools.eta-calculator.description'),
|
||||
keywords: ['eta', 'calculator', 'estimated', 'time', 'arrival', 'average'],
|
||||
component: () => import('./eta-calculator.vue'),
|
||||
icon: Hourglass,
|
||||
});
|
||||
@@ -0,0 +1,318 @@
|
||||
<script setup lang="ts">
|
||||
import { useGenHistory } from './gen-history';
|
||||
|
||||
const props = withDefaults(defineProps<{ tool: string; position?: 'bottom' | 'right'; label?: string }>(), {
|
||||
position: 'bottom',
|
||||
label: '生成记录',
|
||||
});
|
||||
|
||||
const { records, remove, clear } = useGenHistory(props.tool);
|
||||
const open = ref(false);
|
||||
const toast = ref('');
|
||||
|
||||
function fmt(t: number): string {
|
||||
const d = new Date(t);
|
||||
const p = (n: number) => String(n).padStart(2, '0');
|
||||
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function flash(m: string) {
|
||||
toast.value = m;
|
||||
setTimeout(() => (toast.value = ''), 1600);
|
||||
}
|
||||
|
||||
async function copyRecord(r: { title: string; detail?: string }) {
|
||||
const text = r.detail ? `${r.title}\n${r.detail}` : r.title;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
flash('已复制');
|
||||
}
|
||||
catch {
|
||||
flash('复制失败');
|
||||
}
|
||||
}
|
||||
|
||||
function onClear() {
|
||||
if (records.value.length && window.confirm('清空全部生成记录?')) {
|
||||
clear();
|
||||
open.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function onRemove(id: string) {
|
||||
remove(id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- bottom bar mode -->
|
||||
<div v-if="position === 'bottom'" class="gh-bar">
|
||||
<div v-if="open" class="gh-panel above">
|
||||
<div class="gh-head">
|
||||
<span class="gh-title">{{ label }}({{ records.length }})</span>
|
||||
<a href="javascript:;" class="gh-link" @click="onClear">清空</a>
|
||||
<a href="javascript:;" class="gh-link" @click="open = false">收起</a>
|
||||
</div>
|
||||
<div class="gh-list">
|
||||
<div v-if="!records.length" class="gh-empty">
|
||||
暂无记录
|
||||
</div>
|
||||
<div v-for="r in records" :key="r.id" class="gh-item">
|
||||
<div class="gh-item-main">
|
||||
<span class="gh-time">{{ fmt(r.time) }}</span>
|
||||
<span class="gh-item-title">{{ r.title }}</span>
|
||||
</div>
|
||||
<div v-if="r.detail" class="gh-item-detail">
|
||||
{{ r.detail }}
|
||||
</div>
|
||||
<div class="gh-ops">
|
||||
<a href="javascript:;" @click="copyRecord(r)">复制</a>
|
||||
<a href="javascript:;" class="del" @click="onRemove(r.id)">删除</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="javascript:;" class="gh-toggle" @click="open = !open">
|
||||
🕘 {{ label }}<template v-if="records.length">({{ records.length }})</template>
|
||||
<template v-if="records.length && !open"> · 最近:{{ records[0].title }}</template>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- right fab mode -->
|
||||
<template v-else>
|
||||
<a href="javascript:;" class="gh-fab" :title="label" @click="open = !open">
|
||||
🕘<span v-if="records.length" class="gh-badge">{{ records.length }}</span>
|
||||
</a>
|
||||
<div v-if="open" class="gh-panel side">
|
||||
<div class="gh-head">
|
||||
<span class="gh-title">{{ label }}({{ records.length }})</span>
|
||||
<a href="javascript:;" class="gh-link" @click="onClear">清空</a>
|
||||
<a href="javascript:;" class="gh-link" @click="open = false">✕</a>
|
||||
</div>
|
||||
<div class="gh-list">
|
||||
<div v-if="!records.length" class="gh-empty">
|
||||
暂无记录
|
||||
</div>
|
||||
<div v-for="r in records" :key="r.id" class="gh-item">
|
||||
<div class="gh-item-main">
|
||||
<span class="gh-time">{{ fmt(r.time) }}</span>
|
||||
<span class="gh-item-title">{{ r.title }}</span>
|
||||
</div>
|
||||
<div v-if="r.detail" class="gh-item-detail">
|
||||
{{ r.detail }}
|
||||
</div>
|
||||
<div class="gh-ops">
|
||||
<a href="javascript:;" @click="copyRecord(r)">复制</a>
|
||||
<a href="javascript:;" class="del" @click="onRemove(r.id)">删除</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="toast" class="gh-toast">
|
||||
{{ toast }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.gh-bar {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
padding-top: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.gh-toggle {
|
||||
color: #888;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
|
||||
&:hover {
|
||||
color: #18a058;
|
||||
}
|
||||
}
|
||||
|
||||
.gh-panel {
|
||||
position: absolute;
|
||||
background: #fff;
|
||||
border: 1px solid rgba(128, 128, 128, 0.3);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
|
||||
z-index: 9990;
|
||||
width: 420px;
|
||||
max-width: calc(100vw - 40px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 320px;
|
||||
|
||||
&.above {
|
||||
bottom: calc(100% + 4px);
|
||||
left: 0;
|
||||
}
|
||||
|
||||
&.side {
|
||||
position: fixed;
|
||||
right: 16px;
|
||||
bottom: 60px;
|
||||
}
|
||||
|
||||
.gh-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 9px 12px;
|
||||
border-bottom: 1px solid rgba(128, 128, 128, 0.15);
|
||||
flex-shrink: 0;
|
||||
|
||||
.gh-title {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.gh-link {
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: #18a058;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.gh-list {
|
||||
overflow-y: auto;
|
||||
padding: 6px;
|
||||
|
||||
.gh-empty {
|
||||
opacity: 0.45;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.gh-item {
|
||||
padding: 7px 8px;
|
||||
border-radius: 7px;
|
||||
position: relative;
|
||||
|
||||
&:hover {
|
||||
background: rgba(24, 160, 88, 0.06);
|
||||
|
||||
.gh-ops {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.gh-item-main {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: baseline;
|
||||
|
||||
.gh-time {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
color: #999;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.gh-item-title {
|
||||
font-size: 12.5px;
|
||||
color: #333;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.gh-item-detail {
|
||||
font-size: 11.5px;
|
||||
color: #888;
|
||||
margin-top: 2px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
padding-left: 62px;
|
||||
}
|
||||
|
||||
.gh-ops {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
top: 6px;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s;
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
border-radius: 5px;
|
||||
padding: 1px 6px;
|
||||
|
||||
a {
|
||||
font-size: 11.5px;
|
||||
color: #888;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: #18a058;
|
||||
}
|
||||
|
||||
&.del:hover {
|
||||
color: #d03050;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.gh-fab {
|
||||
position: fixed;
|
||||
right: 14px;
|
||||
bottom: 70px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background: rgba(30, 30, 30, 0.85);
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 17px;
|
||||
text-decoration: none;
|
||||
z-index: 9990;
|
||||
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.3);
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: #18a058;
|
||||
}
|
||||
|
||||
.gh-badge {
|
||||
position: absolute;
|
||||
top: -4px;
|
||||
right: -4px;
|
||||
background: #d03050;
|
||||
color: #fff;
|
||||
font-size: 10.5px;
|
||||
border-radius: 999px;
|
||||
padding: 1px 5px;
|
||||
font-style: normal;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.gh-toast {
|
||||
position: fixed;
|
||||
right: 20px;
|
||||
bottom: 20px;
|
||||
background: rgba(30, 30, 30, 0.9);
|
||||
color: #fff;
|
||||
font-size: 12.5px;
|
||||
border-radius: 8px;
|
||||
padding: 8px 16px;
|
||||
z-index: 10000;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,59 @@
|
||||
import { ref } from 'vue';
|
||||
|
||||
export interface GenRecord {
|
||||
id: string;
|
||||
time: number;
|
||||
title: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
const MAX = 50;
|
||||
const LS = (tool: string) => `it-tools-gen-history:${tool}`;
|
||||
|
||||
function load(tool: string): GenRecord[] {
|
||||
try {
|
||||
const arr = JSON.parse(localStorage.getItem(LS(tool)) ?? '[]');
|
||||
return Array.isArray(arr) ? arr : [];
|
||||
}
|
||||
catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** shared per-tool store so page components and the GenHistory UI stay in sync */
|
||||
const stores = new Map<string, Ref<GenRecord[]>>();
|
||||
|
||||
/** Per-tool generation history persisted in the user's browser (localStorage). */
|
||||
export function useGenHistory(tool: string) {
|
||||
if (!stores.has(tool)) {
|
||||
stores.set(tool, ref<GenRecord[]>(load(tool)));
|
||||
}
|
||||
const records = stores.get(tool)!;
|
||||
|
||||
function save() {
|
||||
try {
|
||||
localStorage.setItem(LS(tool), JSON.stringify(records.value.slice(0, MAX)));
|
||||
}
|
||||
catch { /* quota */ }
|
||||
}
|
||||
|
||||
/** add a record; dedupeTitle=true replaces an existing record with the same title */
|
||||
function add(r: { title: string; detail?: string; dedupeTitle?: boolean }) {
|
||||
const id = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
const rest = r.dedupeTitle ? records.value.filter(x => x.title !== r.title) : records.value;
|
||||
records.value = [{ id, time: Date.now(), title: r.title, detail: r.detail }, ...rest].slice(0, MAX);
|
||||
save();
|
||||
}
|
||||
|
||||
function remove(id: string) {
|
||||
records.value = records.value.filter(x => x.id !== id);
|
||||
save();
|
||||
}
|
||||
|
||||
function clear() {
|
||||
records.value = [];
|
||||
save();
|
||||
}
|
||||
|
||||
return { records, add, remove, clear };
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
## Configuration
|
||||
|
||||
Set the global config
|
||||
|
||||
```shell
|
||||
git config --global user.name "[name]"
|
||||
git config --global user.email "[email]"
|
||||
```
|
||||
|
||||
## Get started
|
||||
|
||||
Create a git repository
|
||||
|
||||
```shell
|
||||
git init
|
||||
```
|
||||
|
||||
Clone an existing git repository
|
||||
|
||||
```shell
|
||||
git clone [url]
|
||||
```
|
||||
|
||||
## Commit
|
||||
|
||||
Commit all tracked changes
|
||||
|
||||
```shell
|
||||
git commit -am "[commit message]"
|
||||
```
|
||||
|
||||
Add new modifications to the last commit
|
||||
|
||||
```shell
|
||||
git commit --amend --no-edit
|
||||
```
|
||||
|
||||
## I’ve made a mistake
|
||||
|
||||
Change last commit message
|
||||
|
||||
```shell
|
||||
git commit --amend
|
||||
```
|
||||
|
||||
Undo most recent commit and keep changes
|
||||
|
||||
```shell
|
||||
git reset HEAD~1
|
||||
```
|
||||
|
||||
Undo the `N` most recent commit and keep changes
|
||||
|
||||
```shell
|
||||
git reset HEAD~N
|
||||
```
|
||||
|
||||
Undo most recent commit and get rid of changes
|
||||
|
||||
```shell
|
||||
git reset HEAD~1 --hard
|
||||
```
|
||||
|
||||
Reset branch to remote state
|
||||
|
||||
```shell
|
||||
git fetch origin
|
||||
git reset --hard origin/[branch-name]
|
||||
```
|
||||
|
||||
## Miscellaneous
|
||||
|
||||
Renaming the local master branch to main
|
||||
|
||||
```shell
|
||||
git branch -m master main
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { useThemeVars } from 'naive-ui';
|
||||
import Memo from './git-memo.content.md';
|
||||
|
||||
const themeVars = useThemeVars();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Memo />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
::v-deep(pre) {
|
||||
margin: 0;
|
||||
padding: 15px 22px;
|
||||
background-color: v-bind('themeVars.cardColor');
|
||||
border-radius: 4px;
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { BrandGit } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.git-memo.title'),
|
||||
path: '/git-memo',
|
||||
description: translate('tools.git-memo.description'),
|
||||
keywords: ['git', 'push', 'force', 'pull', 'commit', 'amend', 'rebase', 'merge', 'reset', 'soft', 'hard', 'lease'],
|
||||
component: () => import('./git-memo.vue'),
|
||||
icon: BrandGit,
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { convertHexToBin } from './hash-text.service';
|
||||
|
||||
describe('hash text', () => {
|
||||
describe('convertHexToBin', () => {
|
||||
it('convert hex to bin', () => {
|
||||
expect(convertHexToBin('')).toEqual('');
|
||||
expect(convertHexToBin('FF')).toEqual('11111111');
|
||||
expect(convertHexToBin('F'.repeat(200))).toEqual('1111'.repeat(200));
|
||||
expect(convertHexToBin('2123006AD00F694CE120')).toEqual(
|
||||
'00100001001000110000000001101010110100000000111101101001010011001110000100100000',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
export function convertHexToBin(hex: string) {
|
||||
return hex
|
||||
.trim()
|
||||
.split('')
|
||||
.map(byte => Number.parseInt(byte, 16).toString(2).padStart(4, '0'))
|
||||
.join('');
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<script setup lang="ts">
|
||||
import type { lib } from 'crypto-js';
|
||||
import { MD5, RIPEMD160, SHA1, SHA224, SHA256, SHA3, SHA384, SHA512, enc } from 'crypto-js';
|
||||
|
||||
import InputCopyable from '../../components/InputCopyable.vue';
|
||||
import { convertHexToBin } from './hash-text.service';
|
||||
import { useQueryParam } from '@/composable/queryParams';
|
||||
|
||||
const algos = {
|
||||
MD5,
|
||||
SHA1,
|
||||
SHA256,
|
||||
SHA224,
|
||||
SHA512,
|
||||
SHA384,
|
||||
SHA3,
|
||||
RIPEMD160,
|
||||
} as const;
|
||||
|
||||
type AlgoNames = keyof typeof algos;
|
||||
type Encoding = keyof typeof enc | 'Bin';
|
||||
const algoNames = Object.keys(algos) as AlgoNames[];
|
||||
const encoding = useQueryParam<Encoding>({ defaultValue: 'Hex', name: 'encoding' });
|
||||
const clearText = ref('');
|
||||
|
||||
function formatWithEncoding(words: lib.WordArray, encoding: Encoding) {
|
||||
if (encoding === 'Bin') {
|
||||
return convertHexToBin(words.toString(enc.Hex));
|
||||
}
|
||||
|
||||
return words.toString(enc[encoding]);
|
||||
}
|
||||
|
||||
const hashText = (algo: AlgoNames, value: string) => formatWithEncoding(algos[algo](value), encoding.value);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-card>
|
||||
<c-input-text v-model:value="clearText" multiline raw-text placeholder="Your string to hash..." rows="3" autosize autofocus label="Your text to hash:" />
|
||||
|
||||
<n-divider />
|
||||
|
||||
<c-select
|
||||
v-model:value="encoding"
|
||||
mb-4
|
||||
label="Digest encoding"
|
||||
:options="[
|
||||
{
|
||||
label: 'Binary (base 2)',
|
||||
value: 'Bin',
|
||||
},
|
||||
{
|
||||
label: 'Hexadecimal (base 16)',
|
||||
value: 'Hex',
|
||||
},
|
||||
{
|
||||
label: 'Base64 (base 64)',
|
||||
value: 'Base64',
|
||||
},
|
||||
{
|
||||
label: 'Base64url (base 64 with url safe chars)',
|
||||
value: 'Base64url',
|
||||
},
|
||||
]"
|
||||
/>
|
||||
|
||||
<div v-for="algo in algoNames" :key="algo" style="margin: 5px 0">
|
||||
<n-input-group>
|
||||
<n-input-group-label style="flex: 0 0 120px">
|
||||
{{ algo }}
|
||||
</n-input-group-label>
|
||||
<InputCopyable :value="hashText(algo, clearText)" readonly />
|
||||
</n-input-group>
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,27 @@
|
||||
import { EyeOff } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.hash-text.title'),
|
||||
path: '/hash-text',
|
||||
description: translate('tools.hash-text.description'),
|
||||
keywords: [
|
||||
'hash',
|
||||
'digest',
|
||||
'crypto',
|
||||
'security',
|
||||
'text',
|
||||
'MD5',
|
||||
'SHA1',
|
||||
'SHA256',
|
||||
'SHA224',
|
||||
'SHA512',
|
||||
'SHA384',
|
||||
'SHA3',
|
||||
'RIPEMD160',
|
||||
],
|
||||
component: () => import('./hash-text.vue'),
|
||||
icon: EyeOff,
|
||||
redirectFrom: ['/hash'],
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
<script setup lang="ts">
|
||||
import type { lib } from 'crypto-js';
|
||||
import {
|
||||
HmacMD5,
|
||||
HmacRIPEMD160,
|
||||
HmacSHA1,
|
||||
HmacSHA224,
|
||||
HmacSHA256,
|
||||
HmacSHA3,
|
||||
HmacSHA384,
|
||||
HmacSHA512,
|
||||
enc,
|
||||
} from 'crypto-js';
|
||||
|
||||
import { convertHexToBin } from '../hash-text/hash-text.service';
|
||||
import { useCopy } from '@/composable/copy';
|
||||
|
||||
const algos = {
|
||||
MD5: HmacMD5,
|
||||
RIPEMD160: HmacRIPEMD160,
|
||||
SHA1: HmacSHA1,
|
||||
SHA3: HmacSHA3,
|
||||
SHA224: HmacSHA224,
|
||||
SHA256: HmacSHA256,
|
||||
SHA384: HmacSHA384,
|
||||
SHA512: HmacSHA512,
|
||||
} as const;
|
||||
|
||||
type Encoding = keyof typeof enc | 'Bin';
|
||||
|
||||
function formatWithEncoding(words: lib.WordArray, encoding: Encoding) {
|
||||
if (encoding === 'Bin') {
|
||||
return convertHexToBin(words.toString(enc.Hex));
|
||||
}
|
||||
return words.toString(enc[encoding]);
|
||||
}
|
||||
|
||||
const plainText = ref('');
|
||||
const secret = ref('');
|
||||
const hashFunction = ref<keyof typeof algos>('SHA256');
|
||||
const encoding = ref<Encoding>('Hex');
|
||||
const hmac = computed(() =>
|
||||
formatWithEncoding(algos[hashFunction.value](plainText.value, secret.value), encoding.value),
|
||||
);
|
||||
const { copy } = useCopy({ source: hmac });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div flex flex-col gap-4>
|
||||
<c-input-text v-model:value="plainText" multiline raw-text placeholder="Plain text to compute the hash..." rows="3" autosize autofocus label="Plain text to compute the hash" />
|
||||
<c-input-text v-model:value="secret" raw-text placeholder="Enter the secret key..." label="Secret key" clearable />
|
||||
|
||||
<div flex gap-2>
|
||||
<c-select
|
||||
v-model:value="hashFunction" label="Hashing function"
|
||||
flex-1
|
||||
placeholder="Select an hashing function..."
|
||||
:options="Object.keys(algos).map((label) => ({ label, value: label }))"
|
||||
/>
|
||||
<c-select
|
||||
v-model:value="encoding" label="Output encoding"
|
||||
flex-1
|
||||
placeholder="Select the result encoding..."
|
||||
:options="[
|
||||
{
|
||||
label: 'Binary (base 2)',
|
||||
value: 'Bin',
|
||||
},
|
||||
{
|
||||
label: 'Hexadecimal (base 16)',
|
||||
value: 'Hex',
|
||||
},
|
||||
{
|
||||
label: 'Base64 (base 64)',
|
||||
value: 'Base64',
|
||||
},
|
||||
{
|
||||
label: 'Base64-url (base 64 with url safe chars)',
|
||||
value: 'Base64url',
|
||||
},
|
||||
]"
|
||||
/>
|
||||
</div>
|
||||
<input-copyable v-model:value="hmac" type="textarea" placeholder="The result of the HMAC..." label="HMAC of your text" />
|
||||
<div flex justify-center>
|
||||
<c-button @click="copy()">
|
||||
Copy HMAC
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ShortTextRound } from '@vicons/material';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.hmac-generator.title'),
|
||||
path: '/hmac-generator',
|
||||
description: translate('tools.hmac-generator.description'),
|
||||
keywords: ['hmac', 'generator', 'MD5', 'SHA1', 'SHA256', 'SHA224', 'SHA512', 'SHA384', 'SHA3', 'RIPEMD160'],
|
||||
component: () => import('./hmac-generator.vue'),
|
||||
icon: ShortTextRound,
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
import { escape, unescape } from 'lodash';
|
||||
|
||||
import { useCopy } from '@/composable/copy';
|
||||
|
||||
const escapeInput = ref('<title>IT Tool</title>');
|
||||
const escapeOutput = computed(() => escape(escapeInput.value));
|
||||
const { copy: copyEscaped } = useCopy({ source: escapeOutput });
|
||||
|
||||
const unescapeInput = ref('<title>IT Tool</title>');
|
||||
const unescapeOutput = computed(() => unescape(unescapeInput.value));
|
||||
const { copy: copyUnescaped } = useCopy({ source: unescapeOutput });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card title="Escape html entities">
|
||||
<n-form-item label="Your string :">
|
||||
<c-input-text
|
||||
v-model:value="escapeInput"
|
||||
multiline
|
||||
placeholder="The string to escape"
|
||||
rows="3"
|
||||
autosize
|
||||
raw-text
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
<n-form-item label="Your string escaped :">
|
||||
<c-input-text
|
||||
multiline
|
||||
readonly
|
||||
placeholder="Your string escaped"
|
||||
:value="escapeOutput"
|
||||
rows="3"
|
||||
autosize
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
<div flex justify-center>
|
||||
<c-button @click="copyEscaped()">
|
||||
Copy
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
<c-card title="Unescape html entities">
|
||||
<n-form-item label="Your escaped string :">
|
||||
<c-input-text
|
||||
v-model:value="unescapeInput"
|
||||
multiline
|
||||
placeholder="The string to unescape"
|
||||
rows="3"
|
||||
autosize
|
||||
raw-text
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
<n-form-item label="Your string unescaped :">
|
||||
<c-input-text
|
||||
:value="unescapeOutput"
|
||||
multiline
|
||||
readonly
|
||||
placeholder="Your string unescaped"
|
||||
rows="3"
|
||||
autosize
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
<div flex justify-center>
|
||||
<c-button @click="copyUnescaped()">
|
||||
Copy
|
||||
</c-button>
|
||||
</div>
|
||||
</c-card>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Code } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.html-entities.title'),
|
||||
path: '/html-entities',
|
||||
description: translate('tools.html-entities.description'),
|
||||
keywords: ['html', 'entities', 'escape', 'unescape', 'special', 'characters', 'tags'],
|
||||
component: () => import('./html-entities.vue'),
|
||||
icon: Code,
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
<script setup lang="ts">
|
||||
import { tryOnBeforeUnmount, useVModel } from '@vueuse/core';
|
||||
import { Editor, EditorContent } from '@tiptap/vue-3';
|
||||
import StarterKit from '@tiptap/starter-kit';
|
||||
import { useThemeVars } from 'naive-ui';
|
||||
import MenuBar from './menu-bar.vue';
|
||||
|
||||
const props = defineProps<{ html: string }>();
|
||||
const emit = defineEmits(['update:html']);
|
||||
const themeVars = useThemeVars();
|
||||
const html = useVModel(props, 'html', emit);
|
||||
|
||||
const editor = new Editor({
|
||||
content: html.value,
|
||||
extensions: [StarterKit],
|
||||
});
|
||||
|
||||
editor.on('update', ({ editor }) => emit('update:html', editor.getHTML()));
|
||||
|
||||
tryOnBeforeUnmount(() => {
|
||||
editor.destroy();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card v-if="editor" important:p0>
|
||||
<MenuBar class="editor-header" :editor="editor" />
|
||||
<n-divider style="margin-top: 0" />
|
||||
|
||||
<div px8 pb6>
|
||||
<EditorContent class="editor-content" :editor="editor" />
|
||||
</div>
|
||||
</c-card>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
::v-deep(.ProseMirror-focused) {
|
||||
outline: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style scoped lang="less">
|
||||
::v-deep(.ProseMirror) {
|
||||
> * + * {
|
||||
margin-top: 0.75em;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
ul,
|
||||
ol {
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
code {
|
||||
background-color: v-bind('themeVars.codeColor');
|
||||
padding: 2px 4px;
|
||||
border-radius: 5px;
|
||||
font-size: 85%;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: v-bind('themeVars.codeColor');
|
||||
font-family: monospace;
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 0.5rem;
|
||||
|
||||
code {
|
||||
color: inherit;
|
||||
padding: 0;
|
||||
background: none;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
mark {
|
||||
background-color: #faf594;
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
hr {
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
padding-left: 1rem;
|
||||
border-left: 2px solid rgba(#0d0d0d, 0.1);
|
||||
}
|
||||
|
||||
hr {
|
||||
border: none;
|
||||
border-top: 2px solid rgba(#0d0d0d, 0.1);
|
||||
margin: 2rem 0;
|
||||
}
|
||||
|
||||
ul[data-type='taskList'] {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
> label {
|
||||
flex: 0 0 auto;
|
||||
margin-right: 0.5rem;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
> div {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import type { Component } from 'vue';
|
||||
|
||||
const props = defineProps<{ icon: Component; title: string; action: () => void; isActive?: () => boolean }>();
|
||||
const { icon, title, action, isActive } = toRefs(props);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-tooltip :tooltip="title">
|
||||
<c-button circle variant="text" :type="isActive?.() ? 'primary' : 'default'" @click="action">
|
||||
<n-icon :component="icon" />
|
||||
</c-button>
|
||||
</c-tooltip>
|
||||
</template>
|
||||
@@ -0,0 +1,167 @@
|
||||
<script setup lang="ts">
|
||||
import type { Editor } from '@tiptap/vue-3';
|
||||
import {
|
||||
ArrowBack,
|
||||
ArrowForwardUp,
|
||||
Blockquote,
|
||||
Bold,
|
||||
ClearFormatting,
|
||||
Code,
|
||||
CodePlus,
|
||||
H1,
|
||||
H2,
|
||||
H3,
|
||||
H4,
|
||||
Italic,
|
||||
List,
|
||||
ListNumbers,
|
||||
Strikethrough,
|
||||
TextWrap,
|
||||
} from '@vicons/tabler';
|
||||
import type { Component } from 'vue';
|
||||
import MenuBarItem from './menu-bar-item.vue';
|
||||
|
||||
const props = defineProps<{ editor: Editor }>();
|
||||
const { editor } = toRefs(props);
|
||||
|
||||
type MenuItem =
|
||||
| {
|
||||
icon: Component
|
||||
title: string
|
||||
action: () => void
|
||||
isActive?: () => boolean
|
||||
type: 'button'
|
||||
}
|
||||
| { type: 'divider' };
|
||||
|
||||
const items: MenuItem[] = [
|
||||
{
|
||||
type: 'button',
|
||||
icon: Bold,
|
||||
title: 'Bold',
|
||||
action: () => editor.value.chain().focus().toggleBold().run(),
|
||||
isActive: () => editor.value.isActive('bold'),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: Italic,
|
||||
title: 'Italic',
|
||||
action: () => editor.value.chain().focus().toggleItalic().run(),
|
||||
isActive: () => editor.value.isActive('italic'),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: Strikethrough,
|
||||
title: 'Strike',
|
||||
action: () => editor.value.chain().focus().toggleStrike().run(),
|
||||
isActive: () => editor.value.isActive('strike'),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: Code,
|
||||
title: 'Inline code',
|
||||
action: () => editor.value.chain().focus().toggleCode().run(),
|
||||
isActive: () => editor.value.isActive('code'),
|
||||
},
|
||||
{
|
||||
type: 'divider',
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: H1,
|
||||
title: 'Heading 1',
|
||||
action: () => editor.value.chain().focus().toggleHeading({ level: 1 }).run(),
|
||||
isActive: () => editor.value.isActive('heading', { level: 1 }),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: H2,
|
||||
title: 'Heading 2',
|
||||
action: () => editor.value.chain().focus().toggleHeading({ level: 2 }).run(),
|
||||
isActive: () => editor.value.isActive('heading', { level: 2 }),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: H3,
|
||||
title: 'Heading 3',
|
||||
action: () => editor.value.chain().focus().toggleHeading({ level: 3 }).run(),
|
||||
isActive: () => editor.value.isActive('heading', { level: 3 }),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: H4,
|
||||
title: 'Heading 4',
|
||||
action: () => editor.value.chain().focus().toggleHeading({ level: 4 }).run(),
|
||||
isActive: () => editor.value.isActive('heading', { level: 4 }),
|
||||
},
|
||||
{
|
||||
type: 'divider',
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: List,
|
||||
title: 'Bullet list',
|
||||
action: () => editor.value.chain().focus().toggleBulletList().run(),
|
||||
isActive: () => editor.value.isActive('bulletList'),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: ListNumbers,
|
||||
title: 'Ordered list',
|
||||
action: () => editor.value.chain().focus().toggleOrderedList().run(),
|
||||
isActive: () => editor.value.isActive('orderedList'),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: CodePlus,
|
||||
title: 'Code block',
|
||||
action: () => editor.value.chain().focus().toggleCodeBlock().run(),
|
||||
isActive: () => editor.value.isActive('codeBlock'),
|
||||
},
|
||||
|
||||
{
|
||||
type: 'button',
|
||||
icon: Blockquote,
|
||||
title: 'Blockquote',
|
||||
action: () => editor.value.chain().focus().toggleBlockquote().run(),
|
||||
isActive: () => editor.value.isActive('blockquote'),
|
||||
},
|
||||
{
|
||||
type: 'divider',
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: TextWrap,
|
||||
title: 'Hard break',
|
||||
action: () => editor.value.chain().focus().setHardBreak().run(),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: ClearFormatting,
|
||||
title: 'Clear format',
|
||||
action: () => editor.value.chain().focus().clearNodes().unsetAllMarks().run(),
|
||||
},
|
||||
|
||||
{
|
||||
type: 'button',
|
||||
icon: ArrowBack,
|
||||
title: 'Undo',
|
||||
action: () => editor.value.chain().focus().undo().run(),
|
||||
},
|
||||
{
|
||||
type: 'button',
|
||||
icon: ArrowForwardUp,
|
||||
title: 'Redo',
|
||||
action: () => editor.value.chain().focus().redo().run(),
|
||||
},
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div flex items-center>
|
||||
<template v-for="(item, index) in items">
|
||||
<n-divider v-if="item.type === 'divider'" :key="`divider${index}`" vertical />
|
||||
<MenuBarItem v-else-if="item.type === 'button'" :key="index" v-bind="item" />
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { format } from 'prettier';
|
||||
import htmlParser from 'prettier/plugins/html';
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import Editor from './editor/editor.vue';
|
||||
import TextareaCopyable from '@/components/TextareaCopyable.vue';
|
||||
|
||||
const html = useStorage('html-wysiwyg-editor--html', '<h1>Hey!</h1><p>Welcome to this html wysiwyg editor</p>');
|
||||
|
||||
const formattedHtml = asyncComputed(() => format(html.value, { parser: 'html', plugins: [htmlParser] }), '');
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Editor v-model:html="html" />
|
||||
<TextareaCopyable :value="formattedHtml" language="html" />
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Edit } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.html-wysiwyg-editor.title'),
|
||||
path: '/html-wysiwyg-editor',
|
||||
description: translate('tools.html-wysiwyg-editor.description'),
|
||||
keywords: ['html', 'wysiwyg', 'editor', 'p', 'ul', 'ol', 'converter', 'live'],
|
||||
component: () => import('./html-wysiwyg-editor.vue'),
|
||||
icon: Edit,
|
||||
});
|
||||
@@ -0,0 +1,432 @@
|
||||
export const codesByCategories: {
|
||||
category: string
|
||||
codes: {
|
||||
code: number
|
||||
name: string
|
||||
description: string
|
||||
type: 'HTTP' | 'WebDav'
|
||||
}[]
|
||||
}[] = [
|
||||
{
|
||||
category: '1xx informational response',
|
||||
codes: [
|
||||
{
|
||||
code: 100,
|
||||
name: 'Continue',
|
||||
description: 'Waiting for the client to emit the body of the request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 101,
|
||||
name: 'Switching Protocols',
|
||||
description: 'The server has agreed to change protocol.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 102,
|
||||
name: 'Processing',
|
||||
description: 'The server is processing the request, but no response is available yet.',
|
||||
type: 'WebDav',
|
||||
},
|
||||
{
|
||||
code: 103,
|
||||
name: 'Early Hints',
|
||||
description: 'The server returns some response headers before final HTTP message.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
category: '2xx success',
|
||||
codes: [
|
||||
{
|
||||
code: 200,
|
||||
name: 'OK',
|
||||
description: 'Standard response for successful HTTP requests.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 201,
|
||||
name: 'Created',
|
||||
description: 'The request has been fulfilled, resulting in the creation of a new resource.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 202,
|
||||
name: 'Accepted',
|
||||
description: 'The request has been accepted for processing, but the processing has not been completed.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 203,
|
||||
name: 'Non-Authoritative Information',
|
||||
description:
|
||||
'The request is successful but the content of the original request has been modified by a transforming proxy.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 204,
|
||||
name: 'No Content',
|
||||
description: 'The server successfully processed the request and is not returning any content.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 205,
|
||||
name: 'Reset Content',
|
||||
description: 'The server indicates to reinitialize the document view which sent this request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 206,
|
||||
name: 'Partial Content',
|
||||
description: 'The server is delivering only part of the resource due to a range header sent by the client.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 207,
|
||||
name: 'Multi-Status',
|
||||
description:
|
||||
'The message body that follows is an XML message and can contain a number of separate response codes.',
|
||||
type: 'WebDav',
|
||||
},
|
||||
{
|
||||
code: 208,
|
||||
name: 'Already Reported',
|
||||
description:
|
||||
'The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response.',
|
||||
type: 'WebDav',
|
||||
},
|
||||
{
|
||||
code: 226,
|
||||
name: 'IM Used',
|
||||
description:
|
||||
'The server has fulfilled a request for the resource, and the response is a representation of the result.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
category: '3xx redirection',
|
||||
codes: [
|
||||
{
|
||||
code: 300,
|
||||
name: 'Multiple Choices',
|
||||
description: 'Indicates multiple options for the resource that the client may follow.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 301,
|
||||
name: 'Moved Permanently',
|
||||
description: 'This and all future requests should be directed to the given URI.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 302,
|
||||
name: 'Found',
|
||||
description: 'Redirect to another URL. This is an example of industry practice contradicting the standard.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 303,
|
||||
name: 'See Other',
|
||||
description: 'The response to the request can be found under another URI using a GET method.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 304,
|
||||
name: 'Not Modified',
|
||||
description:
|
||||
'Indicates that the resource has not been modified since the version specified by the request headers.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 305,
|
||||
name: 'Use Proxy',
|
||||
description:
|
||||
'The requested resource is available only through a proxy, the address for which is provided in the response.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 306,
|
||||
name: 'Switch Proxy',
|
||||
description: 'No longer used. Originally meant "Subsequent requests should use the specified proxy."',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 307,
|
||||
name: 'Temporary Redirect',
|
||||
description:
|
||||
'In this case, the request should be repeated with another URI; however, future requests should still use the original URI.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 308,
|
||||
name: 'Permanent Redirect',
|
||||
description: 'The request and all future requests should be repeated using another URI.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
category: '4xx client error',
|
||||
codes: [
|
||||
{
|
||||
code: 400,
|
||||
name: 'Bad Request',
|
||||
description: 'The server cannot or will not process the request due to an apparent client error.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 401,
|
||||
name: 'Unauthorized',
|
||||
description:
|
||||
'Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 402,
|
||||
name: 'Payment Required',
|
||||
description:
|
||||
'Reserved for future use. The original intention was that this code might be used as part of some form of digital cash or micropayment scheme.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 403,
|
||||
name: 'Forbidden',
|
||||
description:
|
||||
'The request was valid, but the server is refusing action. The user might not have the necessary permissions for a resource.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 404,
|
||||
name: 'Not Found',
|
||||
description: 'The requested resource could not be found but may be available in the future.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 405,
|
||||
name: 'Method Not Allowed',
|
||||
description: 'A request method is not supported for the requested resource.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 406,
|
||||
name: 'Not Acceptable',
|
||||
description:
|
||||
'The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 407,
|
||||
name: 'Proxy Authentication Required',
|
||||
description: 'The client must first authenticate itself with the proxy.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 408,
|
||||
name: 'Request Timeout',
|
||||
description: 'The server timed out waiting for the request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 409,
|
||||
name: 'Conflict',
|
||||
description:
|
||||
'Indicates that the request could not be processed because of conflict in the request, such as an edit conflict.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 410,
|
||||
name: 'Gone',
|
||||
description: 'Indicates that the resource requested is no longer available and will not be available again.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 411,
|
||||
name: 'Length Required',
|
||||
description:
|
||||
'The request did not specify the length of its content, which is required by the requested resource.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 412,
|
||||
name: 'Precondition Failed',
|
||||
description: 'The server does not meet one of the preconditions that the requester put on the request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 413,
|
||||
name: 'Payload Too Large',
|
||||
description: 'The request is larger than the server is willing or able to process.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 414,
|
||||
name: 'URI Too Long',
|
||||
description: 'The URI provided was too long for the server to process.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 415,
|
||||
name: 'Unsupported Media Type',
|
||||
description: 'The request entity has a media type which the server or resource does not support.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 416,
|
||||
name: 'Range Not Satisfiable',
|
||||
description: 'The client has asked for a portion of the file, but the server cannot supply that portion.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 417,
|
||||
name: 'Expectation Failed',
|
||||
description: 'The server cannot meet the requirements of the Expect request-header field.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 418,
|
||||
name: 'I\'m a teapot',
|
||||
description: 'The server refuses the attempt to brew coffee with a teapot.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 421,
|
||||
name: 'Misdirected Request',
|
||||
description: 'The request was directed at a server that is not able to produce a response.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 422,
|
||||
name: 'Unprocessable Entity',
|
||||
description: 'The request was well-formed but was unable to be followed due to semantic errors.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 423,
|
||||
name: 'Locked',
|
||||
description: 'The resource that is being accessed is locked.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 424,
|
||||
name: 'Failed Dependency',
|
||||
description: 'The request failed due to failure of a previous request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 425,
|
||||
name: 'Too Early',
|
||||
description: 'Indicates that the server is unwilling to risk processing a request that might be replayed.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 426,
|
||||
name: 'Upgrade Required',
|
||||
description: 'The client should switch to a different protocol such as TLS/1.0.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 428,
|
||||
name: 'Precondition Required',
|
||||
description: 'The origin server requires the request to be conditional.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 429,
|
||||
name: 'Too Many Requests',
|
||||
description: 'The user has sent too many requests in a given amount of time.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 431,
|
||||
name: 'Request Header Fields Too Large',
|
||||
description:
|
||||
'The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 451,
|
||||
name: 'Unavailable For Legal Reasons',
|
||||
description:
|
||||
'A server operator has received a legal demand to deny access to a resource or to a set of resources that includes the requested resource.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
category: '5xx server error',
|
||||
codes: [
|
||||
{
|
||||
code: 500,
|
||||
name: 'Internal Server Error',
|
||||
description:
|
||||
'A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 501,
|
||||
name: 'Not Implemented',
|
||||
description:
|
||||
'The server either does not recognize the request method, or it lacks the ability to fulfill the request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 502,
|
||||
name: 'Bad Gateway',
|
||||
description:
|
||||
'The server was acting as a gateway or proxy and received an invalid response from the upstream server.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 503,
|
||||
name: 'Service Unavailable',
|
||||
description: 'The server is currently unavailable (because it is overloaded or down for maintenance).',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 504,
|
||||
name: 'Gateway Timeout',
|
||||
description:
|
||||
'The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 505,
|
||||
name: 'HTTP Version Not Supported',
|
||||
description: 'The server does not support the HTTP protocol version used in the request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 506,
|
||||
name: 'Variant Also Negotiates',
|
||||
description: 'Transparent content negotiation for the request results in a circular reference.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 507,
|
||||
name: 'Insufficient Storage',
|
||||
description: 'The server is unable to store the representation needed to complete the request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 508,
|
||||
name: 'Loop Detected',
|
||||
description: 'The server detected an infinite loop while processing the request.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 510,
|
||||
name: 'Not Extended',
|
||||
description: 'Further extensions to the request are required for the server to fulfill it.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
{
|
||||
code: 511,
|
||||
name: 'Network Authentication Required',
|
||||
description: 'The client needs to authenticate to gain network access.',
|
||||
type: 'HTTP',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,11 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test.describe('Tool - Http status codes', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/http-status-codes');
|
||||
});
|
||||
|
||||
test('Has correct title', async ({ page }) => {
|
||||
await expect(page).toHaveTitle('HTTP status codes - IT Tools');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
<script setup lang="ts">
|
||||
import { codesByCategories } from './http-status-codes.constants';
|
||||
import { useFuzzySearch } from '@/composable/fuzzySearch';
|
||||
|
||||
const search = ref('');
|
||||
|
||||
const { searchResult } = useFuzzySearch({
|
||||
search,
|
||||
data: codesByCategories.flatMap(({ codes, category }) => codes.map(code => ({ ...code, category }))),
|
||||
options: {
|
||||
keys: [{ name: 'code', weight: 3 }, { name: 'name', weight: 2 }, 'description', 'category'],
|
||||
},
|
||||
});
|
||||
|
||||
const codesByCategoryFiltered = computed(() => {
|
||||
if (!search.value) {
|
||||
return codesByCategories;
|
||||
}
|
||||
|
||||
return [{ category: 'Search results', codes: searchResult.value }];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-input-text
|
||||
v-model:value="search"
|
||||
placeholder="Search http status..."
|
||||
autofocus raw-text mb-10
|
||||
/>
|
||||
|
||||
<div v-for="{ codes, category } of codesByCategoryFiltered" :key="category" mb-8>
|
||||
<div mb-2 text-xl>
|
||||
{{ category }}
|
||||
</div>
|
||||
|
||||
<c-card v-for="{ code, description, name, type } of codes" :key="code" mb-2>
|
||||
<div text-lg font-bold>
|
||||
{{ code }} {{ name }}
|
||||
</div>
|
||||
<div op-70>
|
||||
{{ description }} {{ type !== 'HTTP' ? `For ${type}.` : '' }}
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,20 @@
|
||||
import { HttpRound } from '@vicons/material';
|
||||
import { defineTool } from '../tool';
|
||||
|
||||
import { codesByCategories } from './http-status-codes.constants';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.http-status-codes.title'),
|
||||
path: '/http-status-codes',
|
||||
description: translate('tools.http-status-codes.description'),
|
||||
keywords: [
|
||||
'http',
|
||||
'status',
|
||||
'codes',
|
||||
...codesByCategories.flatMap(({ codes }) => codes.flatMap(({ code, name }) => [String(code), name])),
|
||||
],
|
||||
component: () => import('./http-status-codes.vue'),
|
||||
icon: HttpRound,
|
||||
createdAt: new Date('2023-04-13'),
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { type Page, expect, test } from '@playwright/test';
|
||||
|
||||
async function extractIbanInfo({ page }: { page: Page }) {
|
||||
const itemsLines = await page
|
||||
.locator('.c-key-value-list__item').all();
|
||||
|
||||
return await Promise.all(
|
||||
itemsLines.map(async item => [
|
||||
(await item.locator('.c-key-value-list__key').textContent() ?? '').trim(),
|
||||
(await item.locator('.c-key-value-list__value').textContent() ?? '').trim(),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
test.describe('Tool - Iban validator and parser', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/iban-validator-and-parser');
|
||||
});
|
||||
|
||||
test('Has correct title', async ({ page }) => {
|
||||
await expect(page).toHaveTitle('IBAN validator and parser - IT Tools');
|
||||
});
|
||||
|
||||
test('iban info are extracted from a valid iban', async ({ page }) => {
|
||||
await page.getByTestId('iban-input').fill('DE89370400440532013000');
|
||||
|
||||
const ibanInfo = await extractIbanInfo({ page });
|
||||
|
||||
expect(ibanInfo).toEqual([
|
||||
['Is IBAN valid ?', 'Yes'],
|
||||
['Is IBAN a QR-IBAN ?', 'No'],
|
||||
['Country code', 'DE'],
|
||||
['BBAN', '370400440532013000'],
|
||||
['IBAN friendly format', 'DE89 3704 0044 0532 0130 00'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('invalid iban errors are displayed', async ({ page }) => {
|
||||
await page.getByTestId('iban-input').fill('FR7630006060011234567890189');
|
||||
|
||||
const ibanInfo = await extractIbanInfo({ page });
|
||||
|
||||
expect(ibanInfo).toEqual([
|
||||
['Is IBAN valid ?', 'No'],
|
||||
['IBAN errors', 'Wrong account bank branch checksum Wrong IBAN checksum'],
|
||||
['Is IBAN a QR-IBAN ?', 'No'],
|
||||
['Country code', 'N/A'],
|
||||
['BBAN', 'N/A'],
|
||||
['IBAN friendly format', 'FR76 3000 6060 0112 3456 7890 189'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ValidationErrorsIBAN } from 'ibantools';
|
||||
|
||||
export { getFriendlyErrors };
|
||||
|
||||
const ibanErrorToMessage = {
|
||||
[ValidationErrorsIBAN.NoIBANProvided]: 'No IBAN provided',
|
||||
[ValidationErrorsIBAN.NoIBANCountry]: 'No IBAN country',
|
||||
[ValidationErrorsIBAN.WrongBBANLength]: 'Wrong BBAN length',
|
||||
[ValidationErrorsIBAN.WrongBBANFormat]: 'Wrong BBAN format',
|
||||
[ValidationErrorsIBAN.ChecksumNotNumber]: 'Checksum is not a number',
|
||||
[ValidationErrorsIBAN.WrongIBANChecksum]: 'Wrong IBAN checksum',
|
||||
[ValidationErrorsIBAN.WrongAccountBankBranchChecksum]: 'Wrong account bank branch checksum',
|
||||
[ValidationErrorsIBAN.QRIBANNotAllowed]: 'QR-IBAN not allowed',
|
||||
};
|
||||
|
||||
function getFriendlyErrors(errorCodes: ValidationErrorsIBAN[]) {
|
||||
return errorCodes.map(errorCode => ibanErrorToMessage[errorCode]).filter(Boolean);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
import { extractIBAN, friendlyFormatIBAN, isQRIBAN, validateIBAN } from 'ibantools';
|
||||
import { getFriendlyErrors } from './iban-validator-and-parser.service';
|
||||
import type { CKeyValueListItems } from '@/ui/c-key-value-list/c-key-value-list.types';
|
||||
|
||||
const rawIban = ref('');
|
||||
|
||||
const ibanInfo = computed<CKeyValueListItems>(() => {
|
||||
const iban = rawIban.value.toUpperCase().replace(/\s/g, '').replace(/-/g, '');
|
||||
|
||||
if (iban === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const { valid: isIbanValid, errorCodes } = validateIBAN(iban);
|
||||
const { countryCode, bban } = extractIBAN(iban);
|
||||
const errors = getFriendlyErrors(errorCodes);
|
||||
|
||||
return [
|
||||
|
||||
{
|
||||
label: 'Is IBAN valid ?',
|
||||
value: isIbanValid,
|
||||
showCopyButton: false,
|
||||
},
|
||||
{
|
||||
label: 'IBAN errors',
|
||||
value: errors.length === 0 ? undefined : errors,
|
||||
hideOnNil: true,
|
||||
showCopyButton: false,
|
||||
},
|
||||
{
|
||||
label: 'Is IBAN a QR-IBAN ?',
|
||||
value: isQRIBAN(iban),
|
||||
showCopyButton: false,
|
||||
},
|
||||
{
|
||||
label: 'Country code',
|
||||
value: countryCode,
|
||||
},
|
||||
{
|
||||
label: 'BBAN',
|
||||
value: bban,
|
||||
},
|
||||
{
|
||||
label: 'IBAN friendly format',
|
||||
value: friendlyFormatIBAN(iban),
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const ibanExamples = [
|
||||
'FR7630006000011234567890189',
|
||||
'DE89370400440532013000',
|
||||
'GB29NWBK60161331926819',
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<c-input-text v-model:value="rawIban" placeholder="Enter an IBAN to check for validity..." test-id="iban-input" />
|
||||
|
||||
<c-card v-if="ibanInfo.length > 0" mt-5>
|
||||
<c-key-value-list :items="ibanInfo" data-test-id="iban-info" />
|
||||
</c-card>
|
||||
|
||||
<c-card title="Valid IBAN examples" mt-5>
|
||||
<div v-for="iban in ibanExamples" :key="iban">
|
||||
<c-text-copyable :value="iban" font-mono :displayed-value="friendlyFormatIBAN(iban)" />
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
import Bank from '~icons/mdi/bank';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.iban-validator-and-parser.title'),
|
||||
path: '/iban-validator-and-parser',
|
||||
description: translate('tools.iban-validator-and-parser.description'),
|
||||
keywords: ['iban', 'validator', 'and', 'parser', 'bic', 'bank'],
|
||||
component: () => import('./iban-validator-and-parser.vue'),
|
||||
icon: Bank,
|
||||
createdAt: new Date('2023-08-26'),
|
||||
});
|
||||
@@ -0,0 +1,402 @@
|
||||
<script setup lang="ts">
|
||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
||||
|
||||
const genHist = useGenHistory('image-ocr');
|
||||
interface OcrLine {
|
||||
text: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
import { licenseHeaders } from '../license/license';
|
||||
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const imageSrc = ref('');
|
||||
const fileName = ref('');
|
||||
const lines = ref<OcrLine[]>([]);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const dragActive = ref(false);
|
||||
|
||||
function pickFile() {
|
||||
fileInput.value?.click();
|
||||
}
|
||||
|
||||
async function handleFile(file?: File | null) {
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
if (!file.type.startsWith('image/')) {
|
||||
error.value = '请选择图片文件(png/jpg/webp/bmp 等)';
|
||||
return;
|
||||
}
|
||||
error.value = '';
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
imageSrc.value = String(reader.result ?? '');
|
||||
fileName.value = file.name;
|
||||
recognize();
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function onInputChange(e: Event) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
handleFile(input.files?.[0]);
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
function onDrop(e: DragEvent) {
|
||||
dragActive.value = false;
|
||||
handleFile(e.dataTransfer?.files?.[0]);
|
||||
}
|
||||
|
||||
// paste image from clipboard
|
||||
function onPaste(e: ClipboardEvent) {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) {
|
||||
return;
|
||||
}
|
||||
for (const item of items) {
|
||||
if (item.type.startsWith('image/')) {
|
||||
handleFile(item.getAsFile());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function recognize() {
|
||||
if (!imageSrc.value) {
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const blob = await (await fetch(imageSrc.value)).blob();
|
||||
const form = new FormData();
|
||||
form.append('image_file', blob, fileName.value || 'pasted.png');
|
||||
const res = await fetch('/api/ocr', { method: 'POST', body: form, headers: licenseHeaders('image-ocr') });
|
||||
if (!res.ok) {
|
||||
throw new Error(`OCR 服务 HTTP ${res.status}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
const list: OcrLine[] = Object.keys(data)
|
||||
.sort((a, b) => Number(a) - Number(b))
|
||||
.map(k => ({ text: String(data[k]?.rec_txt ?? ''), score: Number(data[k]?.score ?? 0) }))
|
||||
.filter(l => l.text);
|
||||
lines.value = list;
|
||||
if (!list.length) {
|
||||
error.value = '未识别到文字,可尝试更清晰的截图';
|
||||
}
|
||||
else {
|
||||
genHist.add({ title: fileName.value || '图片OCR', detail: allText.value.slice(0, 100) });
|
||||
}
|
||||
}
|
||||
catch (e: any) {
|
||||
error.value = `识别失败:${e?.message ?? e}`;
|
||||
lines.value = [];
|
||||
}
|
||||
finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const allText = computed(() => lines.value.map(l => l.text).join('\n'));
|
||||
|
||||
async function copyAll() {
|
||||
if (!allText.value) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(allText.value);
|
||||
}
|
||||
catch {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = allText.value;
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
document.execCommand('copy');
|
||||
ta.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function downloadTxt() {
|
||||
if (!allText.value) {
|
||||
return;
|
||||
}
|
||||
const blob = new Blob([allText.value], { type: 'text/plain;charset=utf-8' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'ocr-result.txt';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
imageSrc.value = '';
|
||||
fileName.value = '';
|
||||
lines.value = [];
|
||||
error.value = '';
|
||||
}
|
||||
|
||||
// fit viewport: no page scroll
|
||||
const rootEl = ref<HTMLElement>();
|
||||
const rootStyle = ref<Record<string, string>>({});
|
||||
|
||||
function fit() {
|
||||
const el = rootEl.value;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
const top = el.getBoundingClientRect().top;
|
||||
const height = Math.max(300, window.innerHeight - top - 12);
|
||||
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
|
||||
}
|
||||
|
||||
let observer: ResizeObserver | undefined;
|
||||
onMounted(() => {
|
||||
fit();
|
||||
window.addEventListener('resize', fit);
|
||||
window.addEventListener('paste', onPaste);
|
||||
observer = new ResizeObserver(() => fit());
|
||||
if (rootEl.value) {
|
||||
observer.observe(rootEl.value);
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', fit);
|
||||
window.removeEventListener('paste', onPaste);
|
||||
observer?.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="rootEl" class="ocr-root" :style="rootStyle">
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
style="display:none"
|
||||
@change="onInputChange"
|
||||
>
|
||||
|
||||
<div class="toolbar">
|
||||
<div class="stats">
|
||||
<template v-if="lines.length">
|
||||
识别到 {{ lines.length }} 行文字
|
||||
</template>
|
||||
</div>
|
||||
<c-button type="primary" :disabled="loading || !imageSrc" @click="recognize">
|
||||
重新识别
|
||||
</c-button>
|
||||
<c-button :disabled="!lines.length" @click="copyAll">
|
||||
复制全部
|
||||
</c-button>
|
||||
<c-button :disabled="!lines.length" @click="downloadTxt">
|
||||
下载TXT
|
||||
</c-button>
|
||||
<c-button @click="clearAll">
|
||||
清空
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<div class="body">
|
||||
<!-- left: image -->
|
||||
<div class="pane">
|
||||
<div
|
||||
class="dropzone"
|
||||
:class="{ active: dragActive, hasImage: !!imageSrc }"
|
||||
@click="pickFile"
|
||||
@dragover.prevent="dragActive = true"
|
||||
@dragleave.prevent="dragActive = false"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<img v-if="imageSrc" :src="imageSrc" alt="待识别图片">
|
||||
<div v-else class="drop-hint">
|
||||
<div class="icon">
|
||||
📷
|
||||
</div>
|
||||
<div>点击选择图片</div>
|
||||
<div class="sub">或拖拽图片到此处 / Ctrl+V 粘贴截图</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="fileName" class="hint">
|
||||
{{ fileName }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- right: result -->
|
||||
<div class="pane">
|
||||
<n-spin :show="loading">
|
||||
<div v-if="error" class="ocr-error">
|
||||
{{ error }}
|
||||
</div>
|
||||
<div v-else-if="!lines.length" class="empty">
|
||||
识别结果将显示在这里
|
||||
</div>
|
||||
<div v-else class="lines">
|
||||
<div v-for="(l, i) in lines" :key="i" class="line">
|
||||
<span class="line-text">{{ l.text }}</span>
|
||||
<span class="line-score">{{ (l.score * 100).toFixed(0) }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</n-spin>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<GenHistory tool="image-ocr" position="bottom" label="识别记录" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.ocr-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
padding-bottom: 12px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.stats {
|
||||
margin-right: auto;
|
||||
font-size: 13px;
|
||||
opacity: 0.65;
|
||||
}
|
||||
}
|
||||
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 16px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@media (max-width: 760px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.pane {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.dropzone {
|
||||
flex: 1;
|
||||
min-height: 180px;
|
||||
border: 2px dashed rgba(128, 128, 128, 0.45);
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
transition: border-color 0.2s, background-color 0.2s;
|
||||
box-sizing: border-box;
|
||||
|
||||
&:hover,
|
||||
&.active {
|
||||
border-color: #18a058;
|
||||
background-color: rgba(24, 160, 88, 0.06);
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.drop-hint {
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
opacity: 0.75;
|
||||
|
||||
.icon {
|
||||
font-size: 40px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.sub {
|
||||
font-size: 12px;
|
||||
opacity: 0.6;
|
||||
margin-top: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
opacity: 0.55;
|
||||
margin-top: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
min-height: 150px;
|
||||
border: 1px solid rgba(128, 128, 128, 0.3);
|
||||
border-radius: 6px;
|
||||
opacity: 0.5;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.ocr-error {
|
||||
color: #d03050;
|
||||
font-size: 13px;
|
||||
padding: 12px;
|
||||
border: 1px solid rgba(208, 48, 80, 0.35);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.lines {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
border: 1px solid rgba(128, 128, 128, 0.3);
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
user-select: text;
|
||||
|
||||
.line {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid rgba(128, 128, 128, 0.15);
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.line-text {
|
||||
flex: 1;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.line-score {
|
||||
font-size: 11px;
|
||||
opacity: 0.5;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Scan } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.image-ocr.title'),
|
||||
path: '/image-ocr',
|
||||
description: translate('tools.image-ocr.description'),
|
||||
keywords: ['ocr', 'image', 'text', 'recognize', 'scan', 'extract', 'picture', '截图', '识别', '文字识别', '图片'],
|
||||
component: () => import('./image-ocr.vue'),
|
||||
icon: Scan,
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
import { Photo } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.image-tools.title'),
|
||||
path: '/image-tools',
|
||||
description: translate('tools.image-tools.description'),
|
||||
keywords: ['image', 'compress', 'convert', 'resize', 'crop', 'rotate', 'filter', 'mosaic', 'exif', 'watermark', 'stitch', '图片', '压缩', '转换', '裁剪', '旋转', '滤镜', '打码', '水印', '拼接'],
|
||||
component: () => import('./image-tools.vue'),
|
||||
icon: Photo,
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
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 asciiTextDrawer } from './ascii-text-drawer';
|
||||
|
||||
import { tool as textToUnicode } from './text-to-unicode';
|
||||
import { tool as safelinkDecoder } from './safelink-decoder';
|
||||
import { tool as xmlToJson } from './xml-to-json';
|
||||
import { tool as jsonToXml } from './json-to-xml';
|
||||
import { tool as regexTester } from './regex-tester';
|
||||
import { tool as regexMemo } from './regex-memo';
|
||||
import { tool as markdownToHtml } from './markdown-to-html';
|
||||
import { tool as pdfSignatureChecker } from './pdf-signature-checker';
|
||||
import { tool as numeronymGenerator } from './numeronym-generator';
|
||||
import { tool as macAddressGenerator } from './mac-address-generator';
|
||||
import { tool as textToBinary } from './text-to-binary';
|
||||
import { tool as ulidGenerator } from './ulid-generator';
|
||||
import { tool as ibanValidatorAndParser } from './iban-validator-and-parser';
|
||||
import { tool as stringObfuscator } from './string-obfuscator';
|
||||
import { tool as textDiff } from './text-diff';
|
||||
import { tool as emojiPicker } from './emoji-picker';
|
||||
import { tool as passwordStrengthAnalyser } from './password-strength-analyser';
|
||||
import { tool as yamlToToml } from './yaml-to-toml';
|
||||
import { tool as jsonToToml } from './json-to-toml';
|
||||
import { tool as tomlToYaml } from './toml-to-yaml';
|
||||
import { tool as tomlToJson } from './toml-to-json';
|
||||
import { tool as jsonToCsv } from './json-to-csv';
|
||||
import { tool as cameraRecorder } from './camera-recorder';
|
||||
import { tool as listConverter } from './list-converter';
|
||||
import { tool as phoneParserAndFormatter } from './phone-parser-and-formatter';
|
||||
import { tool as jsonDiff } from './json-diff';
|
||||
import { tool as ipv4RangeExpander } from './ipv4-range-expander';
|
||||
import { tool as httpStatusCodes } from './http-status-codes';
|
||||
import { tool as yamlToJson } from './yaml-to-json-converter';
|
||||
import { tool as jsonToYaml } from './json-to-yaml-converter';
|
||||
import { tool as ipv6UlaGenerator } from './ipv6-ula-generator';
|
||||
import { tool as ipv4AddressConverter } from './ipv4-address-converter';
|
||||
import { tool as benchmarkBuilder } from './benchmark-builder';
|
||||
import { tool as userAgentParser } from './user-agent-parser';
|
||||
import { tool as ipv4SubnetCalculator } from './ipv4-subnet-calculator';
|
||||
import { tool as dockerRunToDockerComposeConverter } from './docker-run-to-docker-compose-converter';
|
||||
import { tool as htmlWysiwygEditor } from './html-wysiwyg-editor';
|
||||
import { tool as rsaKeyPairGenerator } from './rsa-key-pair-generator';
|
||||
import { tool as textToNatoAlphabet } from './text-to-nato-alphabet';
|
||||
import { tool as slugifyString } from './slugify-string';
|
||||
import { tool as keycodeInfo } from './keycode-info';
|
||||
import { tool as jsonMinify } from './json-minify';
|
||||
import { tool as bcrypt } from './bcrypt';
|
||||
import { tool as bip39 } from './bip39-generator';
|
||||
import { tool as caseConverter } from './case-converter';
|
||||
import { tool as chmodCalculator } from './chmod-calculator';
|
||||
import { tool as chronometer } from './chronometer';
|
||||
import { tool as colorConverter } from './color-converter';
|
||||
import { tool as crontabGenerator } from './crontab-generator';
|
||||
import { tool as dateTimeConverter } from './date-time-converter';
|
||||
import { tool as deviceInformation } from './device-information';
|
||||
import { tool as cypher } from './encryption';
|
||||
import { tool as etaCalculator } from './eta-calculator';
|
||||
import { tool as percentageCalculator } from './percentage-calculator';
|
||||
import { tool as gitMemo } from './git-memo';
|
||||
import { tool as hashText } from './hash-text';
|
||||
import { tool as hmacGenerator } from './hmac-generator';
|
||||
import { tool as htmlEntities } from './html-entities';
|
||||
import { tool as baseConverter } from './integer-base-converter';
|
||||
import { tool as jsonViewer } from './json-viewer';
|
||||
import { tool as jwtParser } from './jwt-parser';
|
||||
import { tool as loremIpsumGenerator } from './lorem-ipsum-generator';
|
||||
import { tool as mathEvaluator } from './math-evaluator';
|
||||
import { tool as metaTagGenerator } from './meta-tag-generator';
|
||||
import { tool as mimeTypes } from './mime-types';
|
||||
import { tool as otpCodeGeneratorAndValidator } from './otp-code-generator-and-validator';
|
||||
import { tool as qrCodeGenerator } from './qr-code-generator';
|
||||
import { tool as batchBarcodeGenerator } from './batch-barcode-generator';
|
||||
import { tool as siteBookmarks } from './site-bookmarks';
|
||||
import { tool as translator } from './translator';
|
||||
import { tool as labelDesigner } from './label-designer';
|
||||
import { tool as imageOcr } from './image-ocr';
|
||||
import { tool as codeReader } from './code-reader';
|
||||
import { tool as pdfOcr } from './pdf-ocr';
|
||||
import { tool as pdfTools } from './pdf-tools';
|
||||
import { tool as imageTools } from './image-tools';
|
||||
import { tool as docConvert } from './doc-convert';
|
||||
import { tool as aiRetouch } from './ai-retouch';
|
||||
import { tool as wifiQrCodeGenerator } from './wifi-qr-code-generator';
|
||||
import { tool as randomPortGenerator } from './random-port-generator';
|
||||
import { tool as romanNumeralConverter } from './roman-numeral-converter';
|
||||
import { tool as sqlPrettify } from './sql-prettify';
|
||||
import { tool as svgPlaceholderGenerator } from './svg-placeholder-generator';
|
||||
import { tool as temperatureConverter } from './temperature-converter';
|
||||
import { tool as textStatistics } from './text-statistics';
|
||||
import { tool as tokenGenerator } from './token-generator';
|
||||
import type { ToolCategory } from './tools.types';
|
||||
import { tool as urlEncoder } from './url-encoder';
|
||||
import { tool as urlParser } from './url-parser';
|
||||
import { tool as uuidGenerator } from './uuid-generator';
|
||||
import { tool as macAddressLookup } from './mac-address-lookup';
|
||||
import { tool as xmlFormatter } from './xml-formatter';
|
||||
import { tool as yamlViewer } from './yaml-viewer';
|
||||
|
||||
export const toolsByCategory: ToolCategory[] = [
|
||||
{
|
||||
name: 'Crypto',
|
||||
components: [tokenGenerator, hashText, bcrypt, uuidGenerator, ulidGenerator, cypher, bip39, hmacGenerator, rsaKeyPairGenerator, passwordStrengthAnalyser, pdfSignatureChecker],
|
||||
},
|
||||
{
|
||||
name: 'Converter',
|
||||
components: [
|
||||
dateTimeConverter,
|
||||
baseConverter,
|
||||
romanNumeralConverter,
|
||||
base64StringConverter,
|
||||
base64FileConverter,
|
||||
colorConverter,
|
||||
caseConverter,
|
||||
textToNatoAlphabet,
|
||||
textToBinary,
|
||||
textToUnicode,
|
||||
yamlToJson,
|
||||
yamlToToml,
|
||||
jsonToYaml,
|
||||
jsonToToml,
|
||||
listConverter,
|
||||
tomlToJson,
|
||||
tomlToYaml,
|
||||
xmlToJson,
|
||||
jsonToXml,
|
||||
markdownToHtml,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Web',
|
||||
components: [
|
||||
urlEncoder,
|
||||
htmlEntities,
|
||||
urlParser,
|
||||
deviceInformation,
|
||||
basicAuthGenerator,
|
||||
metaTagGenerator,
|
||||
otpCodeGeneratorAndValidator,
|
||||
mimeTypes,
|
||||
jwtParser,
|
||||
keycodeInfo,
|
||||
slugifyString,
|
||||
htmlWysiwygEditor,
|
||||
userAgentParser,
|
||||
httpStatusCodes,
|
||||
jsonDiff,
|
||||
safelinkDecoder,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Images and videos',
|
||||
components: [qrCodeGenerator, wifiQrCodeGenerator, batchBarcodeGenerator, codeReader, imageOcr, pdfOcr, pdfTools, imageTools, docConvert, aiRetouch, labelDesigner, siteBookmarks, svgPlaceholderGenerator, cameraRecorder],
|
||||
},
|
||||
{
|
||||
name: 'Development',
|
||||
components: [
|
||||
gitMemo,
|
||||
randomPortGenerator,
|
||||
crontabGenerator,
|
||||
jsonViewer,
|
||||
jsonMinify,
|
||||
jsonToCsv,
|
||||
sqlPrettify,
|
||||
chmodCalculator,
|
||||
dockerRunToDockerComposeConverter,
|
||||
xmlFormatter,
|
||||
yamlViewer,
|
||||
emailNormalizer,
|
||||
regexTester,
|
||||
regexMemo,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Network',
|
||||
components: [ipv4SubnetCalculator, ipv4AddressConverter, ipv4RangeExpander, macAddressLookup, macAddressGenerator, ipv6UlaGenerator],
|
||||
},
|
||||
{
|
||||
name: 'Math',
|
||||
components: [mathEvaluator, etaCalculator, percentageCalculator],
|
||||
},
|
||||
{
|
||||
name: 'Measurement',
|
||||
components: [chronometer, temperatureConverter, benchmarkBuilder],
|
||||
},
|
||||
{
|
||||
name: 'Text',
|
||||
components: [
|
||||
loremIpsumGenerator,
|
||||
textStatistics,
|
||||
emojiPicker,
|
||||
stringObfuscator,
|
||||
textDiff,
|
||||
numeronymGenerator,
|
||||
asciiTextDrawer,
|
||||
translator,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Data',
|
||||
components: [phoneParserAndFormatter, ibanValidatorAndParser],
|
||||
},
|
||||
];
|
||||
|
||||
export const tools = toolsByCategory.flatMap(({ components }) => components);
|
||||
export const toolsWithCategory = toolsByCategory.flatMap(({ components, name }) =>
|
||||
components.map(tool => ({ category: name, ...tool })),
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ArrowsLeftRight } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.base-converter.title'),
|
||||
path: '/base-converter',
|
||||
description: translate('tools.base-converter.description'),
|
||||
keywords: ['integer', 'number', 'base', 'conversion', 'decimal', 'hexadecimal', 'binary', 'octal', 'base64'],
|
||||
component: () => import('./integer-base-converter.vue'),
|
||||
icon: ArrowsLeftRight,
|
||||
});
|
||||
Loaded 100 of 528 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user