chore: global code formatting

This commit is contained in:
ShareVB committed 2026-09-06 09:02:45 +02:00
1 parent 5bf94bc567
commit bc44870665
791 files changed
+16920 -9437

No files matched your search

+1 -4
View File
@@ -43,10 +43,7 @@ watchEffect(() => {
locale.value = get(getITToolsSetting('default_locale', locale.value)); locale.value = get(getITToolsSetting('default_locale', locale.value));
syncRef( syncRef(locale, useStorage('locale', locale));
locale,
useStorage('locale', locale),
);
</script> </script>
<template> <template>
+40 -19
View File
@@ -21,8 +21,8 @@ const collapsedCategories = useStorage<Record<string, boolean>>(
{ {
deep: true, deep: true,
serializer: { serializer: {
read: v => (v ? JSON.parse(v) : null), read: (v) => (v ? JSON.parse(v) : null),
write: v => JSON.stringify(v), write: (v) => JSON.stringify(v),
}, },
}, },
); );
@@ -52,9 +52,7 @@ function toggleCategoryCollapse({ name }: { name: string }) {
} }
const areAllCollapsed = computed(() => { const areAllCollapsed = computed(() => {
return toolsByCategory.value.every(({ name }) => return toolsByCategory.value.every(({ name }) => collapsedCategories.value[name] !== false);
collapsedCategories.value[name] !== false,
);
}); });
async function toggleAllCategories() { async function toggleAllCategories() {
@@ -82,12 +80,12 @@ function getAnimationDuration(itemCount: number): number {
const baseDuration = 250; const baseDuration = 250;
const durationIncrement = 5; const durationIncrement = 5;
return baseDuration + (Math.min(itemCount, 30) * durationIncrement); return baseDuration + Math.min(itemCount, 30) * durationIncrement;
} }
// Function to check if any tool in the category is active // Function to check if any tool in the category is active
function isCategoryActive(components: Tool[]): boolean { function isCategoryActive(components: Tool[]): boolean {
return components.some(tool => tool.path === route.path); return components.some((tool) => tool.path === route.path);
} }
const menuOptions = computed(() => const menuOptions = computed(() =>
@@ -96,7 +94,7 @@ const menuOptions = computed(() =>
isCollapsed: collapsedCategories.value[name], isCollapsed: collapsedCategories.value[name],
isActive: isCategoryActive(components), isActive: isCategoryActive(components),
animationDuration: getAnimationDuration(components.length), animationDuration: getAnimationDuration(components.length),
tools: components.map(tool => ({ tools: components.map((tool) => ({
label: makeLabel(tool), label: makeLabel(tool),
icon: makeIcon(tool), icon: makeIcon(tool),
key: tool.path, key: tool.path,
@@ -105,16 +103,14 @@ const menuOptions = computed(() =>
); );
async function scrollToActiveItem() { async function scrollToActiveItem() {
const activeCategory = toolsByCategory.value.find(({ components }) => const activeCategory = toolsByCategory.value.find(({ components }) => isCategoryActive(components));
isCategoryActive(components),
);
if (activeCategory) { if (activeCategory) {
// Expand the active category // Expand the active category
collapsedCategories.value[activeCategory.name] = false; collapsedCategories.value[activeCategory.name] = false;
// Wait for the entire animation to complete // Wait for the entire animation to complete
await new Promise(resolve => setTimeout(resolve, getAnimationDuration(activeCategory.components.length) + 50)); await new Promise((resolve) => setTimeout(resolve, getAnimationDuration(activeCategory.components.length) + 50));
// Scroll to the active menu item // Scroll to the active menu item
const menuContainer = menuContainerRefs.value[activeCategory.name]; const menuContainer = menuContainerRefs.value[activeCategory.name];
@@ -131,9 +127,12 @@ onMounted(() => {
scrollToActiveItem(); scrollToActiveItem();
}); });
watch(() => route.path, () => { watch(
() => route.path,
() => {
scrollToActiveItem(); scrollToActiveItem();
}); },
);
const themeVars = useThemeVars(); const themeVars = useThemeVars();
</script> </script>
@@ -147,19 +146,37 @@ const themeVars = useThemeVars();
{{ areAllCollapsed ? $t('collapsibleToolMenu.text.expanding') : $t('collapsibleToolMenu.text.collapsing') }} {{ areAllCollapsed ? $t('collapsibleToolMenu.text.expanding') : $t('collapsibleToolMenu.text.collapsing') }}
</span> </span>
<span v-else> <span v-else>
{{ areAllCollapsed ? $t('collapsibleToolMenu.text.expand-all-tools') : $t('collapsibleToolMenu.text.collapse-all-tools') }} {{
areAllCollapsed
? $t('collapsibleToolMenu.text.expand-all-tools')
: $t('collapsibleToolMenu.text.collapse-all-tools')
}}
</span> </span>
</c-button> </c-button>
</div> </div>
<div v-for="{ name, tools, isCollapsed, isActive, animationDuration } of menuOptions" :key="name" class="category-container"> <div
v-for="{ name, tools, isCollapsed, isActive, animationDuration } of menuOptions"
:key="name"
class="category-container"
>
<button <button
class="category-button" class="category-button"
:class="{ 'category-active': isActive }" :class="{ 'category-active': isActive }"
flex cursor-pointer items-center op-60 flex
cursor-pointer
items-center
op-60
@click="toggleCategoryCollapse({ name })" @click="toggleCategoryCollapse({ name })"
> >
<span :class="{ 'rotate-0': isCollapsed, 'rotate-90': !isCollapsed }" text-16px lh-1 op-50 transition-transform duration-200> <span
:class="{ 'rotate-0': isCollapsed, 'rotate-90': !isCollapsed }"
text-16px
lh-1
op-50
transition-transform
duration-200
>
<icon-mdi-chevron-right /> <icon-mdi-chevron-right />
</span> </span>
@@ -169,7 +186,11 @@ const themeVars = useThemeVars();
</button> </button>
<div <div
:ref="el => { if (el) menuContainerRefs[name] = el as HTMLElement }" :ref="
(el) => {
if (el) menuContainerRefs[name] = el as HTMLElement;
}
"
class="menu-container" class="menu-container"
:class="{ collapsed: isCollapsed }" :class="{ collapsed: isCollapsed }"
:style="{ '--animation-duration': `${animationDuration}ms` }" :style="{ '--animation-duration': `${animationDuration}ms` }"
+37 -20
View File
@@ -9,19 +9,19 @@ import { useAppTheme } from '@/ui/theme/themes';
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
transformer?: (v: string) => string transformer?: (v: string) => string;
inputValidationRules?: UseValidationRule<string>[] inputValidationRules?: UseValidationRule<string>[];
inputLabel?: string inputLabel?: string;
inputPlaceholder?: string inputPlaceholder?: string;
inputDefault?: string inputDefault?: string;
outputLabel?: string outputLabel?: string;
outputLanguage?: string outputLanguage?: string;
downloadFileName?: string downloadFileName?: string;
downloadButtonText?: string downloadButtonText?: string;
rows?: number rows?: number;
inputLineNumbers?: boolean inputLineNumbers?: boolean;
inputMaxRows?: number inputMaxRows?: number;
inputAutosize?: boolean inputAutosize?: boolean;
}>(), }>(),
{ {
transformer: _.identity, transformer: _.identity,
@@ -41,8 +41,19 @@ const props = withDefaults(
); );
const { const {
transformer, inputValidationRules, inputLabel, outputLabel, outputLanguage, transformer,
inputPlaceholder, inputDefault, downloadFileName, downloadButtonText, rows, inputLineNumbers, inputMaxRows, inputAutosize, inputValidationRules,
inputLabel,
outputLabel,
outputLanguage,
inputPlaceholder,
inputDefault,
downloadFileName,
downloadButtonText,
rows,
inputLineNumbers,
inputMaxRows,
inputAutosize,
} = toRefs(props); } = toRefs(props);
const appTheme = useAppTheme(); const appTheme = useAppTheme();
@@ -140,7 +151,8 @@ watch(
watch( watch(
input, input,
() => nextTick(() => { () =>
nextTick(() => {
const textarea = textareaElement.value; const textarea = textareaElement.value;
if (textarea) { if (textarea) {
lineNumbersOffset.value = textarea.scrollTop; lineNumbersOffset.value = textarea.scrollTop;
@@ -154,8 +166,7 @@ function focusInput() {
} }
const outputBase64 = computed(() => Base64.encode(output.value)); const outputBase64 = computed(() => Base64.encode(output.value));
const { download } = useDownloadFileFromBase64( const { download } = useDownloadFileFromBase64({
{
source: outputBase64, source: outputBase64,
filename: downloadFileName, filename: downloadFileName,
}); });
@@ -191,7 +202,9 @@ const { download } = useDownloadFileFromBase64(
aria-hidden="true" aria-hidden="true"
@click="focusInput" @click="focusInput"
> >
<pre class="line-numbers__content" :style="{ transform: `translateY(-${lineNumbersOffset}px)` }">{{ lineNumbersText }}</pre> <pre class="line-numbers__content" :style="{ transform: `translateY(-${lineNumbersOffset}px)` }">{{
lineNumbersText
}}</pre>
</div> </div>
</template> </template>
</CInputText> </CInputText>
@@ -199,7 +212,11 @@ const { download } = useDownloadFileFromBase64(
<div overflow-auto> <div overflow-auto>
<n-tabs type="line"> <n-tabs type="line">
<n-tab-pane name="output" :tab="outputLabel"> <n-tab-pane name="output" :tab="outputLabel">
<textarea-copyable :value="output" :language="outputLanguage" :follow-height-of="inputElement?.inputWrapperRef" /> <textarea-copyable
:value="output"
:language="outputLanguage"
:follow-height-of="inputElement?.inputWrapperRef"
/>
</n-tab-pane> </n-tab-pane>
<n-tab-pane name="editable" :tab="t('formatTransformer.viewer')"> <n-tab-pane name="editable" :tab="t('formatTransformer.viewer')">
<CodeBlockCopyable :value="output" :language="outputLanguage" /> <CodeBlockCopyable :value="output" :language="outputLanguage" />
+7 -15
View File
@@ -4,7 +4,7 @@ import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import type { Tool } from '@/tools/tools.types'; import type { Tool } from '@/tools/tools.types';
defineProps<{ defineProps<{
tool: Tool tool: Tool;
}>(); }>();
const textRef = ref<HTMLElement>(); const textRef = ref<HTMLElement>();
@@ -25,9 +25,10 @@ async function checkTruncation() {
const textWidth = context.measureText(text).width; const textWidth = context.measureText(text).width;
// Calculate precise container width by accounting for padding // Calculate precise container width by accounting for padding
const containerWidth = textRef.value.clientWidth const containerWidth =
- Number.parseFloat(computedStyle.paddingLeft) textRef.value.clientWidth -
- Number.parseFloat(computedStyle.paddingRight); Number.parseFloat(computedStyle.paddingLeft) -
Number.parseFloat(computedStyle.paddingRight);
showTooltip.value = textWidth > containerWidth; showTooltip.value = textWidth > containerWidth;
} }
@@ -55,19 +56,10 @@ onUnmounted(() => {
</script> </script>
<template> <template>
<n-tooltip <n-tooltip placement="right" :delay="500" :show-arrow="true" :disabled="!showTooltip">
placement="right"
:delay="500"
:show-arrow="true"
:disabled="!showTooltip"
>
<template #trigger> <template #trigger>
<RouterLink :to="tool.path" class="menu-link"> <RouterLink :to="tool.path" class="menu-link">
<span <span ref="textRef" class="menu-text" @mouseenter="checkTruncation">
ref="textRef"
class="menu-text"
@mouseenter="checkTruncation"
>
{{ tool.name }} {{ tool.name }}
</span> </span>
</RouterLink> </RouterLink>
+5 -2
View File
@@ -48,11 +48,14 @@ watchEffect(() => {
// Close the menu when navigating (tool links, the about button, ...) so the // Close the menu when navigating (tool links, the about button, ...) so the
// destination page is visible. // destination page is visible.
const route = useRoute(); const route = useRoute();
watch(() => route.path, () => { watch(
() => route.path,
() => {
if (isSmallScreen.value) { if (isSmallScreen.value) {
isMenuCollapsed.value = true; isMenuCollapsed.value = true;
} }
}); },
);
onUnmounted(() => { onUnmounted(() => {
document.body.style.overflow = ''; document.body.style.overflow = '';
}); });
+1 -1
View File
@@ -8,7 +8,7 @@ const { value } = toRefs(props);
const initialText = t('spanCopyable.copy'); const initialText = t('spanCopyable.copy');
const { copy, isJustCopied } = useCopy({ source: value, createToast: false }); const { copy, isJustCopied } = useCopy({ source: value, createToast: false });
const tooltipText = computed(() => isJustCopied.value ? t('spanCopyable.copied') : initialText); const tooltipText = computed(() => (isJustCopied.value ? t('spanCopyable.copied') : initialText));
</script> </script>
<template> <template>
+30 -19
View File
@@ -24,16 +24,16 @@ import { translate as t } from '@/plugins/i18n.plugin';
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
value: string value: string;
followHeightOf?: HTMLElement | null followHeightOf?: HTMLElement | null;
language?: string language?: string;
copyPlacement?: 'top-right' | 'bottom-right' | 'outside' | 'none' copyPlacement?: 'top-right' | 'bottom-right' | 'outside' | 'none';
copyMessage?: string copyMessage?: string;
wordWrap?: boolean wordWrap?: boolean;
downloadFileName?: string downloadFileName?: string;
downloadButtonText?: string downloadButtonText?: string;
scrollable?: boolean scrollable?: boolean;
maxHeight?: string maxHeight?: string;
}>(), }>(),
{ {
followHeightOf: null, followHeightOf: null,
@@ -65,26 +65,30 @@ hljs.registerLanguage('python', pythonHljs);
hljs.registerLanguage('php', phpHljs); hljs.registerLanguage('php', phpHljs);
hljs.registerLanguage('protobuf', protobufHljs); hljs.registerLanguage('protobuf', protobufHljs);
const { value, language, followHeightOf, copyPlacement, copyMessage, downloadFileName, downloadButtonText } = toRefs(props); const { value, language, followHeightOf, copyPlacement, copyMessage, downloadFileName, downloadButtonText } =
toRefs(props);
const { height } = followHeightOf.value ? useElementSize(followHeightOf) : { height: ref(null) }; const { height } = followHeightOf.value ? useElementSize(followHeightOf) : { height: ref(null) };
const scrollbarRef = ref(); const scrollbarRef = ref();
// Watch for content changes and scroll to bottom // Watch for content changes and scroll to bottom
watch(value, () => { watch(
value,
() => {
nextTick(() => { nextTick(() => {
if (scrollbarRef.value) { if (scrollbarRef.value) {
scrollbarRef.value.scrollTo({ top: scrollbarRef.value.scrollbarInstRef.containerRef.scrollHeight }); scrollbarRef.value.scrollTo({ top: scrollbarRef.value.scrollbarInstRef.containerRef.scrollHeight });
} }
}); });
}, { flush: 'post' }); },
{ flush: 'post' },
);
const { copy, isJustCopied } = useCopy({ source: value, createToast: false }); const { copy, isJustCopied } = useCopy({ source: value, createToast: false });
const tooltipText = computed(() => isJustCopied.value ? t('textareaCopyable.copied') : copyMessage.value); const tooltipText = computed(() => (isJustCopied.value ? t('textareaCopyable.copied') : copyMessage.value));
const valueBase64 = computed(() => Base64.encode(value.value)); const valueBase64 = computed(() => Base64.encode(value.value));
const { download } = useDownloadFileFromBase64( const { download } = useDownloadFileFromBase64({
{
source: valueBase64, source: valueBase64,
filename: downloadFileName, filename: downloadFileName,
}); });
@@ -94,7 +98,13 @@ const { download } = useDownloadFileFromBase64(
<div style="overflow-x: hidden; width: 100%"> <div style="overflow-x: hidden; width: 100%">
<c-card <c-card
relative relative
:style="copyPlacement === 'top-right' ? 'padding-top: 50px' : (copyPlacement === 'bottom-right' ? 'padding-bottom: 50px' : '')" :style="
copyPlacement === 'top-right'
? 'padding-top: 50px'
: copyPlacement === 'bottom-right'
? 'padding-bottom: 50px'
: ''
"
> >
<n-scrollbar <n-scrollbar
ref="scrollbarRef" ref="scrollbarRef"
@@ -112,8 +122,9 @@ const { download } = useDownloadFileFromBase64(
</n-scrollbar> </n-scrollbar>
<div <div
v-if="value && copyPlacement !== 'none'" v-if="value && copyPlacement !== 'none'"
absolute right-10px absolute
:class="copyPlacement === 'top-right' ? 'top-10px' : (copyPlacement === 'bottom-right' ? 'bottom-10px' : '')" right-10px
:class="copyPlacement === 'top-right' ? 'top-10px' : copyPlacement === 'bottom-right' ? 'bottom-10px' : ''"
:style="scrollable ? 'z-index: 10; background: var(--bg-color); border-radius: 50%; padding: 2px;' : ''" :style="scrollable ? 'z-index: 10; background: var(--bg-color); border-radius: 50%; padding: 2px;' : ''"
> >
<c-tooltip v-if="value && copyPlacement !== 'outside'" :tooltip="tooltipText" position="left"> <c-tooltip v-if="value && copyPlacement !== 'outside'" :tooltip="tooltipText" position="left">
+2 -5
View File
@@ -32,10 +32,7 @@ const theme = useThemeVars();
<div class="truncat my-5px text-lg text-black dark:text-white"> <div class="truncat my-5px text-lg text-black dark:text-white">
{{ tool.name }} {{ tool.name }}
<World <World v-if="tool.externAccessDescription" class="tool-privacy-icon" />
v-if="tool.externAccessDescription"
class="tool-privacy-icon"
/>
</div> </div>
<div class="line-clamp-2 text-neutral-500 dark:text-neutral-400"> <div class="line-clamp-2 text-neutral-500 dark:text-neutral-400">
@@ -48,6 +45,6 @@ const theme = useThemeVars();
<style lang="css" scoped> <style lang="css" scoped>
.tool-privacy-icon { .tool-privacy-icon {
display: inline-block; display: inline-block;
height: .9em; height: 0.9em;
} }
</style> </style>
+20 -10
View File
@@ -2,8 +2,14 @@ import { type Ref, ref, watchEffect } from 'vue';
export { computedCatch, computedCatchAsync }; export { computedCatch, computedCatchAsync };
function computedCatch<T, D>(getter: () => T, { defaultValue }: { defaultValue: D; defaultErrorMessage?: string }): [Ref<T | D>, Ref<string | undefined>]; function computedCatch<T, D>(
function computedCatch<T, D>(getter: () => T, { defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {}) { getter: () => T,
{ defaultValue }: { defaultValue: D; defaultErrorMessage?: string },
): [Ref<T | D>, Ref<string | undefined>];
function computedCatch<T, D>(
getter: () => T,
{ defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {},
) {
const error = ref<string | undefined>(); const error = ref<string | undefined>();
const value = ref<T | D | undefined>(); const value = ref<T | D | undefined>();
@@ -11,9 +17,8 @@ function computedCatch<T, D>(getter: () => T, { defaultValue, defaultErrorMessag
try { try {
error.value = undefined; error.value = undefined;
value.value = getter(); value.value = getter();
} } catch (err) {
catch (err) { error.value = err instanceof Error ? err.message : (err?.toString() ?? defaultErrorMessage);
error.value = err instanceof Error ? err.message : err?.toString() ?? defaultErrorMessage;
value.value = defaultValue; value.value = defaultValue;
} }
}); });
@@ -21,8 +26,14 @@ function computedCatch<T, D>(getter: () => T, { defaultValue, defaultErrorMessag
return [value, error] as const; return [value, error] as const;
} }
function computedCatchAsync<T, D>(getterAsync: () => Promise<T>, { defaultValue }: { defaultValue: D; defaultErrorMessage?: string }): [Ref<T | D>, Ref<string | undefined>]; function computedCatchAsync<T, D>(
function computedCatchAsync<T, D>(getterAsync: () => Promise<T>, { defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {}) { getterAsync: () => Promise<T>,
{ defaultValue }: { defaultValue: D; defaultErrorMessage?: string },
): [Ref<T | D>, Ref<string | undefined>];
function computedCatchAsync<T, D>(
getterAsync: () => Promise<T>,
{ defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {},
) {
const error = ref<string | undefined>(); const error = ref<string | undefined>();
const value = ref<T | D | undefined>(); const value = ref<T | D | undefined>();
@@ -30,9 +41,8 @@ function computedCatchAsync<T, D>(getterAsync: () => Promise<T>, { defaultValue,
try { try {
error.value = undefined; error.value = undefined;
value.value = await getterAsync(); value.value = await getterAsync();
} } catch (err) {
catch (err) { error.value = err instanceof Error ? err.message : (err?.toString() ?? defaultErrorMessage);
error.value = err instanceof Error ? err.message : err?.toString() ?? defaultErrorMessage;
value.value = defaultValue; value.value = defaultValue;
} }
}); });
+1 -2
View File
@@ -11,8 +11,7 @@ function computedRefreshable<T>(getter: () => T, { throttle }: { throttle?: numb
if (throttle) { if (throttle) {
watchThrottled(getter, update, { throttle }); watchThrottled(getter, update, { throttle });
} } else {
else {
watch(getter, update); watch(getter, update);
} }
+33 -20
View File
@@ -4,7 +4,11 @@ import { useMessage } from 'naive-ui';
import type { MaybeRefOrGetter } from 'vue'; import type { MaybeRefOrGetter } from 'vue';
import { translate as t } from '@/plugins/i18n.plugin'; import { translate as t } from '@/plugins/i18n.plugin';
export function useCopy({ source, text = t('tools.copy.text.copied-to-the-clipboard'), createToast = true }: { source?: MaybeRefOrGetter<string>; text?: string; createToast?: boolean } = {}) { export function useCopy({
source,
text = t('tools.copy.text.copied-to-the-clipboard'),
createToast = true,
}: { source?: MaybeRefOrGetter<string>; text?: string; createToast?: boolean } = {}) {
const { copy, copied, ...rest } = useClipboard({ const { copy, copied, ...rest } = useClipboard({
source, source,
legacy: true, legacy: true,
@@ -18,8 +22,7 @@ export function useCopy({ source, text = t('tools.copy.text.copied-to-the-clipbo
async copy(content?: string, { notificationMessage }: { notificationMessage?: string } = {}) { async copy(content?: string, { notificationMessage }: { notificationMessage?: string } = {}) {
if (source) { if (source) {
await copy(); await copy();
} } else {
else {
await copy(content); await copy(content);
} }
@@ -30,7 +33,11 @@ export function useCopy({ source, text = t('tools.copy.text.copied-to-the-clipbo
}; };
} }
export function useCopyClipboardItems({ source, text = t('tools.copy.text.copied-to-the-clipboard'), createToast = true }: { source?: MaybeRefOrGetter<Array<{ mime: string; content: string }>>; text?: string; createToast?: boolean } = {}) { export function useCopyClipboardItems({
source,
text = t('tools.copy.text.copied-to-the-clipboard'),
createToast = true,
}: { source?: MaybeRefOrGetter<Array<{ mime: string; content: string }>>; text?: string; createToast?: boolean } = {}) {
function toClipboardItem(item: { mime: string; content: string }) { function toClipboardItem(item: { mime: string; content: string }) {
return new ClipboardItem({ return new ClipboardItem({
[item.mime]: new Blob([item.content], { type: item.mime }), [item.mime]: new Blob([item.content], { type: item.mime }),
@@ -46,11 +53,13 @@ export function useCopyClipboardItems({ source, text = t('tools.copy.text.copied
return { return {
...rest, ...rest,
isJustCopied: copied, isJustCopied: copied,
async copy(content?: { mime: string; content: string }[], { notificationMessage }: { notificationMessage?: string } = {}) { async copy(
content?: { mime: string; content: string }[],
{ notificationMessage }: { notificationMessage?: string } = {},
) {
if (source) { if (source) {
await copy(); await copy();
} } else {
else {
await copy((content || []).map(toClipboardItem)); await copy((content || []).map(toClipboardItem));
} }
@@ -61,7 +70,17 @@ export function useCopyClipboardItems({ source, text = t('tools.copy.text.copied
}; };
} }
export function useCopyHtml({ sourceHtml, fallbackText, toastText = t('tools.copy.text.copied-to-the-clipboard'), createToast = true }: { sourceHtml?: MaybeRefOrGetter<string>; fallbackText?: MaybeRefOrGetter<string>; toastText?: string; createToast?: boolean } = {}) { export function useCopyHtml({
sourceHtml,
fallbackText,
toastText = t('tools.copy.text.copied-to-the-clipboard'),
createToast = true,
}: {
sourceHtml?: MaybeRefOrGetter<string>;
fallbackText?: MaybeRefOrGetter<string>;
toastText?: string;
createToast?: boolean;
} = {}) {
const message = useMessage(); const message = useMessage();
const copied = ref(false); const copied = ref(false);
@@ -81,8 +100,7 @@ export function useCopyHtml({ sourceHtml, fallbackText, toastText = t('tools.cop
try { try {
document.execCommand('copy'); document.execCommand('copy');
} } finally {
finally {
document.body.removeChild(textarea); document.body.removeChild(textarea);
} }
} }
@@ -100,19 +118,16 @@ export function useCopyHtml({ sourceHtml, fallbackText, toastText = t('tools.cop
const blobText = new Blob([fallbackText || html], { type: 'text/plain' }); const blobText = new Blob([fallbackText || html], { type: 'text/plain' });
const item = new ClipboardItemCtor({ 'text/plain': blobText, 'text/html': blobHtml }); const item = new ClipboardItemCtor({ 'text/plain': blobText, 'text/html': blobHtml });
await navigator.clipboard.write([item]); await navigator.clipboard.write([item]);
} } else if (navigator.clipboard?.writeText) {
else if (navigator.clipboard?.writeText) {
// Async text fallback // Async text fallback
await navigator.clipboard.writeText(fallbackText || html); await navigator.clipboard.writeText(fallbackText || html);
} } else {
else {
// Legacy execCommand fallback // Legacy execCommand fallback
legacyCopy(fallbackText || html); legacyCopy(fallbackText || html);
} }
copied.value = true; copied.value = true;
} } catch (e: any) {
catch (e: any) {
error.value = e.toString(); error.value = e.toString();
} }
} }
@@ -122,16 +137,14 @@ export function useCopyHtml({ sourceHtml, fallbackText, toastText = t('tools.cop
async copy(html?: string, text?: string, { notificationMessage }: { notificationMessage?: string } = {}) { async copy(html?: string, text?: string, { notificationMessage }: { notificationMessage?: string } = {}) {
if (sourceHtml) { if (sourceHtml) {
await copyHtml(toValue(sourceHtml), toValue(fallbackText)); await copyHtml(toValue(sourceHtml), toValue(fallbackText));
} } else if (html) {
else if (html) {
await copyHtml(html, text); await copyHtml(html, text);
} }
if (createToast) { if (createToast) {
if (error.value) { if (error.value) {
message.error(error.value); message.error(error.value);
} } else {
else {
message.success(notificationMessage ?? toastText); message.success(notificationMessage ?? toastText);
} }
} }
+9 -3
View File
@@ -4,15 +4,21 @@ import { getMimeTypeFromBase64 } from './downloadBase64';
describe('downloadBase64', () => { describe('downloadBase64', () => {
describe('getMimeTypeFromBase64', () => { describe('getMimeTypeFromBase64', () => {
it('when the base64 string has a data URI, it returns the mime type', () => { it('when the base64 string has a data URI, it returns the mime type', () => {
expect(getMimeTypeFromBase64({ base64String: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' })).to.deep.equal({ mimeType: 'image/png' }); expect(
expect(getMimeTypeFromBase64({ base64String: 'data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' })).to.deep.equal({ mimeType: 'image/jpg' }); getMimeTypeFromBase64({ base64String: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' }),
).to.deep.equal({ mimeType: 'image/png' });
expect(
getMimeTypeFromBase64({ base64String: 'data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' }),
).to.deep.equal({ mimeType: 'image/jpg' });
}); });
it('when the base64 string has no data URI, it try to infer the mime type from the signature', () => { it('when the base64 string has no data URI, it try to infer the mime type from the signature', () => {
// https://en.wikipedia.org/wiki/List_of_file_signatures // https://en.wikipedia.org/wiki/List_of_file_signatures
// PNG // PNG
expect(getMimeTypeFromBase64({ base64String: 'iVBORw0KGgoAAAANSUhEUgAAAAUA' })).to.deep.equal({ mimeType: 'image/png' }); expect(getMimeTypeFromBase64({ base64String: 'iVBORw0KGgoAAAANSUhEUgAAAAUA' })).to.deep.equal({
mimeType: 'image/png',
});
// GIF // GIF
expect(getMimeTypeFromBase64({ base64String: 'R0lGODdh' })).to.deep.equal({ mimeType: 'image/gif' }); expect(getMimeTypeFromBase64({ base64String: 'R0lGODdh' })).to.deep.equal({ mimeType: 'image/gif' });
+44 -21
View File
@@ -5,16 +5,18 @@ import { get } from '@vueuse/core';
export { export {
getMimeTypeFromBase64, getMimeTypeFromBase64,
getMimeTypeFromExtension, getExtensionFromMimeType, getMimeTypeFromExtension,
useDownloadFileFromBase64, useDownloadFileFromBase64Refs, getExtensionFromMimeType,
useDownloadFileFromBase64,
useDownloadFileFromBase64Refs,
previewImageFromBase64, previewImageFromBase64,
}; };
const commonMimeTypesSignatures = { const commonMimeTypesSignatures = {
'JVBERi0': 'application/pdf', JVBERi0: 'application/pdf',
'R0lGODdh': 'image/gif', R0lGODdh: 'image/gif',
'R0lGODlh': 'image/gif', R0lGODlh: 'image/gif',
'iVBORw0KGgo': 'image/png', iVBORw0KGgo: 'image/png',
'/9j/': 'image/jpg', '/9j/': 'image/jpg',
}; };
@@ -25,7 +27,9 @@ function getMimeTypeFromBase64({ base64String }: { base64String: string }) {
return { mimeType: mimeTypeFromBase64 }; return { mimeType: mimeTypeFromBase64 };
} }
const inferredMimeType = _.find(commonMimeTypesSignatures, (_mimeType, signature) => base64String.startsWith(signature)); const inferredMimeType = _.find(commonMimeTypesSignatures, (_mimeType, signature) =>
base64String.startsWith(signature),
);
if (inferredMimeType) { if (inferredMimeType) {
return { mimeType: inferredMimeType }; return { mimeType: inferredMimeType };
@@ -38,8 +42,8 @@ function getFileExtensionFromMimeType({
mimeType, mimeType,
defaultExtension = 'txt', defaultExtension = 'txt',
}: { }: {
mimeType: string | undefined mimeType: string | undefined;
defaultExtension?: string defaultExtension?: string;
}) { }) {
if (mimeType) { if (mimeType) {
return getExtensionFromMimeType(mimeType) ?? defaultExtension; return getExtensionFromMimeType(mimeType) ?? defaultExtension;
@@ -48,8 +52,17 @@ function getFileExtensionFromMimeType({
return defaultExtension; return defaultExtension;
} }
function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }: function downloadFromBase64({
{ sourceValue: string; filename?: string; extension?: string; fileMimeType?: string }) { sourceValue,
filename,
extension,
fileMimeType,
}: {
sourceValue: string;
filename?: string;
extension?: string;
fileMimeType?: string;
}) {
if (sourceValue === '') { if (sourceValue === '') {
throw new Error('Base64 string is empty'); throw new Error('Base64 string is empty');
} }
@@ -62,8 +75,7 @@ function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
base64String = `data:${targetMimeType};base64,${sourceValue}`; base64String = `data:${targetMimeType};base64,${sourceValue}`;
} }
const cleanExtension = extension ?? getFileExtensionFromMimeType( const cleanExtension = extension ?? getFileExtensionFromMimeType({ mimeType, defaultExtension });
{ mimeType, defaultExtension });
let cleanFileName = filename ?? `file.${cleanExtension}`; let cleanFileName = filename ?? `file.${cleanExtension}`;
if (extension && !cleanFileName.endsWith(`.${extension}`)) { if (extension && !cleanFileName.endsWith(`.${extension}`)) {
cleanFileName = `${cleanFileName}.${cleanExtension}`; cleanFileName = `${cleanFileName}.${cleanExtension}`;
@@ -75,9 +87,15 @@ function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
a.click(); a.click();
} }
function useDownloadFileFromBase64( function useDownloadFileFromBase64({
{ source, filename, extension }: source,
{ source: MaybeRef<string>; filename?: MaybeRef<string>; extension?: MaybeRef<string> }) { filename,
extension,
}: {
source: MaybeRef<string>;
filename?: MaybeRef<string>;
extension?: MaybeRef<string>;
}) {
return { return {
download() { download() {
downloadFromBase64({ sourceValue: get(source), filename: get(filename), extension: get(extension) }); downloadFromBase64({ sourceValue: get(source), filename: get(filename), extension: get(extension) });
@@ -105,17 +123,22 @@ function previewImageFromBase64(base64String: string): HTMLImageElement {
if (previewContainer) { if (previewContainer) {
previewContainer.innerHTML = ''; previewContainer.innerHTML = '';
previewContainer.appendChild(container); previewContainer.appendChild(container);
} } else {
else {
throw new Error('Preview container element not found'); throw new Error('Preview container element not found');
} }
return img; return img;
} }
function useDownloadFileFromBase64Refs( function useDownloadFileFromBase64Refs({
{ source, filename, extension }: source,
{ source: Ref<string>; filename?: Ref<string>; extension?: Ref<string> }) { filename,
extension,
}: {
source: Ref<string>;
filename?: Ref<string>;
extension?: Ref<string>;
}) {
return { return {
download() { download() {
downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value }); downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value });
+4 -4
View File
@@ -14,10 +14,10 @@ function useFuzzySearch<Data>({
options = {}, options = {},
limit = -1, limit = -1,
}: { }: {
search: MaybeRef<string> search: MaybeRef<string>;
data: Data[] data: Data[];
options?: IFuseOptions<Data> & { filterEmpty?: boolean } options?: IFuseOptions<Data> & { filterEmpty?: boolean };
limit?: number limit?: number;
}) { }) {
const fuse = new Fuse(data, options); const fuse = new Fuse(data, options);
const filterEmpty = options.filterEmpty ?? true; const filterEmpty = options.filterEmpty ?? true;
+37 -13
View File
@@ -26,7 +26,15 @@ const transformers = {
}, },
}; };
function useQueryParam<T>({ tool, name, defaultValue }: { tool: string; name: string; defaultValue: T }): RemovableRef<T> { function useQueryParam<T>({
tool,
name,
defaultValue,
}: {
tool: string;
name: string;
defaultValue: T;
}): RemovableRef<T> {
const type = typeof defaultValue; const type = typeof defaultValue;
const transformer = transformers[type as keyof typeof transformers] ?? transformers.string; const transformer = transformers[type as keyof typeof transformers] ?? transformers.string;
const defaultValueOrSetting = getITToolsSetting(`${tool}:${name}`, defaultValue); const defaultValueOrSetting = getITToolsSetting(`${tool}:${name}`, defaultValue);
@@ -43,7 +51,15 @@ function useQueryParam<T>({ tool, name, defaultValue }: { tool: string; name: st
}); });
} }
function useQueryParamOrStorage<T>({ name, storageName, defaultValue }: { name: string; storageName: string; defaultValue: T }) { function useQueryParamOrStorage<T>({
name,
storageName,
defaultValue,
}: {
name: string;
storageName: string;
defaultValue: T;
}) {
const type = typeof defaultValue; const type = typeof defaultValue;
const transformer = transformers[type as keyof typeof transformers] ?? transformers.string; const transformer = transformers[type as keyof typeof transformers] ?? transformers.string;
@@ -53,23 +69,32 @@ function useQueryParamOrStorage<T>({ name, storageName, defaultValue }: { name:
const proxyDefaultValue = transformer.toQuery(defaultValueOrSetting as never); const proxyDefaultValue = transformer.toQuery(defaultValueOrSetting as never);
const proxy = useRouteQuery(name, proxyDefaultValue); const proxy = useRouteQuery(name, proxyDefaultValue);
const r = isRef(defaultValueOrSetting) ? defaultValueOrSetting as Ref<T> : ref(get(defaultValueOrSetting)); const r = isRef(defaultValueOrSetting) ? (defaultValueOrSetting as Ref<T>) : ref(get(defaultValueOrSetting));
watch(r, watch(
r,
(value) => { (value) => {
proxy.value = transformer.toQuery(value as never); proxy.value = transformer.toQuery(value as never);
storageRef.value = value as never; storageRef.value = value as never;
}, },
{ deep: true }); { deep: true },
);
r.value = (proxy.value && proxy.value !== proxyDefaultValue r.value = (
? transformer.fromQuery(proxy.value) as unknown as T proxy.value && proxy.value !== proxyDefaultValue
: storageRef.value as T) as never; ? (transformer.fromQuery(proxy.value) as unknown as T)
: (storageRef.value as T)
) as never;
return r; return r;
} }
function useITStorage<T>(key: string, defaults: MaybeRef<T>, storage?: StorageLike, options?: UseStorageOptions<T>): RemovableRef<T> { function useITStorage<T>(
key: string,
defaults: MaybeRef<T>,
storage?: StorageLike,
options?: UseStorageOptions<T>,
): RemovableRef<T> {
const defaultValueOrSetting = getITToolsSetting(key, defaults); const defaultValueOrSetting = getITToolsSetting(key, defaults);
return useStorage<T>(key, defaultValueOrSetting, storage, options); return useStorage<T>(key, defaultValueOrSetting, storage, options);
} }
@@ -81,10 +106,9 @@ function getITToolsSetting<T>(key: string, defaultValue: MaybeRef<T>) {
} }
if (key.includes(':')) { if (key.includes(':')) {
const [tool, subkey] = key.split(':'); const [tool, subkey] = key.split(':');
return (itToolsSettings[tool] || {})[subkey] as T ?? defaultValue; return ((itToolsSettings[tool] || {})[subkey] as T) ?? defaultValue;
} } else {
else { return (itToolsSettings[key] as T) ?? defaultValue;
return (itToolsSettings)[key] as T ?? defaultValue;
} }
} }
+19 -19
View File
@@ -6,9 +6,9 @@ type ValidatorReturnType = unknown;
type GetErrorMessageReturnType = string; type GetErrorMessageReturnType = string;
export interface UseValidationRule<T> { export interface UseValidationRule<T> {
validator: (value: T) => ValidatorReturnType validator: (value: T) => ValidatorReturnType;
getErrorMessage?: (value: T) => GetErrorMessageReturnType getErrorMessage?: (value: T) => GetErrorMessageReturnType;
message: string message: string;
} }
export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean { export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
@@ -20,8 +20,7 @@ export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
} }
return returnValue === false; return returnValue === false;
} } catch (_) {
catch (_) {
return true; return true;
} }
} }
@@ -29,15 +28,14 @@ export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
export function getErrorMessageOrThrown(cb: () => GetErrorMessageReturnType): string { export function getErrorMessageOrThrown(cb: () => GetErrorMessageReturnType): string {
try { try {
return cb() || ''; return cb() || '';
} } catch (e: any) {
catch (e: any) {
return e.toString(); return e.toString();
} }
} }
export interface ValidationAttrs { export interface ValidationAttrs {
feedback: string feedback: string;
validationStatus: string | undefined validationStatus: string | undefined;
} }
export function useValidation<T>({ export function useValidation<T>({
@@ -45,15 +43,15 @@ export function useValidation<T>({
rules, rules,
watch: watchRefs = [], watch: watchRefs = [],
}: { }: {
source: Ref<T> source: Ref<T>;
rules: MaybeRef<UseValidationRule<T>[]> rules: MaybeRef<UseValidationRule<T>[]>;
watch?: Ref<unknown>[] watch?: Ref<unknown>[];
}) { }) {
const state = reactive<{ const state = reactive<{
message: string message: string;
status: undefined | 'error' status: undefined | 'error';
isValid: boolean isValid: boolean;
attrs: ValidationAttrs attrs: ValidationAttrs;
}>({ }>({
message: '', message: '',
status: undefined, status: undefined,
@@ -74,9 +72,11 @@ export function useValidation<T>({
if (isFalsyOrHasThrown(() => rule.validator(source.value))) { if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
if (rule.getErrorMessage) { if (rule.getErrorMessage) {
const getErrorMessage = rule.getErrorMessage; const getErrorMessage = rule.getErrorMessage;
state.message = rule.message.replace('{0}', getErrorMessageOrThrown(() => getErrorMessage(source.value))); state.message = rule.message.replace(
} '{0}',
else { getErrorMessageOrThrown(() => getErrorMessage(source.value)),
);
} else {
state.message = rule.message; state.message = rule.message;
} }
state.status = 'error'; state.status = 'error';
@@ -2,14 +2,14 @@ import type { Component } from 'vue';
import type { RouteLocationRaw } from 'vue-router'; import type { RouteLocationRaw } from 'vue-router';
export interface PaletteOption { export interface PaletteOption {
name: string name: string;
description?: string description?: string;
icon?: Component icon?: Component;
action?: () => void action?: () => void;
to?: RouteLocationRaw to?: RouteLocationRaw;
category: string category: string;
keywords?: string[] keywords?: string[];
href?: string href?: string;
closeOnSelect?: boolean closeOnSelect?: boolean;
externAccessDescription?: string externAccessDescription?: string;
} }
@@ -20,7 +20,16 @@ const { selected } = toRefs(props);
'text-white': selected, 'text-white': selected,
'bg-primary': selected, 'bg-primary': selected,
}" }"
w-full flex cursor-pointer items-center overflow-hidden rounded pa-3 transition hover:bg-primary hover:text-white w-full
flex
cursor-pointer
items-center
overflow-hidden
rounded
pa-3
transition
hover:bg-primary
hover:text-white
@click="() => emit('activated', option)" @click="() => emit('activated', option)"
> >
<component :is="option.icon" v-if="option.icon" mr-3 h-30px w-30px shrink-0 op-50 /> <component :is="option.icon" v-if="option.icon" mr-3 h-30px w-30px shrink-0 op-50 />
@@ -28,14 +37,8 @@ const { selected } = toRefs(props);
<div flex-1 overflow-hidden> <div flex-1 overflow-hidden>
<div truncate font-bold lh-tight op-90> <div truncate font-bold lh-tight op-90>
{{ option.name }} {{ option.name }}
<World <World v-if="option.externAccessDescription" class="tool-privacy-icon" />
v-if="option.externAccessDescription" <DeviceDesktop v-else class="tool-privacy-icon" />
class="tool-privacy-icon"
/>
<DeviceDesktop
v-else
class="tool-privacy-icon"
/>
</div> </div>
<div v-if="option.description" truncate lh-tight op-60> <div v-if="option.description" truncate lh-tight op-60>
@@ -48,6 +51,6 @@ const { selected } = toRefs(props);
<style lang="css" scoped> <style lang="css" scoped>
.tool-privacy-icon { .tool-privacy-icon {
display: inline-block; display: inline-block;
height: .9em; height: 0.9em;
} }
</style> </style>
+2 -2
View File
@@ -7,6 +7,6 @@ export type TrackerService = ReturnType<typeof createTrackerService>;
* and the tracker service are not tied to the tracking library currently in use. * and the tracker service are not tied to the tracking library currently in use.
*/ */
export interface PlausibleInstance { export interface PlausibleInstance {
trackEvent: (eventName: string) => void trackEvent: (eventName: string) => void;
enableAutoPageviews: () => void enableAutoPageviews: () => void;
} }
+11 -5
View File
@@ -13,7 +13,9 @@ const FALLBACK_LOCALE = 'en';
// only fetched the first time it becomes the active locale. // only fetched the first time it becomes the active locale.
const eagerToolMessages = import.meta.glob('../tools/*/locales/en.yml', { eager: true, import: 'default' }); const eagerToolMessages = import.meta.glob('../tools/*/locales/en.yml', { eager: true, import: 'default' });
const lazyBaseMessages = import.meta.glob(['../../locales/*.yml', '!../../locales/en.yml'], { import: 'default' }); const lazyBaseMessages = import.meta.glob(['../../locales/*.yml', '!../../locales/en.yml'], { import: 'default' });
const lazyToolMessages = import.meta.glob(['../tools/*/locales/*.yml', '!../tools/*/locales/en.yml'], { import: 'default' }); const lazyToolMessages = import.meta.glob(['../tools/*/locales/*.yml', '!../tools/*/locales/en.yml'], {
import: 'default',
});
function localeOfPath(path: string): string { function localeOfPath(path: string): string {
return path.replace(/^.*\/([^/]+)\.yml$/, '$1'); return path.replace(/^.*\/([^/]+)\.yml$/, '$1');
@@ -31,8 +33,8 @@ export const appLocales = (() => {
if (available === '*' || available === 'all') { if (available === '*' || available === 'all') {
return allLocales; return allLocales;
} }
const wantedLocales = available.split(',').map(locale => locale.trim()); const wantedLocales = available.split(',').map((locale) => locale.trim());
return allLocales.filter(locale => wantedLocales.includes(locale) || locale === FALLBACK_LOCALE); return allLocales.filter((locale) => wantedLocales.includes(locale) || locale === FALLBACK_LOCALE);
})(); })();
const i18n = createI18n({ const i18n = createI18n({
@@ -64,7 +66,7 @@ export async function loadLocaleMessages(locale: string) {
return; return;
} }
const messageParts = await Promise.all(loaders.map(loader => loader())); const messageParts = await Promise.all(loaders.map((loader) => loader()));
i18n.global.setLocaleMessage(locale, merge({}, ...messageParts)); i18n.global.setLocaleMessage(locale, merge({}, ...messageParts));
loadedLocales.add(locale); loadedLocales.add(locale);
} }
@@ -75,7 +77,11 @@ export const i18nPlugin: Plugin = {
// Messages arrive after the switch; vue-i18n falls back to English until // Messages arrive after the switch; vue-i18n falls back to English until
// setLocaleMessage triggers a reactive re-render. Watching through the getter // setLocaleMessage triggers a reactive re-render. Watching through the getter
// avoids depending on vue-i18n's locale ref generics. // avoids depending on vue-i18n's locale ref generics.
watch(() => getCurrentLocale(), locale => loadLocaleMessages(locale), { immediate: true }); watch(
() => getCurrentLocale(),
(locale) => loadLocaleMessages(locale),
{ immediate: true },
);
}, },
}; };
+6 -6
View File
@@ -18,11 +18,11 @@ export function createPlausibleInstance({
config, config,
}: { }: {
config: { config: {
isTrackerEnabled: boolean isTrackerEnabled: boolean;
domain: string domain: string;
apiHost: string apiHost: string;
trackLocalhost: boolean trackLocalhost: boolean;
} };
}): PlausibleInstance { }): PlausibleInstance {
// `init` throws when no domain is configured. Without a domain the events would be attributed to // `init` throws when no domain is configured. Without a domain the events would be attributed to
// nothing anyway, so stay with the no-op instance instead. // nothing anyway, so stay with the no-op instance instead.
@@ -46,7 +46,7 @@ export function createPlausibleInstance({
} }
return { return {
trackEvent: eventName => track(eventName, {}), trackEvent: (eventName) => track(eventName, {}),
// `init` already captures pageviews, `autoCapturePageviews` being enabled by default // `init` already captures pageviews, `autoCapturePageviews` being enabled by default
enableAutoPageviews: noop, enableAutoPageviews: noop,
}; };
+3 -4
View File
@@ -10,9 +10,8 @@ import { useAppTheme } from './ui/theme/themes';
// Conditional dynamic import: import.meta.env.DEV is statically false in production // Conditional dynamic import: import.meta.env.DEV is statically false in production
// builds, so the demo gallery (and everything it imports: c-markdown, markdown-it, …) // builds, so the demo gallery (and everything it imports: c-markdown, markdown-it, …)
// is dead-code-eliminated from the bundle instead of shipping in the entry graph. // is dead-code-eliminated from the bundle instead of shipping in the entry graph.
const demoRoutes = import.meta.env.DEV && config.app.env === 'development' const demoRoutes =
? (await import('./ui/demo/demo.routes')).routes import.meta.env.DEV && config.app.env === 'development' ? (await import('./ui/demo/demo.routes')).routes : [];
: [];
const $loading = useLoading(); const $loading = useLoading();
const toolsRoutes = tools.map(({ path, name, component, ...config }) => ({ const toolsRoutes = tools.map(({ path, name, component, ...config }) => ({
@@ -24,7 +23,7 @@ const toolsRoutes = tools.map(({ path, name, component, ...config }) => ({
const toolsRedirectRoutes = tools const toolsRedirectRoutes = tools
.filter(({ redirectFrom }) => redirectFrom && redirectFrom.length > 0) .filter(({ redirectFrom }) => redirectFrom && redirectFrom.length > 0)
.flatMap( .flatMap(
({ path, redirectFrom }) => redirectFrom?.map(redirectSource => ({ path: redirectSource, redirect: path })) ?? [], ({ path, redirectFrom }) => redirectFrom?.map((redirectSource) => ({ path: redirectSource, redirect: path })) ?? [],
); );
const router = createRouter({ const router = createRouter({
+13 -5
View File
@@ -17,15 +17,23 @@ export const useStyleStore = defineStore('style', {
const isSmallScreen = useMediaQuery('(max-width: 700px)'); const isSmallScreen = useMediaQuery('(max-width: 700px)');
const isMenuCollapsed = useITStorage('isMenuCollapsed', isSmallScreen.value) as Ref<boolean>; const isMenuCollapsed = useITStorage('isMenuCollapsed', isSmallScreen.value) as Ref<boolean>;
watch(isSmallScreen, v => (isMenuCollapsed.value = v)); watch(isSmallScreen, (v) => (isMenuCollapsed.value = v));
// Keep browser UI (iOS Safari chrome, PWA title bar) matching the app background // Keep browser UI (iOS Safari chrome, PWA title bar) matching the app background
watch(isDarkTheme, (isDark) => { watch(
isDarkTheme,
(isDark) => {
// Cast: naive-ui's Layout override type resolves to '{}' under // Cast: naive-ui's Layout override type resolves to '{}' under
// tsconfig.vitest.json, even though the value is a plain color string // tsconfig.vitest.json, even though the value is a plain color string
const themeColor = (isDark ? darkThemeOverrides.Layout?.color : lightThemeOverrides.Layout?.color) as string | undefined; const themeColor = (isDark ? darkThemeOverrides.Layout?.color : lightThemeOverrides.Layout?.color) as
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', themeColor ?? (isDark ? '#1c1c1c' : '#f1f5f9')); | string
}, { immediate: true }); | undefined;
document
.querySelector('meta[name="theme-color"]')
?.setAttribute('content', themeColor ?? (isDark ? '#1c1c1c' : '#f1f5f9'));
},
{ immediate: true },
);
return { return {
themeMode, themeMode,
+1 -1
View File
@@ -4,5 +4,5 @@ import { appBaseUrl as base } from '@/utils/base-url';
// fetch runs concurrently with the config fetches in src/tools/index.ts (sibling async // fetch runs concurrently with the config fetches in src/tools/index.ts (sibling async
// module subgraphs evaluate in parallel) instead of serially after them. // module subgraphs evaluate in parallel) instead of serially after them.
export const toolsSettings: Record<string, Record<string, any> | any> = await fetch(`${base}tools-settings.json`) export const toolsSettings: Record<string, Record<string, any> | any> = await fetch(`${base}tools-settings.json`)
.then(response => (response.ok ? response.json() as Promise<Record<string, Record<string, any> | any>> : {})) .then((response) => (response.ok ? (response.json() as Promise<Record<string, Record<string, any> | any>>) : {}))
.catch(() => ({})); .catch(() => ({}));
@@ -5,7 +5,10 @@ import UnitsConverter from '@/components/UnitsConverter.vue';
const supportedUnits = { const supportedUnits = {
'g-force': { value: 'g-force', label: t('tools.acceleration-converter.texts.label-g-force') }, 'g-force': { value: 'g-force', label: t('tools.acceleration-converter.texts.label-g-force') },
'm/s2': { value: 'meter per second squared', label: t('tools.acceleration-converter.texts.label-meter-per-second-squared') }, 'm/s2': {
value: 'meter per second squared',
label: t('tools.acceleration-converter.texts.label-meter-per-second-squared'),
},
}; };
</script> </script>
+1 -3
View File
@@ -5,9 +5,7 @@ export const tool = defineTool({
name: t('tools.acceleration-converter.title'), name: t('tools.acceleration-converter.title'),
path: '/acceleration-converter', path: '/acceleration-converter',
description: t('tools.acceleration-converter.description'), description: t('tools.acceleration-converter.description'),
keywords: ['acceleration', 'converter', keywords: ['acceleration', 'converter', 'units', 'g (g-force)', 'm/s2'],
'units', 'g (g-force)', 'm/s2',
],
component: () => import('./acceleration-converter.vue'), component: () => import('./acceleration-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Run')), icon: defineAsyncComponent(() => import('@vicons/tabler/es/Run')),
createdAt: new Date('2026-01-30'), createdAt: new Date('2026-01-30'),
@@ -24,7 +24,8 @@ const { searchResult } = useFlexSearch({
<c-input-text <c-input-text
v-model:value="search" v-model:value="search"
:placeholder="t('tools.ad-ldap-searcher.texts.placeholder-search-active-directory-ldap-mapping')" :placeholder="t('tools.ad-ldap-searcher.texts.placeholder-search-active-directory-ldap-mapping')"
mx-auto max-w-600px mx-auto
max-w-600px
> >
<template #prefix> <template #prefix>
<icon-mdi-search mr-6px color-black op-70 dark:color-white /> <icon-mdi-search mr-6px color-black op-70 dark:color-white />
@@ -33,11 +34,7 @@ const { searchResult } = useFlexSearch({
</div> </div>
<div> <div>
<div <div v-if="searchResult.length === 0" mt-4 text-center text-20px font-bold>
v-if="searchResult.length === 0"
mt-4 text-center text-20px font-bold
>
{{ t('tools.ad-ldap-searcher.texts.tag-no-results') }} {{ t('tools.ad-ldap-searcher.texts.tag-no-results') }}
</div> </div>
@@ -16,8 +16,7 @@ const splittedPrompts = computed(() => {
splitLength: splitLength.value, splitLength: splitLength.value,
newLine: true, newLine: true,
}); });
} } catch (e: any) {
catch (e: any) {
return [e.toString()]; return [e.toString()];
} }
}); });
@@ -26,7 +25,7 @@ const promptValidation = useValidation({
source: prompt, source: prompt,
rules: [ rules: [
{ {
validator: v => v !== '', validator: (v) => v !== '',
message: t('tools.ai-prompt-splitter.texts.message-prompt-must-not-be-empty'), message: t('tools.ai-prompt-splitter.texts.message-prompt-must-not-be-empty'),
}, },
], ],
+4 -4
View File
@@ -1,7 +1,7 @@
declare module "chatgpt-prompt-splitter" { declare module 'chatgpt-prompt-splitter' {
export default function promptSplitter(options: { export default function promptSplitter(options: {
prompt: string prompt: string;
splitLength: number splitLength: number;
newLine: boolean newLine: boolean;
}): Array<string>; }): Array<string>;
} }
@@ -301,8 +301,8 @@ describe('StandardAmortizationCalculator', () => {
// 60 months + 5 year summary rows = 65 total // 60 months + 5 year summary rows = 65 total
expect(schedule).toHaveLength(65); expect(schedule).toHaveLength(65);
const monthRows = schedule.filter(row => row.type === 'month'); const monthRows = schedule.filter((row) => row.type === 'month');
const yearRows = schedule.filter(row => row.type === 'year'); const yearRows = schedule.filter((row) => row.type === 'year');
expect(monthRows).toHaveLength(60); expect(monthRows).toHaveLength(60);
expect(yearRows).toHaveLength(5); expect(yearRows).toHaveLength(5);
@@ -331,7 +331,7 @@ describe('StandardAmortizationCalculator', () => {
const schedule = Array.from(calculator.getAmortizationSchedule(params)); const schedule = Array.from(calculator.getAmortizationSchedule(params));
// Filter to only month rows for balance comparison // Filter to only month rows for balance comparison
const monthRows = schedule.filter(row => row.type === 'month'); const monthRows = schedule.filter((row) => row.type === 'month');
for (let i = 1; i < monthRows.length; i++) { for (let i = 1; i < monthRows.length; i++) {
expect(monthRows[i].remainingBalance).toBeLessThan(monthRows[i - 1].remainingBalance); expect(monthRows[i].remainingBalance).toBeLessThan(monthRows[i - 1].remainingBalance);
@@ -346,7 +346,7 @@ describe('StandardAmortizationCalculator', () => {
}; };
const schedule = Array.from(calculator.getAmortizationSchedule(params)); const schedule = Array.from(calculator.getAmortizationSchedule(params));
const monthRows = schedule.filter(row => row.type === 'month'); const monthRows = schedule.filter((row) => row.type === 'month');
const lastMonthPayment = monthRows[monthRows.length - 1]; const lastMonthPayment = monthRows[monthRows.length - 1];
expect(lastMonthPayment.remainingBalance).toBeCloseTo(0, 0); expect(lastMonthPayment.remainingBalance).toBeCloseTo(0, 0);
@@ -376,7 +376,7 @@ describe('StandardAmortizationCalculator', () => {
}; };
const schedule = Array.from(calculator.getAmortizationSchedule(params)); const schedule = Array.from(calculator.getAmortizationSchedule(params));
const monthRows = schedule.filter(row => row.type === 'month'); const monthRows = schedule.filter((row) => row.type === 'month');
const firstPayment = monthRows[0].payment; const firstPayment = monthRows[0].payment;
monthRows.forEach((payment) => { monthRows.forEach((payment) => {
@@ -392,7 +392,7 @@ describe('StandardAmortizationCalculator', () => {
}; };
const schedule = Array.from(calculator.getAmortizationSchedule(params)); const schedule = Array.from(calculator.getAmortizationSchedule(params));
const yearRows = schedule.filter(row => row.type === 'year'); const yearRows = schedule.filter((row) => row.type === 'year');
expect(yearRows).toHaveLength(2); // 2 years expect(yearRows).toHaveLength(2); // 2 years
expect(yearRows[0].paymentIndex).toBe(1); // Year 1 expect(yearRows[0].paymentIndex).toBe(1); // Year 1
@@ -407,8 +407,8 @@ describe('StandardAmortizationCalculator', () => {
}; };
const schedule = Array.from(calculator.getAmortizationSchedule(params)); const schedule = Array.from(calculator.getAmortizationSchedule(params));
const monthRows = schedule.filter(row => row.type === 'month'); const monthRows = schedule.filter((row) => row.type === 'month');
const yearRows = schedule.filter(row => row.type === 'year'); const yearRows = schedule.filter((row) => row.type === 'year');
// Calculate cumulative totals for the year // Calculate cumulative totals for the year
const totalPrincipal = monthRows.reduce((sum, row) => sum + row.principalPayment, 0); const totalPrincipal = monthRows.reduce((sum, row) => sum + row.principalPayment, 0);
@@ -465,7 +465,7 @@ describe('StandardAmortizationCalculator', () => {
const schedule = Array.from(calculator.getAmortizationSchedule(params)); const schedule = Array.from(calculator.getAmortizationSchedule(params));
// 3 months, no year summary (< 12 months) // 3 months, no year summary (< 12 months)
expect(schedule).toHaveLength(3); expect(schedule).toHaveLength(3);
const monthRows = schedule.filter(row => row.type === 'month'); const monthRows = schedule.filter((row) => row.type === 'month');
expect(monthRows[2].remainingBalance).toBeCloseTo(0, 0); expect(monthRows[2].remainingBalance).toBeCloseTo(0, 0);
}); });
@@ -479,7 +479,7 @@ describe('StandardAmortizationCalculator', () => {
const schedule = Array.from(calculator.getAmortizationSchedule(params)); const schedule = Array.from(calculator.getAmortizationSchedule(params));
// 480 months + 40 year summary rows = 520 total // 480 months + 40 year summary rows = 520 total
expect(schedule).toHaveLength(520); expect(schedule).toHaveLength(520);
const monthRows = schedule.filter(row => row.type === 'month'); const monthRows = schedule.filter((row) => row.type === 'month');
expect(monthRows).toHaveLength(480); expect(monthRows).toHaveLength(480);
expect(monthRows[479].remainingBalance).toBeCloseTo(0, 0); expect(monthRows[479].remainingBalance).toBeCloseTo(0, 0);
}); });
@@ -1,23 +1,23 @@
export interface AmortizationParams { export interface AmortizationParams {
readonly principal: number readonly principal: number;
readonly periodInterestRate: number readonly periodInterestRate: number;
readonly numberOfPayments: number readonly numberOfPayments: number;
} }
export interface CachedPaymentResults { export interface CachedPaymentResults {
readonly payment: number readonly payment: number;
readonly totalPayments: number readonly totalPayments: number;
} }
export interface GetNthResult extends CachedPaymentResults { export interface GetNthResult extends CachedPaymentResults {
readonly paymentIndex: number readonly paymentIndex: number;
readonly principalPayment: number readonly principalPayment: number;
readonly interestPayment: number readonly interestPayment: number;
readonly remainingBalance: number readonly remainingBalance: number;
} }
export interface AmortizationScheduleItem extends GetNthResult { export interface AmortizationScheduleItem extends GetNthResult {
readonly type: 'month' | 'year' readonly type: 'month' | 'year';
} }
type AmortizationPaymentCacheKey = `principal:${number};interest-rate:${number};number-of-payments:${number}`; type AmortizationPaymentCacheKey = `principal:${number};interest-rate:${number};number-of-payments:${number}`;
@@ -162,8 +162,8 @@ export class StandardAmortizationCalculator extends AmortizationCalculator {
const r = 1 + periodInterestRate; const r = 1 + periodInterestRate;
const balanceBeforePayment const balanceBeforePayment =
= principal * r ** (paymentIndex - 1) - payment * ((r ** (paymentIndex - 1) - 1) / periodInterestRate); principal * r ** (paymentIndex - 1) - payment * ((r ** (paymentIndex - 1) - 1) / periodInterestRate);
const interestPayment = balanceBeforePayment * periodInterestRate; const interestPayment = balanceBeforePayment * periodInterestRate;
+1 -3
View File
@@ -5,9 +5,7 @@ export const tool = defineTool({
name: t('tools.angle-converter.title'), name: t('tools.angle-converter.title'),
path: '/angle-converter', path: '/angle-converter',
description: t('tools.angle-converter.description'), description: t('tools.angle-converter.description'),
keywords: ['angle', 'converter', keywords: ['angle', 'converter', 'units', 'degree', 'radian', 'turn', 'grad'],
'units', 'degree', 'radian', 'turn', 'grad',
],
component: () => import('./angle-converter.vue'), component: () => import('./angle-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Angle')), icon: defineAsyncComponent(() => import('@vicons/tabler/es/Angle')),
createdAt: new Date('2024-08-15'), createdAt: new Date('2024-08-15'),
@@ -1,9 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { onMounted, ref } from 'vue'; import { onMounted, ref } from 'vue';
import { import { NButton, NCheckbox, NCheckboxGroup, NInput } from 'naive-ui';
NButton, NCheckbox, NCheckboxGroup, NInput,
} from 'naive-ui';
import { Terminal } from '@xterm/xterm'; import { Terminal } from '@xterm/xterm';
import '@xterm/xterm/css/xterm.css'; import '@xterm/xterm/css/xterm.css';
import styles from 'ansi-styles'; import styles from 'ansi-styles';
@@ -27,11 +25,9 @@ const outputEscapeSequence = computed(() => {
if (foregroundColor.value) { if (foregroundColor.value) {
if (colorMode.value === 'basic') { if (colorMode.value === 'basic') {
openSeq += styles.color.ansi(styles.hexToAnsi(foregroundColor.value)); openSeq += styles.color.ansi(styles.hexToAnsi(foregroundColor.value));
} } else if (colorMode.value === '256') {
else if (colorMode.value === '256') {
openSeq += styles.color.ansi256(styles.hexToAnsi256(foregroundColor.value)); openSeq += styles.color.ansi256(styles.hexToAnsi256(foregroundColor.value));
} } else {
else {
openSeq += styles.color.ansi16m(...styles.hexToRgb(foregroundColor.value)); openSeq += styles.color.ansi16m(...styles.hexToRgb(foregroundColor.value));
} }
closeSeq = styles.color.close + closeSeq; closeSeq = styles.color.close + closeSeq;
@@ -39,11 +35,9 @@ const outputEscapeSequence = computed(() => {
if (backgroundColor.value) { if (backgroundColor.value) {
if (colorMode.value === 'basic') { if (colorMode.value === 'basic') {
openSeq += styles.bgColor.ansi(styles.hexToAnsi(backgroundColor.value)); openSeq += styles.bgColor.ansi(styles.hexToAnsi(backgroundColor.value));
} } else if (colorMode.value === '256') {
else if (colorMode.value === '256') {
openSeq += styles.bgColor.ansi256(styles.hexToAnsi256(backgroundColor.value)); openSeq += styles.bgColor.ansi256(styles.hexToAnsi256(backgroundColor.value));
} } else {
else {
openSeq += styles.bgColor.ansi16m(...styles.hexToRgb(backgroundColor.value)); openSeq += styles.bgColor.ansi16m(...styles.hexToRgb(backgroundColor.value));
} }
closeSeq = styles.bgColor.close + closeSeq; closeSeq = styles.bgColor.close + closeSeq;
@@ -75,7 +69,7 @@ onMounted(() => {
writeTermAndScrollBottom(outputEscapeSequence.value); writeTermAndScrollBottom(outputEscapeSequence.value);
}); });
watch(outputEscapeSequence, seq => writeTermAndScrollBottom(seq), { immediate: true }); watch(outputEscapeSequence, (seq) => writeTermAndScrollBottom(seq), { immediate: true });
const escapeSequenceToTest = useQueryParam({ tool: 'ansi', name: 'seq', defaultValue: '' }); const escapeSequenceToTest = useQueryParam({ tool: 'ansi', name: 'seq', defaultValue: '' });
</script> </script>
@@ -142,7 +136,10 @@ const escapeSequenceToTest = useQueryParam({ tool: 'ansi', name: 'seq', defaultV
</c-card> </c-card>
<c-card :title="t('tools.ansi-escape-tester.texts.title-terminal-preview')"> <c-card :title="t('tools.ansi-escape-tester.texts.title-terminal-preview')">
<n-form-item label-placement="left" :label="t('tools.ansi-escape-tester.texts.label-custom-ansi-sequence')"> <n-form-item label-placement="left" :label="t('tools.ansi-escape-tester.texts.label-custom-ansi-sequence')">
<NInput v-model:value="escapeSequenceToTest" :placeholder="t('tools.ansi-escape-tester.texts.placeholder-enter-ansi-escape-sequence')" /> <NInput
v-model:value="escapeSequenceToTest"
:placeholder="t('tools.ansi-escape-tester.texts.placeholder-enter-ansi-escape-sequence')"
/>
<NButton type="primary" ml-1 @click="term?.writeln(escapeSequenceToTest)"> <NButton type="primary" ml-1 @click="term?.writeln(escapeSequenceToTest)">
{{ t('tools.ansi-escape-tester.texts.tag-test') }} {{ t('tools.ansi-escape-tester.texts.tag-test') }}
</NButton> </NButton>
@@ -8,32 +8,26 @@ const { t } = useI18n();
const decryptedInput = ref(''); const decryptedInput = ref('');
const encryptPassword = ref(''); const encryptPassword = ref('');
const encryptId = ref(''); const encryptId = ref('');
const cryptedOutput = computedAsync( const cryptedOutput = computedAsync(async () => {
async () => {
try { try {
const v = new Vault({ password: encryptPassword.value }); const v = new Vault({ password: encryptPassword.value });
return await v.encrypt(decryptedInput.value, encryptId.value); return await v.encrypt(decryptedInput.value, encryptId.value);
} } catch (e: any) {
catch (e: any) {
return e.toString(); return e.toString();
} }
}, });
);
const cryptedInput = ref(''); const cryptedInput = ref('');
const decryptPassword = ref(''); const decryptPassword = ref('');
const decryptedOutput = computedAsync( const decryptedOutput = computedAsync(async () => {
async () => {
try { try {
const v = new Vault({ password: decryptPassword.value }); const v = new Vault({ password: decryptPassword.value });
// handle mac \r // handle mac \r
return (await v.decrypt(cryptedInput.value?.replace(/\r(?!\n)/, '\n'), undefined)) ?? ''; return (await v.decrypt(cryptedInput.value?.replace(/\r(?!\n)/, '\n'), undefined)) ?? '';
} } catch (e: any) {
catch (e: any) {
return e.toString(); return e.toString();
} }
}, });
);
</script> </script>
<template> <template>
@@ -80,7 +74,9 @@ const decryptedOutput = computedAsync(
v-model:value="cryptedInput" v-model:value="cryptedInput"
:placeholder="t('tools.ansible-vault-crypt-decrypt.texts.placeholder-put-your-encrypted-string-here')" :placeholder="t('tools.ansible-vault-crypt-decrypt.texts.placeholder-put-your-encrypted-string-here')"
:label="t('tools.ansible-vault-crypt-decrypt.texts.label-string-to-decrypt')" :label="t('tools.ansible-vault-crypt-decrypt.texts.label-string-to-decrypt')"
raw-text multiline mb-5 raw-text
multiline
mb-5
rows="5" rows="5"
/> />
+55 -22
View File
@@ -6,14 +6,26 @@ import TextareaCopyable from '@/components/TextareaCopyable.vue';
const { t } = useI18n(); const { t } = useI18n();
interface KeyValuePair { interface KeyValuePair {
key: string key: string;
value?: string value?: string;
} }
const baseUrl = useQueryParamOrStorage({ name: 'url', storageName: 'api-tester:url', defaultValue: '' }); const baseUrl = useQueryParamOrStorage({ name: 'url', storageName: 'api-tester:url', defaultValue: '' });
const method = useQueryParamOrStorage({ name: 'method', storageName: 'api-tester:m', defaultValue: 'POST' }); const method = useQueryParamOrStorage({ name: 'method', storageName: 'api-tester:m', defaultValue: 'POST' });
const queryParams = useQueryParamOrStorage<KeyValuePair[]>({ name: 'params', storageName: 'api-tester:params', defaultValue: [] }); const queryParams = useQueryParamOrStorage<KeyValuePair[]>({
const headers = useQueryParamOrStorage<KeyValuePair[]>({ name: 'headers', storageName: 'api-tester:headers', defaultValue: [] }); name: 'params',
const contentType = useQueryParamOrStorage({ name: 'ct', storageName: 'api-tester:ct', defaultValue: 'application/json' }); storageName: 'api-tester:params',
defaultValue: [],
});
const headers = useQueryParamOrStorage<KeyValuePair[]>({
name: 'headers',
storageName: 'api-tester:headers',
defaultValue: [],
});
const contentType = useQueryParamOrStorage({
name: 'ct',
storageName: 'api-tester:ct',
defaultValue: 'application/json',
});
const body = useQueryParamOrStorage({ name: 'body', storageName: 'api-tester:body', defaultValue: '' }); const body = useQueryParamOrStorage({ name: 'body', storageName: 'api-tester:body', defaultValue: '' });
const noCORS = ref(false); const noCORS = ref(false);
const apiCallResult = ref(); const apiCallResult = ref();
@@ -40,23 +52,20 @@ async function callAPI() {
const response = await fetch(url, { const response = await fetch(url, {
method: method.value, method: method.value,
headers: queryHeaders, headers: queryHeaders,
body: (method.value === 'GET' || method.value === 'HEAD') ? null : body.value, body: method.value === 'GET' || method.value === 'HEAD' ? null : body.value,
mode: noCORS.value ? 'no-cors' : 'cors', mode: noCORS.value ? 'no-cors' : 'cors',
}); });
let responseText = await response.text(); let responseText = await response.text();
try { try {
responseText = JSON.stringify(JSON.parse(responseText), null, 2); responseText = JSON.stringify(JSON.parse(responseText), null, 2);
} } catch (_) {}
catch (_) {
}
apiCallResult.value = { apiCallResult.value = {
code: response.status, code: response.status,
error: '', error: '',
result: responseText, result: responseText,
}; };
} } catch (err: any) {
catch (err: any) {
apiCallResult.value = { apiCallResult.value = {
code: -1, code: -1,
error: err.toString(), error: err.toString(),
@@ -97,8 +106,16 @@ function emptyKeyPair() {
</template> </template>
<template #default="{ value }"> <template #default="{ value }">
<div v-if="value" w-100 flex justify-center gap-2> <div v-if="value" w-100 flex justify-center gap-2>
<c-input-text v-model:value="value.key" :placeholder="t('tools.api-tester.texts.placeholder-header-name')" type="text" /> <c-input-text
<c-input-text v-model:value="value.value" :placeholder="t('tools.api-tester.texts.placeholder-value')" type="text" /> v-model:value="value.key"
:placeholder="t('tools.api-tester.texts.placeholder-header-name')"
type="text"
/>
<c-input-text
v-model:value="value.value"
:placeholder="t('tools.api-tester.texts.placeholder-value')"
type="text"
/>
</div> </div>
</template> </template>
</n-dynamic-input> </n-dynamic-input>
@@ -117,8 +134,16 @@ function emptyKeyPair() {
</template> </template>
<template #default="{ value }"> <template #default="{ value }">
<div v-if="value" w-100 flex justify-center gap-2> <div v-if="value" w-100 flex justify-center gap-2>
<c-input-text v-model:value="value.key" :placeholder="t('tools.api-tester.texts.placeholder-param-name')" type="text" /> <c-input-text
<c-input-text v-model:value="value.value" :placeholder="t('tools.api-tester.texts.placeholder-value')" type="text" /> v-model:value="value.key"
:placeholder="t('tools.api-tester.texts.placeholder-param-name')"
type="text"
/>
<c-input-text
v-model:value="value.value"
:placeholder="t('tools.api-tester.texts.placeholder-value')"
type="text"
/>
</div> </div>
</template> </template>
</n-dynamic-input> </n-dynamic-input>
@@ -143,15 +168,23 @@ function emptyKeyPair() {
</c-button> </c-button>
</div> </div>
</c-card> </c-card>
<n-spin <n-spin v-if="inprogress" size="small" />
v-if="inprogress" <c-alert
size="small" v-if="!inprogress && apiCallResult && apiCallResult.code !== 200"
/> type="error"
<c-alert v-if="!inprogress && apiCallResult && apiCallResult.code !== 200" type="error" mt-12 :title="t('tools.api-tester.texts.title-error-while-calling-api')"> mt-12
<p><strong>Status code = {{ apiCallResult.code }}</strong></p> :title="t('tools.api-tester.texts.title-error-while-calling-api')"
>
<p>
<strong>Status code = {{ apiCallResult.code }}</strong>
</p>
<TextareaCopyable :value="apiCallResult.error" copy-placement="none" /> <TextareaCopyable :value="apiCallResult.error" copy-placement="none" />
</c-alert> </c-alert>
<c-card v-if="!inprogress && apiCallResult && apiCallResult.code === 200" mt-12 :title="t('tools.api-tester.texts.title-api-call-result')"> <c-card
v-if="!inprogress && apiCallResult && apiCallResult.code === 200"
mt-12
:title="t('tools.api-tester.texts.title-api-call-result')"
>
<TextareaCopyable :value="apiCallResult.result" word-wrap /> <TextareaCopyable :value="apiCallResult.result" word-wrap />
</c-card> </c-card>
</div> </div>
+1 -3
View File
@@ -5,9 +5,7 @@ export const tool = defineTool({
name: t('tools.area-converter.title'), name: t('tools.area-converter.title'),
path: '/area-converter', path: '/area-converter',
description: t('tools.area-converter.description'), description: t('tools.area-converter.description'),
keywords: ['area', 'converter', keywords: ['area', 'converter', 'units', 'square meter', 'are', 'square'],
'units', 'square meter', 'are', 'square',
],
component: () => import('./area-converter.vue'), component: () => import('./area-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/SquaresDiagonal')), icon: defineAsyncComponent(() => import('@vicons/tabler/es/SquaresDiagonal')),
createdAt: new Date('2024-08-15'), createdAt: new Date('2024-08-15'),
+16 -12
View File
@@ -7,7 +7,11 @@ const { t } = useI18n();
// Inputs // Inputs
const password = ref(''); const password = ref('');
const algorithm = useQueryParamOrStorage<'argon2id' | 'argon2i' | 'argon2d'>({ name: 'algo', storageName: 'argon2:a', defaultValue: 'argon2id' }); const algorithm = useQueryParamOrStorage<'argon2id' | 'argon2i' | 'argon2d'>({
name: 'algo',
storageName: 'argon2:a',
defaultValue: 'argon2id',
});
// Parameters // Parameters
const salt = useQueryParamOrStorage({ name: 'salt', storageName: 'argon2:s', defaultValue: '' }); const salt = useQueryParamOrStorage({ name: 'salt', storageName: 'argon2:s', defaultValue: '' });
@@ -15,7 +19,11 @@ const iterations = useQueryParamOrStorage({ name: 'iter', storageName: 'argon2:i
const memorySizeKB = useQueryParamOrStorage({ name: 'memory', storageName: 'argon2:m', defaultValue: 512 }); const memorySizeKB = useQueryParamOrStorage({ name: 'memory', storageName: 'argon2:m', defaultValue: 512 });
const parallelism = useQueryParamOrStorage({ name: 'paral', storageName: 'argon2:p', defaultValue: 1 }); const parallelism = useQueryParamOrStorage({ name: 'paral', storageName: 'argon2:p', defaultValue: 1 });
const hashLength = useQueryParamOrStorage({ name: 'len', storageName: 'argon2:l', defaultValue: 32 }); const hashLength = useQueryParamOrStorage({ name: 'len', storageName: 'argon2:l', defaultValue: 32 });
const outputType = useQueryParamOrStorage<'hex' | 'encoded' | 'binary'>({ name: 'output', storageName: 'argon2:o', defaultValue: 'encoded' }); const outputType = useQueryParamOrStorage<'hex' | 'encoded' | 'binary'>({
name: 'output',
storageName: 'argon2:o',
defaultValue: 'encoded',
});
// Result // Result
const result = ref(''); const result = ref('');
@@ -45,16 +53,10 @@ async function generateHash() {
outputType: outputType.value, outputType: outputType.value,
} as const; } as const;
const fn const fn = algorithm.value === 'argon2id' ? argon2id : algorithm.value === 'argon2i' ? argon2i : argon2d;
= algorithm.value === 'argon2id'
? argon2id
: algorithm.value === 'argon2i'
? argon2i
: argon2d;
result.value = await fn(options); result.value = await fn(options);
} } catch (err: any) {
catch (err: any) {
error.value = err.toString(); error.value = err.toString();
} }
} }
@@ -65,7 +67,8 @@ async function generateHash() {
<NForm label-width="120" label-placement="left"> <NForm label-width="120" label-placement="left">
<NFormItem :label="t('tools.argon2-hash.texts.label-algorithm')"> <NFormItem :label="t('tools.argon2-hash.texts.label-algorithm')">
<NSelect <NSelect
v-model:value="algorithm" :options="[ v-model:value="algorithm"
:options="[
{ label: t('tools.argon2-hash.texts.label-argon2id'), value: 'argon2id' }, { label: t('tools.argon2-hash.texts.label-argon2id'), value: 'argon2id' },
{ label: t('tools.argon2-hash.texts.label-argon2i'), value: 'argon2i' }, { label: t('tools.argon2-hash.texts.label-argon2i'), value: 'argon2i' },
{ label: t('tools.argon2-hash.texts.label-argon2d'), value: 'argon2d' }, { label: t('tools.argon2-hash.texts.label-argon2d'), value: 'argon2d' },
@@ -101,7 +104,8 @@ async function generateHash() {
<NFormItem :label="t('tools.argon2-hash.texts.label-output-type')"> <NFormItem :label="t('tools.argon2-hash.texts.label-output-type')">
<NSelect <NSelect
v-model:value="outputType" :options="[ v-model:value="outputType"
:options="[
{ label: t('tools.argon2-hash.texts.label-hex'), value: 'hex' }, { label: t('tools.argon2-hash.texts.label-hex'), value: 'hex' },
{ label: t('tools.argon2-hash.texts.label-encoded'), value: 'encoded' }, { label: t('tools.argon2-hash.texts.label-encoded'), value: 'encoded' },
{ label: t('tools.argon2-hash.texts.label-binary'), value: 'binary' }, { label: t('tools.argon2-hash.texts.label-binary'), value: 'binary' },
+5 -3
View File
@@ -9,8 +9,7 @@ const arpaInput = ref('');
const decodedIP = computed(() => { const decodedIP = computed(() => {
try { try {
return fromARPA(arpaInput.value.trim()); return fromARPA(arpaInput.value.trim());
} } catch (e: any) {
catch (e: any) {
return `# ${e.toString()}`; return `# ${e.toString()}`;
} }
}); });
@@ -19,7 +18,10 @@ const decodedIP = computed(() => {
<template> <template>
<div> <div>
<NFormItem :label="t('tools.arpa-decoder.texts.label-arpa-address')" label-placement="left" mb-2> <NFormItem :label="t('tools.arpa-decoder.texts.label-arpa-address')" label-placement="left" mb-2>
<NInput v-model:value="arpaInput" :placeholder="t('tools.arpa-decoder.texts.placeholder-e-g-10-1-168-192-in-addr-arpa-or-xxxx-ip6-arpa')" /> <NInput
v-model:value="arpaInput"
:placeholder="t('tools.arpa-decoder.texts.placeholder-e-g-10-1-168-192-in-addr-arpa-or-xxxx-ip6-arpa')"
/>
</NFormItem> </NFormItem>
<c-card v-if="decodedIP"> <c-card v-if="decodedIP">
@@ -1,13 +1,13 @@
// aspect-ratio-calculator.service.ts // aspect-ratio-calculator.service.ts
export interface AspectRatio { export interface AspectRatio {
r1: number r1: number;
r2: number r2: number;
} }
export interface Dimensions { export interface Dimensions {
width: number width: number;
height: number height: number;
} }
export function calculateAspectRatio(width: number, height: number): AspectRatio { export function calculateAspectRatio(width: number, height: number): AspectRatio {
@@ -19,16 +19,11 @@ export function calculateAspectRatio(width: number, height: number): AspectRatio
}; };
} }
export function calculateDimensions( export function calculateDimensions(knownDimension: number, ratio: AspectRatio, isWidth: boolean): Dimensions {
knownDimension: number,
ratio: AspectRatio,
isWidth: boolean,
): Dimensions {
if (isWidth) { if (isWidth) {
const height = Math.round((knownDimension * ratio.r2) / ratio.r1); const height = Math.round((knownDimension * ratio.r2) / ratio.r1);
return { width: knownDimension, height }; return { width: knownDimension, height };
} } else {
else {
const width = Math.round((knownDimension * ratio.r1) / ratio.r2); const width = Math.round((knownDimension * ratio.r1) / ratio.r2);
return { width, height: knownDimension }; return { width, height: knownDimension };
} }
@@ -3,10 +3,7 @@
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ref } from 'vue'; import { ref } from 'vue';
import { NButton, NRadio, NRadioGroup, NSpace } from 'naive-ui'; import { NButton, NRadio, NRadioGroup, NSpace } from 'naive-ui';
import { import { calculateAspectRatio, calculateDimensions } from './aspect-ratio-calculator.service';
calculateAspectRatio,
calculateDimensions,
} from './aspect-ratio-calculator.service';
const { t } = useI18n(); const { t } = useI18n();
@@ -22,37 +19,30 @@ function calculateResult() {
const ratio = calculateAspectRatio(width.value, height.value); const ratio = calculateAspectRatio(width.value, height.value);
if (r2.value) { if (r2.value) {
r1.value = ratio.r1 / ratio.r2; r1.value = ratio.r1 / ratio.r2;
} } else if (r1.value) {
else if (r1.value) {
r2.value = ratio.r2 / ratio.r1; r2.value = ratio.r2 / ratio.r1;
} } else {
else {
r1.value = ratio.r1; r1.value = ratio.r1;
r2.value = ratio.r2; r2.value = ratio.r2;
} }
if (ratio.r1 !== r1.value) { if (ratio.r1 !== r1.value) {
result.value = `Aspect Ratio: ${r1.value}:${r2.value} or ${ratio.r1}:${ratio.r2}`; result.value = `Aspect Ratio: ${r1.value}:${r2.value} or ${ratio.r1}:${ratio.r2}`;
} } else {
else {
result.value = `Aspect Ratio: ${ratio.r1}:${ratio.r2}`; result.value = `Aspect Ratio: ${ratio.r1}:${ratio.r2}`;
} }
} } else if (mode.value === 'dimensions' && r1.value && r2.value) {
else if (mode.value === 'dimensions' && r1.value && r2.value) {
if (width.value) { if (width.value) {
const dimensions = calculateDimensions(width.value, { r1: r1.value, r2: r2.value }, true); const dimensions = calculateDimensions(width.value, { r1: r1.value, r2: r2.value }, true);
height.value = dimensions.height; height.value = dimensions.height;
result.value = `Dimensions: ${dimensions.width}x${dimensions.height}`; result.value = `Dimensions: ${dimensions.width}x${dimensions.height}`;
} } else if (height.value) {
else if (height.value) {
const dimensions = calculateDimensions(height.value, { r1: r1.value, r2: r2.value }, false); const dimensions = calculateDimensions(height.value, { r1: r1.value, r2: r2.value }, false);
width.value = dimensions.width; width.value = dimensions.width;
result.value = `Dimensions: ${dimensions.width}x${dimensions.height}`; result.value = `Dimensions: ${dimensions.width}x${dimensions.height}`;
} } else {
else {
result.value = 'Please enter either width or height to calculate dimensions'; result.value = 'Please enter either width or height to calculate dimensions';
} }
} } else {
else {
result.value = 'Please fill in the required fields'; result.value = 'Please fill in the required fields';
} }
} }
@@ -85,25 +75,41 @@ function clearRatio() {
<div class="input-group"> <div class="input-group">
<div class="input-pair"> <div class="input-pair">
<label>{{ t('tools.aspect-ratio-calculator.texts.tag-pixels-width') }}</label> <label>{{ t('tools.aspect-ratio-calculator.texts.tag-pixels-width') }}</label>
<n-input-number-i18n v-model:value="width" :placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-pixels-width')" :min="1" /> <n-input-number-i18n
v-model:value="width"
:placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-pixels-width')"
:min="1"
/>
</div> </div>
<div class="input-pair"> <div class="input-pair">
<label>{{ t('tools.aspect-ratio-calculator.texts.tag-pixels-height') }}</label> <label>{{ t('tools.aspect-ratio-calculator.texts.tag-pixels-height') }}</label>
<n-input-number-i18n v-model:value="height" :placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-pixels-height')" :min="1" /> <n-input-number-i18n
v-model:value="height"
:placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-pixels-height')"
:min="1"
/>
</div> </div>
</div> </div>
<div class="input-group"> <div class="input-group">
<div class="input-pair"> <div class="input-pair">
<label>{{ t('tools.aspect-ratio-calculator.texts.tag-ratio-width') }}</label> <label>{{ t('tools.aspect-ratio-calculator.texts.tag-ratio-width') }}</label>
<n-input-number-i18n v-model:value="r1" :placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-ratio-width')" :min="1" /> <n-input-number-i18n
v-model:value="r1"
:placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-ratio-width')"
:min="1"
/>
</div> </div>
<div class="separator"> <div class="separator">
{{ t('tools.aspect-ratio-calculator.texts.tag-') }} {{ t('tools.aspect-ratio-calculator.texts.tag-') }}
</div> </div>
<div class="input-pair"> <div class="input-pair">
<label>{{ t('tools.aspect-ratio-calculator.texts.tag-ratio-height') }}</label> <label>{{ t('tools.aspect-ratio-calculator.texts.tag-ratio-height') }}</label>
<n-input-number-i18n v-model:value="r2" :placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-ratio-height')" :min="1" /> <n-input-number-i18n
v-model:value="r2"
:placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-ratio-height')"
:min="1"
/>
</div> </div>
</div> </div>
@@ -14,7 +14,11 @@ const scale = useQueryParamOrStorage({ name: 'scale', storageName: 'barcode-gen:
const height = useQueryParamOrStorage({ name: 'height', storageName: 'barcode-gen:height', defaultValue: 25 }); const height = useQueryParamOrStorage({ name: 'height', storageName: 'barcode-gen:height', defaultValue: 25 });
const margin = useQueryParamOrStorage({ name: 'margin', storageName: 'barcode-gen:margin', defaultValue: 10 }); const margin = useQueryParamOrStorage({ name: 'margin', storageName: 'barcode-gen:margin', defaultValue: 10 });
const format = useQueryParamOrStorage({ name: 'format', storageName: 'barcode-gen:format', defaultValue: 'code128' }); const format = useQueryParamOrStorage({ name: 'format', storageName: 'barcode-gen:format', defaultValue: 'code128' });
const displayValue = useQueryParamOrStorage({ name: 'display', storageName: 'barcode-gen:display', defaultValue: true }); const displayValue = useQueryParamOrStorage({
name: 'display',
storageName: 'barcode-gen:display',
defaultValue: true,
});
const value = useQueryParam({ tool: 'barcode-gen', name: 'text', defaultValue: '123456789' }); const value = useQueryParam({ tool: 'barcode-gen', name: 'text', defaultValue: '123456789' });
const barcodeCanvas = ref<HTMLCanvasElement>(); const barcodeCanvas = ref<HTMLCanvasElement>();
@@ -39,8 +43,7 @@ watchEffect(() => {
try { try {
bwipjs.toCanvas(barcodeCanvas.value, options.value); bwipjs.toCanvas(barcodeCanvas.value, options.value);
} } catch (e: any) {
catch (e: any) {
error.value = e.toString(); error.value = e.toString();
} }
}); });
@@ -51,8 +54,7 @@ const barcodePNG = computed(() => {
const barcodeSVG = computed(() => { const barcodeSVG = computed(() => {
try { try {
return Base64.encode(bwipjs.toSVG(options.value)); return Base64.encode(bwipjs.toSVG(options.value));
} } catch (e: any) {
catch (e: any) {
return ''; return '';
} }
}); });
+6 -8
View File
@@ -12,10 +12,9 @@ const barCode = computedAsync(async () => {
} }
try { try {
const barcodeReader = new BrowserMultiFormatReader(); const barcodeReader = new BrowserMultiFormatReader();
const result = (await barcodeReader.decodeFromImageUrl(imageBase64.value)); const result = await barcodeReader.decodeFromImageUrl(imageBase64.value);
return { text: result.getText(), format: BarcodeFormat[result.getBarcodeFormat()], error: '' }; return { text: result.getText(), format: BarcodeFormat[result.getBarcodeFormat()], error: '' };
} } catch (e: any) {
catch (e: any) {
return { error: e.toString(), text: '', format: '' }; return { error: e.toString(), text: '', format: '' };
} }
}); });
@@ -50,11 +49,10 @@ async function onUpload(file: File) {
<div v-if="barCode?.text"> <div v-if="barCode?.text">
<n-divider /> <n-divider />
<h3>{{ t('tools.barcode-reader.texts.tag-decoded') }}<span v-if="barCode?.format">({{ barCode?.format }})</span></h3> <h3>
<TextareaCopyable {{ t('tools.barcode-reader.texts.tag-decoded') }}<span v-if="barCode?.format">({{ barCode?.format }})</span>
:value="barCode?.text" </h3>
:word-wrap="true" <TextareaCopyable :value="barCode?.text" :word-wrap="true" />
/>
</div> </div>
<c-alert v-if="barCode?.error"> <c-alert v-if="barCode?.error">
{{ barCode?.error }} {{ barCode?.error }}
@@ -3,7 +3,12 @@ import { useI18n } from 'vue-i18n';
import { useBase64 } from '@vueuse/core'; import { useBase64 } from '@vueuse/core';
import type { Ref } from 'vue'; import type { Ref } from 'vue';
import { useCopy } from '@/composable/copy'; import { useCopy } from '@/composable/copy';
import { getExtensionFromMimeType, getMimeTypeFromBase64, previewImageFromBase64, useDownloadFileFromBase64Refs } from '@/composable/downloadBase64'; import {
getExtensionFromMimeType,
getMimeTypeFromBase64,
previewImageFromBase64,
useDownloadFileFromBase64Refs,
} from '@/composable/downloadBase64';
import { useValidation } from '@/composable/validation'; import { useValidation } from '@/composable/validation';
import { isValidBase64 } from '@/utils/base64'; import { isValidBase64 } from '@/utils/base64';
@@ -12,8 +17,7 @@ const { t } = useI18n();
const fileName = ref('file'); const fileName = ref('file');
const fileExtension = ref(''); const fileExtension = ref('');
const base64Input = ref(''); const base64Input = ref('');
const { download } = useDownloadFileFromBase64Refs( const { download } = useDownloadFileFromBase64Refs({
{
source: base64Input, source: base64Input,
filename: fileName, filename: fileName,
extension: fileExtension, extension: fileExtension,
@@ -23,20 +27,17 @@ const base64InputValidation = useValidation({
rules: [ rules: [
{ {
message: t('tools.base64-file-converter.texts.message-invalid-base-64-string'), message: t('tools.base64-file-converter.texts.message-invalid-base-64-string'),
validator: value => isValidBase64(value.trim()), validator: (value) => isValidBase64(value.trim()),
}, },
], ],
}); });
watch( watch(base64Input, (newValue, _) => {
base64Input,
(newValue, _) => {
const { mimeType } = getMimeTypeFromBase64({ base64String: newValue }); const { mimeType } = getMimeTypeFromBase64({ base64String: newValue });
if (mimeType) { if (mimeType) {
fileExtension.value = getExtensionFromMimeType(mimeType) || fileExtension.value; fileExtension.value = getExtensionFromMimeType(mimeType) || fileExtension.value;
} }
}, });
);
function previewImage() { function previewImage() {
if (!base64InputValidation.isValid) { if (!base64InputValidation.isValid) {
@@ -51,8 +52,7 @@ function previewImage() {
previewContainer.innerHTML = ''; previewContainer.innerHTML = '';
previewContainer.appendChild(image); previewContainer.appendChild(image);
} }
} } catch (_) {
catch (_) {
// //
} }
} }
@@ -64,8 +64,7 @@ function downloadFile() {
try { try {
download(); download();
} } catch (_) {
catch (_) {
// //
} }
} }
@@ -79,7 +78,10 @@ const cleanedFileBase64 = computed(() => {
} }
return fileBase64.value.replace(/^data:[^;]*;base64,/, ''); return fileBase64.value.replace(/^data:[^;]*;base64,/, '');
}); });
const { copy: copyFileBase64 } = useCopy({ source: cleanedFileBase64, text: t('tools.base64-file-converter.texts.text-base64-string-copied-to-the-clipboard') }); const { copy: copyFileBase64 } = useCopy({
source: cleanedFileBase64,
text: t('tools.base64-file-converter.texts.text-base64-string-copied-to-the-clipboard'),
});
async function onUpload(file: File) { async function onUpload(file: File) {
if (file) { if (file) {
@@ -145,7 +147,14 @@ async function onUpload(file: File) {
</n-checkbox> </n-checkbox>
</n-space> </n-space>
<c-input-text :value="cleanedFileBase64" multiline readonly :placeholder="t('tools.base64-file-converter.texts.placeholder-file-in-base64-will-be-here')" rows="5" my-2 /> <c-input-text
:value="cleanedFileBase64"
multiline
readonly
:placeholder="t('tools.base64-file-converter.texts.placeholder-file-in-base64-will-be-here')"
rows="5"
my-2
/>
<div flex justify-center> <div flex justify-center>
<c-button @click="copyFileBase64()"> <c-button @click="copyFileBase64()">
@@ -11,12 +11,14 @@ const textInput = ref('');
const base64Output = computed(() => { const base64Output = computed(() => {
try { try {
return Base64.fromUint8Array(hexArray.fromString(textInput.value)); return Base64.fromUint8Array(hexArray.fromString(textInput.value));
} } catch (e: any) {
catch (e: any) {
return e.toString(); return e.toString();
} }
}); });
const { copy: copyTextBase64 } = useCopy({ source: base64Output, text: t('tools.base64-hex-converter.texts.text-base64-hex-array-copied-to-the-clipboard') }); const { copy: copyTextBase64 } = useCopy({
source: base64Output,
text: t('tools.base64-hex-converter.texts.text-base64-hex-array-copied-to-the-clipboard'),
});
const uppercase = ref(false); const uppercase = ref(false);
const grouping = ref(0); const grouping = ref(0);
@@ -30,13 +32,14 @@ const textOutput = computed(() => {
grouping: grouping.value, grouping: grouping.value,
rowlength: rowlength.value, rowlength: rowlength.value,
}); });
} } catch (e: any) {
catch (e: any) {
return e.toString(); return e.toString();
} }
}, });
); const { copy: copyText } = useCopy({
const { copy: copyText } = useCopy({ source: textOutput, text: t('tools.base64-hex-converter.texts.text-hex-array-copied-to-the-clipboard') }); source: textOutput,
text: t('tools.base64-hex-converter.texts.text-hex-array-copied-to-the-clipboard'),
});
const b64ValidationRules = [ const b64ValidationRules = [
{ {
message: t('tools.base64-hex-converter.texts.message-invalid-base64-string'), message: t('tools.base64-hex-converter.texts.message-invalid-base64-string'),
@@ -62,7 +65,9 @@ const b64ValidationRules = [
:value="base64Output" :value="base64Output"
multiline multiline
readonly readonly
:placeholder="t('tools.base64-hex-converter.texts.placeholder-the-base64-encoding-of-your-hex-array-will-be-here')" :placeholder="
t('tools.base64-hex-converter.texts.placeholder-the-base64-encoding-of-your-hex-array-will-be-here')
"
rows="5" rows="5"
mb-5 mb-5
/> />
@@ -80,10 +85,14 @@ const b64ValidationRules = [
<n-switch v-model:value="uppercase" /> <n-switch v-model:value="uppercase" />
</n-form-item> </n-form-item>
<n-form-item :label="t('tools.base64-hex-converter.texts.label-group-by')" label-placement="left"> <n-form-item :label="t('tools.base64-hex-converter.texts.label-group-by')" label-placement="left">
<n-input-number-i18n v-model:value="grouping" :min="0" style="width: 6em" mr-1 />{{ t('tools.base64-hex-converter.texts.tag-digits-0-no-grouping') }} <n-input-number-i18n v-model:value="grouping" :min="0" style="width: 6em" mr-1 />{{
t('tools.base64-hex-converter.texts.tag-digits-0-no-grouping')
}}
</n-form-item> </n-form-item>
<n-form-item :label="t('tools.base64-hex-converter.texts.label-split-as-rows-by')" label-placement="left"> <n-form-item :label="t('tools.base64-hex-converter.texts.label-split-as-rows-by')" label-placement="left">
<n-input-number-i18n v-model:value="rowlength" :min="0" style="width: 6em" mr-1 />{{ t('tools.base64-hex-converter.texts.tag-group-of-digits-0-no-rows') }} <n-input-number-i18n v-model:value="rowlength" :min="0" style="width: 6em" mr-1 />{{
t('tools.base64-hex-converter.texts.tag-group-of-digits-0-no-rows')
}}
</n-form-item> </n-form-item>
</n-space> </n-space>
<c-input-text <c-input-text
+9 -9
View File
@@ -8,7 +8,7 @@ set -euo pipefail
## ⌨️ Keyboard Shortcuts ## ⌨️ Keyboard Shortcuts
| Keys | Does | | Keys | Does |
|---------------------|--------------------------------------------------| | ------------------- | ------------------------------------------------ |
| `Ctrl+A` / `Ctrl+E` | Jump to the start / end of the line | | `Ctrl+A` / `Ctrl+E` | Jump to the start / end of the line |
| `Ctrl+B` / `Ctrl+F` | Back / forward one character | | `Ctrl+B` / `Ctrl+F` | Back / forward one character |
| `Alt+B` / `Alt+F` | Back / forward one word | | `Alt+B` / `Alt+F` | Back / forward one word |
@@ -213,7 +213,7 @@ declare -i counter=0
``` ```
| Variable | Holds | | Variable | Holds |
|----------------------------------|-------------------------------------------| | -------------------------------- | ----------------------------------------- |
| `$0` | The name of the script | | `$0` | The name of the script |
| `$1` … `$9` | Positional arguments | | `$1` … `$9` | Positional arguments |
| `$#` | How many arguments were passed | | `$#` | How many arguments were passed |
@@ -230,7 +230,7 @@ declare -i counter=0
## 🔤 Parameter Expansion ## 🔤 Parameter Expansion
| Expansion | Result | | Expansion | Result |
|-------------------------|----------------------------------------------------------------------------| | ----------------------- | -------------------------------------------------------------------------- |
| `${var:-default}` | `default` when `var` is unset or empty | | `${var:-default}` | `default` when `var` is unset or empty |
| `${var:=default}` | The same, and assigns it | | `${var:=default}` | The same, and assigns it |
| `${var:?message}` | Abort with `message` when unset — great for required arguments | | `${var:?message}` | Abort with `message` when unset — great for required arguments |
@@ -285,7 +285,7 @@ done
Use `[[ ... ]]` in bash — it handles empty variables and patterns far better than the old `[ ... ]`. Use `[[ ... ]]` in bash — it handles empty variables and patterns far better than the old `[ ... ]`.
| Files | True when | | Files | True when |
|----------------|-------------------------------------------| | -------------- | ----------------------------------------- |
| `-e file` | It exists | | `-e file` | It exists |
| `-f file` | It exists and is a regular file | | `-f file` | It exists and is a regular file |
| `-d file` | It exists and is a directory | | `-d file` | It exists and is a directory |
@@ -296,7 +296,7 @@ Use `[[ ... ]]` in bash — it handles empty variables and patterns far better t
| `f1 -nt f2` | `f1` is newer than `f2` (`-ot` for older) | | `f1 -nt f2` | `f1` is newer than `f2` (`-ot` for older) |
| Strings | True when | | Strings | True when |
|----------------|-----------------------------------------------| | -------------- | --------------------------------------------- |
| `-z "$s"` | The string is empty | | `-z "$s"` | The string is empty |
| `-n "$s"` | The string is not empty | | `-n "$s"` | The string is not empty |
| `"$a" == "$b"` | They are equal (`=` also works) | | `"$a" == "$b"` | They are equal (`=` also works) |
@@ -306,7 +306,7 @@ Use `[[ ... ]]` in bash — it handles empty variables and patterns far better t
| `"$s" =~ ^re$` | Regex match, captures land in `$BASH_REMATCH` | | `"$s" =~ ^re$` | Regex match, captures land in `$BASH_REMATCH` |
| Numbers | Meaning | | Numbers | Meaning |
|---------|-----------------------| | ------- | --------------------- |
| `-eq` | Equal | | `-eq` | Equal |
| `-ne` | Not equal | | `-ne` | Not equal |
| `-lt` | Less than | | `-lt` | Less than |
@@ -383,7 +383,7 @@ export -f greet
## ➡️ Redirection ## ➡️ Redirection
| Syntax | Does | | Syntax | Does |
|--------------------|--------------------------------------------| | ------------------ | ------------------------------------------ |
| `> file` | Send stdout to a file, replacing it | | `> file` | Send stdout to a file, replacing it |
| `>> file` | Append stdout to a file | | `>> file` | Append stdout to a file |
| `2> file` | Send stderr to a file | | `2> file` | Send stderr to a file |
@@ -490,7 +490,7 @@ shellcheck script.sh
Escape sequences take the form `\033[<style>;<colour>m`, and `\033[0m` resets. `\e` and `\x1B` are the same character as `\033`. Escape sequences take the form `\033[<style>;<colour>m`, and `\033[0m` resets. `\e` and `\x1B` are the same character as `\033`.
| Colour | Foreground | Bright | Background | | Colour | Foreground | Bright | Background |
|---------|------------|--------|------------| | ------- | ---------- | ------ | ---------- |
| Black | `30` | `90` | `40` | | Black | `30` | `90` | `40` |
| Red | `31` | `91` | `41` | | Red | `31` | `91` | `41` |
| Green | `32` | `92` | `42` | | Green | `32` | `92` | `42` |
@@ -501,7 +501,7 @@ Escape sequences take the form `\033[<style>;<colour>m`, and `\033[0m` resets. `
| White | `37` | `97` | `47` | | White | `37` | `97` | `47` |
| Style | Code | Style | Code | | Style | Code | Style | Code |
|-------|------|-----------|------| | ----- | ---- | --------- | ---- |
| Reset | `0` | Underline | `4` | | Reset | `0` | Underline | `4` |
| Bold | `1` | Blink | `5` | | Bold | `1` | Blink | `5` |
| Dim | `2` | Reverse | `7` | | Dim | `2` | Reverse | `7` |
+18 -21
View File
@@ -2,25 +2,23 @@ import { getCurrentLocale, translate as t } from '@/plugins/i18n.plugin';
Intl.DurationFormat ??= class DurationFormat { Intl.DurationFormat ??= class DurationFormat {
format(duration: { seconds?: number; milliseconds?: number }): string { format(duration: { seconds?: number; milliseconds?: number }): string {
return 'seconds' in duration return 'seconds' in duration ? `${duration.seconds} seconds` : `${duration.milliseconds} milliseconds`;
? `${duration.seconds} seconds`
: `${duration.milliseconds} milliseconds`;
} }
}; };
export type Update<Result> = export type Update<Result> =
| { | {
kind: 'progress' kind: 'progress';
progress: number progress: number;
} }
| { | {
kind: 'success' kind: 'success';
value: Result value: Result;
timeTakenMs: number timeTakenMs: number;
} }
| { | {
kind: 'error' kind: 'error';
message: string message: string;
}; };
// generic type for the callback versions of bcryptjs's `hash` and `compare` // generic type for the callback versions of bcryptjs's `hash` and `compare`
@@ -32,8 +30,8 @@ export type BcryptFn<Param, Result> = (
) => void; ) => void;
interface BcryptWithProgressOptions { interface BcryptWithProgressOptions {
signal: AbortSignal signal: AbortSignal;
timeoutMs: number timeoutMs: number;
} }
export async function* bcryptWithProgressUpdates<Param, Result>( export async function* bcryptWithProgressUpdates<Param, Result>(
@@ -44,13 +42,12 @@ export async function* bcryptWithProgressUpdates<Param, Result>(
const { timeoutMs = 10_000 } = options ?? {}; const { timeoutMs = 10_000 } = options ?? {};
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
// @ts-ignore: AbortSignal.any breaks typecheck // @ts-ignore: AbortSignal.any breaks typecheck
const signal: AbortSignal = AbortSignal.any([ const signal: AbortSignal = AbortSignal.any(
AbortSignal.timeout(timeoutMs), [AbortSignal.timeout(timeoutMs), options?.signal].filter((x) => x != null),
options?.signal, );
].filter(x => x != null));
let res = (_: Update<Result>) => {}; let res = (_: Update<Result>) => {};
const nextPromise = () => new Promise<Update<Result>>(resolve => res = resolve); const nextPromise = () => new Promise<Update<Result>>((resolve) => (res = resolve));
const promises = [nextPromise()]; const promises = [nextPromise()];
const nextValue = (value: Update<Result>) => { const nextValue = (value: Update<Result>) => {
res(value); res(value);
@@ -74,8 +71,9 @@ export async function* bcryptWithProgressUpdates<Param, Result>(
nextValue({ kind: 'progress', progress: 0 }); nextValue({ kind: 'progress', progress: 0 });
if (signal.reason instanceof DOMException && signal.reason.name === 'TimeoutError') { if (signal.reason instanceof DOMException && signal.reason.name === 'TimeoutError') {
const message = t('tools.bcrypt.texts.timed-out-after-timeout-period', { const message = t('tools.bcrypt.texts.timed-out-after-timeout-period', {
timeoutPeriod: new Intl.DurationFormat(getCurrentLocale(), { style: 'long' }) timeoutPeriod: new Intl.DurationFormat(getCurrentLocale(), { style: 'long' }).format({
.format({ seconds: Math.round(timeoutMs / 1000) }), seconds: Math.round(timeoutMs / 1000),
}),
}); });
nextValue({ kind: 'error', message }); nextValue({ kind: 'error', message });
@@ -83,8 +81,7 @@ export async function* bcryptWithProgressUpdates<Param, Result>(
// throw inside callback to cancel execution of hashing/comparing // throw inside callback to cancel execution of hashing/comparing
throw signal.reason; throw signal.reason;
} } else {
else {
nextValue({ kind: 'progress', progress }); nextValue({ kind: 'progress', progress });
} }
}, },
+46 -14
View File
@@ -10,10 +10,10 @@ const { t, locale } = useI18n();
const themeVars = useThemeVars(); const themeVars = useThemeVars();
interface ExecutionState<T> { interface ExecutionState<T> {
result: T | null result: T | null;
percentage: number percentage: number;
error: string | null error: string | null;
timeTakenMs: number | null timeTakenMs: number | null;
} }
const blankState = () => ({ result: null, percentage: 0, error: null, timeTakenMs: null }); const blankState = () => ({ result: null, percentage: 0, error: null, timeTakenMs: null });
@@ -89,7 +89,13 @@ initWatcher(compare, [compareString, compareHash], compareState);
mb-2 mb-2
/> />
<n-form-item :label="t('tools.bcrypt.texts.label-salt-count')" label-placement="left" label-width="120"> <n-form-item :label="t('tools.bcrypt.texts.label-salt-count')" label-placement="left" label-width="120">
<n-input-number v-model:value="saltCount" :placeholder="t('tools.bcrypt.texts.placeholder-salt-rounds')" :max="20" :min="4" w-full /> <n-input-number
v-model:value="saltCount"
:placeholder="t('tools.bcrypt.texts.placeholder-salt-rounds')"
:max="20"
:min="4"
w-full
/>
</n-form-item> </n-form-item>
<n-progress :percentage="hashState.percentage" :show-indicator="false" /> <n-progress :percentage="hashState.percentage" :show-indicator="false" />
@@ -100,9 +106,15 @@ initWatcher(compare, [compareString, compareHash], compareState);
text-center text-center
/> />
<div mt-1 h-3 op-60> <div mt-1 h-3 op-60>
{{ hashState.timeTakenMs == null ? '' : t('tools.bcrypt.texts.hashed-in-elapsed-period', { {{
elapsedPeriod: new Intl.DurationFormat(locale, { style: "long" }).format({ milliseconds: hashState.timeTakenMs }), hashState.timeTakenMs == null
}) }} ? ''
: t('tools.bcrypt.texts.hashed-in-elapsed-period', {
elapsedPeriod: new Intl.DurationFormat(locale, { style: 'long' }).format({
milliseconds: hashState.timeTakenMs,
}),
})
}}
</div> </div>
<div mt-5 flex justify-center> <div mt-5 flex justify-center>
@@ -115,17 +127,31 @@ initWatcher(compare, [compareString, compareHash], compareState);
<c-card :title="t('tools.bcrypt.texts.title-compare-string-with-hash')"> <c-card :title="t('tools.bcrypt.texts.title-compare-string-with-hash')">
<n-form label-width="120"> <n-form label-width="120">
<n-form-item :label="t('tools.bcrypt.texts.label-your-string')" label-placement="left"> <n-form-item :label="t('tools.bcrypt.texts.label-your-string')" label-placement="left">
<c-input-text v-model:value="compareString" :placeholder="t('tools.bcrypt.texts.placeholder-your-string-to-compare')" raw-text /> <c-input-text
v-model:value="compareString"
:placeholder="t('tools.bcrypt.texts.placeholder-your-string-to-compare')"
raw-text
/>
</n-form-item> </n-form-item>
<n-form-item :label="t('tools.bcrypt.texts.label-your-hash')" label-placement="left"> <n-form-item :label="t('tools.bcrypt.texts.label-your-hash')" label-placement="left">
<c-input-text v-model:value="compareHash" :placeholder="t('tools.bcrypt.texts.placeholder-your-hash-to-compare')" raw-text /> <c-input-text
v-model:value="compareHash"
:placeholder="t('tools.bcrypt.texts.placeholder-your-hash-to-compare')"
raw-text
/>
</n-form-item> </n-form-item>
<n-progress :percentage="compareState.percentage" :show-indicator="false" /> <n-progress :percentage="compareState.percentage" :show-indicator="false" />
<div> <div>
<c-input-text <c-input-text
id="bcrypt-compare-result" id="bcrypt-compare-result"
:value="compareState.result == null ? undefined : compareState.result ? t('tools.bcrypt.texts.matched') : t('tools.bcrypt.texts.no-match')" :value="
compareState.result == null
? undefined
: compareState.result
? t('tools.bcrypt.texts.matched')
: t('tools.bcrypt.texts.no-match')
"
:placeholder="compareState.error ?? t('tools.bcrypt.texts.comparison-result')" :placeholder="compareState.error ?? t('tools.bcrypt.texts.comparison-result')"
readonly readonly
text-center text-center
@@ -134,9 +160,15 @@ initWatcher(compare, [compareString, compareHash], compareState);
/> />
</div> </div>
<div mb-1 mt-1 h-3 op-60> <div mb-1 mt-1 h-3 op-60>
{{ compareState.timeTakenMs == null ? '' : t('tools.bcrypt.texts.compared-in-elapsed-period', { {{
elapsedPeriod: new Intl.DurationFormat(locale, { style: 'long' }).format({ milliseconds: compareState.timeTakenMs }), compareState.timeTakenMs == null
}) }} ? ''
: t('tools.bcrypt.texts.compared-in-elapsed-period', {
elapsedPeriod: new Intl.DurationFormat(locale, { style: 'long' }).format({
milliseconds: compareState.timeTakenMs,
}),
})
}}
</div> </div>
</n-form> </n-form>
</c-card> </c-card>
@@ -13,22 +13,28 @@ function computeAverage({ data }: { data: number[] }) {
function computeVariance({ data }: { data: number[] }) { function computeVariance({ data }: { data: number[] }) {
const mean = computeAverage({ data }); const mean = computeAverage({ data });
const squaredDiffs = data.map(value => (value - mean) ** 2); const squaredDiffs = data.map((value) => (value - mean) ** 2);
return computeAverage({ data: squaredDiffs }); return computeAverage({ data: squaredDiffs });
} }
function arrayToMarkdownTable({ data, headerMap = {} }: { data: Record<string, unknown>[]; headerMap?: Record<string, string> }) { function arrayToMarkdownTable({
data,
headerMap = {},
}: {
data: Record<string, unknown>[];
headerMap?: Record<string, string>;
}) {
if (!Array.isArray(data) || data.length === 0) { if (!Array.isArray(data) || data.length === 0) {
return ''; return '';
} }
const headers = Object.keys(data[0]); const headers = Object.keys(data[0]);
const rows = data.map(obj => Object.values(obj)); const rows = data.map((obj) => Object.values(obj));
const headerRow = `| ${headers.map(header => headerMap[header] ?? header).join(' | ')} |`; const headerRow = `| ${headers.map((header) => headerMap[header] ?? header).join(' | ')} |`;
const separatorRow = `| ${headers.map(() => '---').join(' | ')} |`; const separatorRow = `| ${headers.map(() => '---').join(' | ')} |`;
const dataRows = rows.map(row => `| ${row.join(' | ')} |`).join('\n'); const dataRows = rows.map((row) => `| ${row.join(' | ')} |`).join('\n');
return `${headerRow}\n${separatorRow}\n${dataRows}`; return `${headerRow}\n${separatorRow}\n${dataRows}`;
} }
@@ -38,8 +38,8 @@ const results = computed(() => {
const deltaWithBestMean = mean - bestMean; const deltaWithBestMean = mean - bestMean;
const ratioWithBestMean = bestMean === 0 ? '∞' : round(mean / bestMean); const ratioWithBestMean = bestMean === 0 ? '∞' : round(mean / bestMean);
const comparisonValues: string const comparisonValues: string =
= (index !== 0 && bestMean !== mean) ? ` (+${round(deltaWithBestMean)}${cleanUnit} ; x${ratioWithBestMean})` : ''; index !== 0 && bestMean !== mean ? ` (+${round(deltaWithBestMean)}${cleanUnit} ; x${ratioWithBestMean})` : '';
return { return {
position: index + 1, position: index + 1,
@@ -102,7 +102,9 @@ function copyAsBulletList() {
<div flex justify-center> <div flex justify-center>
<c-button v-if="suites.length > 1" variant="text" @click="suites.splice(index, 1)"> <c-button v-if="suites.length > 1" variant="text" @click="suites.splice(index, 1)">
<n-icon :component="Trash" depth="3" mr-2 size="18" />{{ t('tools.benchmark-builder.texts.tag-delete-suite') }} <n-icon :component="Trash" depth="3" mr-2 size="18" />{{
t('tools.benchmark-builder.texts.tag-delete-suite')
}}
</c-button> </c-button>
<c-button <c-button
variant="text" variant="text"
@@ -118,7 +120,13 @@ function copyAsBulletList() {
<div style="flex: 0 0 100%"> <div style="flex: 0 0 100%">
<div style="max-width: 600px; margin: 0 auto"> <div style="max-width: 600px; margin: 0 auto">
<div mx-auto max-w-sm flex justify-center gap-3> <div mx-auto max-w-sm flex justify-center gap-3>
<c-input-text v-model:value="unit" :placeholder="t('tools.benchmark-builder.texts.placeholder-unit-eg-ms')" :label="t('tools.benchmark-builder.texts.label-unit')" label-position="left" mb-4 /> <c-input-text
v-model:value="unit"
:placeholder="t('tools.benchmark-builder.texts.placeholder-unit-eg-ms')"
:label="t('tools.benchmark-builder.texts.label-unit')"
label-position="left"
mb-4
/>
<c-button <c-button
@click=" @click="
@@ -32,13 +32,22 @@ const bimiRecord = computed(() => {
<NCard :title="t('tools.bimi-dns-generator.texts.title-bimi-dns-record-generator')"> <NCard :title="t('tools.bimi-dns-generator.texts.title-bimi-dns-record-generator')">
<NForm :model="bimiData" label-placement="left" label-width="150px"> <NForm :model="bimiData" label-placement="left" label-width="150px">
<NFormItem :label="t('tools.bimi-dns-generator.texts.label-domain')"> <NFormItem :label="t('tools.bimi-dns-generator.texts.label-domain')">
<NInput v-model:value="bimiData.domain" :placeholder="t('tools.bimi-dns-generator.texts.placeholder-example-com')" /> <NInput
v-model:value="bimiData.domain"
:placeholder="t('tools.bimi-dns-generator.texts.placeholder-example-com')"
/>
</NFormItem> </NFormItem>
<NFormItem :label="t('tools.bimi-dns-generator.texts.label-logo-url')"> <NFormItem :label="t('tools.bimi-dns-generator.texts.label-logo-url')">
<NInput v-model:value="bimiData.logoUrl" :placeholder="t('tools.bimi-dns-generator.texts.placeholder-https-example-com-logo-svg')" /> <NInput
v-model:value="bimiData.logoUrl"
:placeholder="t('tools.bimi-dns-generator.texts.placeholder-https-example-com-logo-svg')"
/>
</NFormItem> </NFormItem>
<NFormItem :label="t('tools.bimi-dns-generator.texts.label-vmc-certificate-url')"> <NFormItem :label="t('tools.bimi-dns-generator.texts.label-vmc-certificate-url')">
<NInput v-model:value="bimiData.vmcUrl" :placeholder="t('tools.bimi-dns-generator.texts.placeholder-https-example-com-vmc-pem')" /> <NInput
v-model:value="bimiData.vmcUrl"
:placeholder="t('tools.bimi-dns-generator.texts.placeholder-https-example-com-vmc-pem')"
/>
</NFormItem> </NFormItem>
</NForm> </NForm>
@@ -7,8 +7,16 @@ const { t } = useI18n();
type NumberFormat = 'dec' | 'hex' | 'oct' | 'bin'; type NumberFormat = 'dec' | 'hex' | 'oct' | 'bin';
const inputFormatA = useQueryParamOrStorage<NumberFormat>({ name: 'text', storageName: 'bin-calc:fa', defaultValue: 'dec' }); const inputFormatA = useQueryParamOrStorage<NumberFormat>({
const inputFormatB = useQueryParamOrStorage<NumberFormat>({ name: 'text', storageName: 'bin-calc:fb', defaultValue: 'dec' }); name: 'text',
storageName: 'bin-calc:fa',
defaultValue: 'dec',
});
const inputFormatB = useQueryParamOrStorage<NumberFormat>({
name: 'text',
storageName: 'bin-calc:fb',
defaultValue: 'dec',
});
const operation = useQueryParamOrStorage({ name: 'op', storageName: 'bin-calc:o', defaultValue: 'AND' }); const operation = useQueryParamOrStorage({ name: 'op', storageName: 'bin-calc:o', defaultValue: 'AND' });
const inputA = ref(''); const inputA = ref('');
const inputB = ref(''); const inputB = ref('');
@@ -34,7 +42,7 @@ const inputAValidation = useValidation({
watch: [inputFormatA], watch: [inputFormatA],
rules: [ rules: [
{ {
validator: v => parseInputA(v) !== null, validator: (v) => parseInputA(v) !== null,
message: t('tools.binary-calculator.texts.message-number-is-invalid'), message: t('tools.binary-calculator.texts.message-number-is-invalid'),
}, },
], ],
@@ -44,7 +52,7 @@ const inputBValidation = useValidation({
watch: [inputFormatB], watch: [inputFormatB],
rules: [ rules: [
{ {
validator: v => parseInputB(v) !== null, validator: (v) => parseInputB(v) !== null,
message: t('tools.binary-calculator.texts.message-number-is-invalid'), message: t('tools.binary-calculator.texts.message-number-is-invalid'),
}, },
], ],
@@ -77,8 +85,7 @@ function parseInput(value: string, format: NumberFormat): number | null {
return null; return null;
} }
return num; return num;
} } catch {
catch {
return null; return null;
} }
} }
@@ -115,22 +122,35 @@ const result = computed(() => {
} }
}); });
const signedResult = computed(() => result.value !== null ? (result.value | 0).toString() : ''); const signedResult = computed(() => (result.value !== null ? (result.value | 0).toString() : ''));
const unsignedResult = computed(() => result.value !== null ? (result.value >>> 0).toString() : ''); const unsignedResult = computed(() => (result.value !== null ? (result.value >>> 0).toString() : ''));
const bitmask = computed(() => const bitmask = computed(() =>
result.value !== null result.value !== null ? (result.value >>> 0).toString(2).padStart(32, '0').split('') : [],
? (result.value >>> 0).toString(2).padStart(32, '0').split('')
: [],
); );
</script> </script>
<template> <template>
<div style="min-height: 50vh; max-width: 800px;"> <div style="min-height: 50vh; max-width: 800px">
<n-space justify="space-evenly" mb-2> <n-space justify="space-evenly" mb-2>
<NSelect v-model:value="inputFormatA" :options="formatOptions" style="width: 130px" /> <NSelect v-model:value="inputFormatA" :options="formatOptions" style="width: 130px" />
<c-input-text v-model:value="inputA" style="width: 150px" :validation="inputAValidation" label-position="left" :label="t('tools.binary-calculator.texts.label-a')" :placeholder="t('tools.binary-calculator.texts.placeholder-enter-a')" /> <c-input-text
v-model:value="inputA"
style="width: 150px"
:validation="inputAValidation"
label-position="left"
:label="t('tools.binary-calculator.texts.label-a')"
:placeholder="t('tools.binary-calculator.texts.placeholder-enter-a')"
/>
<NSelect v-model:value="inputFormatB" :options="formatOptions" style="width: 130px" /> <NSelect v-model:value="inputFormatB" :options="formatOptions" style="width: 130px" />
<c-input-text v-model:value="inputB" style="width: 150px" :validation="inputBValidation" label-position="left" :label="t('tools.binary-calculator.texts.label-b')" :placeholder="t('tools.binary-calculator.texts.placeholder-enter-b')" :disabled="isUnary" /> <c-input-text
v-model:value="inputB"
style="width: 150px"
:validation="inputBValidation"
label-position="left"
:label="t('tools.binary-calculator.texts.label-b')"
:placeholder="t('tools.binary-calculator.texts.placeholder-enter-b')"
:disabled="isUnary"
/>
</n-space> </n-space>
<c-select <c-select
@@ -143,21 +163,46 @@ const bitmask = computed(() =>
/> />
<c-card v-if="result !== null" :title="t('tools.binary-calculator.texts.title-result')" mb-1> <c-card v-if="result !== null" :title="t('tools.binary-calculator.texts.title-result')" mb-1>
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-decimal-signed')" label-position="left" :value="signedResult" /> <input-copyable
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-decimal-unigned')" label-position="left" :value="unsignedResult" /> label-width="130px"
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-binary')" label-position="left" :value="`0b${result.toString(2).padStart(32, '0')}`" /> mb-1
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-hexadecimal')" label-position="left" :value="`0x${result.toString(16).toUpperCase()}`" /> :label="t('tools.binary-calculator.texts.label-decimal-signed')"
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-octal')" label-position="left" :value="`0o${result.toString(8)}`" /> label-position="left"
:value="signedResult"
/>
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-decimal-unigned')"
label-position="left"
:value="unsignedResult"
/>
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-binary')"
label-position="left"
:value="`0b${result.toString(2).padStart(32, '0')}`"
/>
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-hexadecimal')"
label-position="left"
:value="`0x${result.toString(16).toUpperCase()}`"
/>
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-octal')"
label-position="left"
:value="`0o${result.toString(8)}`"
/>
</c-card> </c-card>
<c-card v-if="result !== null" :title="t('tools.binary-calculator.texts.title-bitmask')"> <c-card v-if="result !== null" :title="t('tools.binary-calculator.texts.title-bitmask')">
<NSpace justify="center" wrap> <NSpace justify="center" wrap>
<NTag <NTag v-for="(bit, index) in bitmask" :key="index" :type="bit === '1' ? 'success' : 'default'" size="small">
v-for="(bit, index) in bitmask"
:key="index"
:type="bit === '1' ? 'success' : 'default'"
size="small"
>
{{ bit }} {{ bit }}
</NTag> </NTag>
</NSpace> </NSpace>
+33 -16
View File
@@ -26,22 +26,26 @@ import { useQueryParamOrStorage } from '@/composable/queryParams';
const { t } = useI18n(); const { t } = useI18n();
const languages = { const languages = {
'English': englishWordList, English: englishWordList,
'Chinese simplified': chineseSimplifiedWordList, 'Chinese simplified': chineseSimplifiedWordList,
'Chinese traditional': chineseTraditionalWordList, 'Chinese traditional': chineseTraditionalWordList,
'Czech': czechWordList, Czech: czechWordList,
'French': frenchWordList, French: frenchWordList,
'Italian': italianWordList, Italian: italianWordList,
'Japanese': japaneseWordList, Japanese: japaneseWordList,
'Korean': koreanWordList, Korean: koreanWordList,
'Portuguese': portugueseWordList, Portuguese: portugueseWordList,
'Spanish': spanishWordList, Spanish: spanishWordList,
}; };
const entropy = ref(generateEntropy()); const entropy = ref(generateEntropy());
const passphraseInput = ref(''); const passphraseInput = ref('');
const language = useQueryParamOrStorage<keyof typeof languages>({ name: 'lang', storageName: 'bip39-gen:l', defaultValue: 'English' }); const language = useQueryParamOrStorage<keyof typeof languages>({
name: 'lang',
storageName: 'bip39-gen:l',
defaultValue: 'English',
});
const passphrase = computed({ const passphrase = computed({
get() { get() {
@@ -57,11 +61,11 @@ const entropyValidation = useValidation({
source: entropy, source: entropy,
rules: [ rules: [
{ {
validator: value => value === '' || (value.length <= 32 && value.length >= 16 && value.length % 4 === 0), validator: (value) => value === '' || (value.length <= 32 && value.length >= 16 && value.length % 4 === 0),
message: t('tools.bip39-generator.texts.message-entropy-length-should-be-16-32-and-be-a-multiple-of-4'), message: t('tools.bip39-generator.texts.message-entropy-length-should-be-16-32-and-be-a-multiple-of-4'),
}, },
{ {
validator: value => /^[a-fA-F0-9]*$/.test(value), validator: (value) => /^[a-fA-F0-9]*$/.test(value),
message: t('tools.bip39-generator.texts.message-entropy-should-be-an-hexadecimal-string'), message: t('tools.bip39-generator.texts.message-entropy-should-be-an-hexadecimal-string'),
}, },
], ],
@@ -71,7 +75,7 @@ const mnemonicValidation = useValidation({
source: passphrase, source: passphrase,
rules: [ rules: [
{ {
validator: value => isNotThrowing(() => mnemonicToEntropy(value, languages[language.value])), validator: (value) => isNotThrowing(() => mnemonicToEntropy(value, languages[language.value])),
message: t('tools.bip39-generator.texts.message-invalid-mnemonic'), message: t('tools.bip39-generator.texts.message-invalid-mnemonic'),
}, },
], ],
@@ -81,8 +85,14 @@ function refreshEntropy() {
entropy.value = generateEntropy(); entropy.value = generateEntropy();
} }
const { copy: copyEntropy } = useCopy({ source: entropy, text: t('tools.bip39-generator.texts.text-entropy-copied-to-the-clipboard') }); const { copy: copyEntropy } = useCopy({
const { copy: copyPassphrase } = useCopy({ source: passphrase, text: t('tools.bip39-generator.texts.text-passphrase-copied-to-the-clipboard') }); source: entropy,
text: t('tools.bip39-generator.texts.text-entropy-copied-to-the-clipboard'),
});
const { copy: copyPassphrase } = useCopy({
source: passphrase,
text: t('tools.bip39-generator.texts.text-passphrase-copied-to-the-clipboard'),
});
</script> </script>
<template> <template>
@@ -103,7 +113,10 @@ const { copy: copyPassphrase } = useCopy({ source: passphrase, text: t('tools.bi
:validation-status="entropyValidation.status" :validation-status="entropyValidation.status"
> >
<n-input-group> <n-input-group>
<c-input-text v-model:value="entropy" :placeholder="t('tools.bip39-generator.texts.placeholder-your-string')" /> <c-input-text
v-model:value="entropy"
:placeholder="t('tools.bip39-generator.texts.placeholder-your-string')"
/>
<c-button @click="refreshEntropy()"> <c-button @click="refreshEntropy()">
<n-icon size="22"> <n-icon size="22">
@@ -125,7 +138,11 @@ const { copy: copyPassphrase } = useCopy({ source: passphrase, text: t('tools.bi
:validation-status="mnemonicValidation.status" :validation-status="mnemonicValidation.status"
> >
<n-input-group> <n-input-group>
<c-input-text v-model:value="passphrase" :placeholder="t('tools.bip39-generator.texts.placeholder-your-mnemonic')" raw-text /> <c-input-text
v-model:value="passphrase"
:placeholder="t('tools.bip39-generator.texts.placeholder-your-mnemonic')"
raw-text
/>
<c-button @click="copyPassphrase()"> <c-button @click="copyPassphrase()">
<n-icon size="22" :component="Copy" /> <n-icon size="22" :component="Copy" />
+30 -7
View File
@@ -52,18 +52,41 @@ const bmiCategory = computed(() => {
<template> <template>
<c-card :title="t('tools.bmi-calculator.texts.title-bmi-calculator')" max-w-800px> <c-card :title="t('tools.bmi-calculator.texts.title-bmi-calculator')" max-w-800px>
<c-select v-model:value="units" :label="t('tools.bmi-calculator.texts.label-select-units')" :options="options" mb-2 label-position="left" /> <c-select
v-model:value="units"
:label="t('tools.bmi-calculator.texts.label-select-units')"
:options="options"
mb-2
label-position="left"
/>
<n-space justify="space-evenly"> <n-space justify="space-evenly">
<n-form-item :label="`Weight (${(units === 'metric' ? 'kg' : 'lbs')}):`" label-placement="left" mb-2> <n-form-item :label="`Weight (${units === 'metric' ? 'kg' : 'lbs'}):`" label-placement="left" mb-2>
<n-input-number-i18n v-model:value="weight" :placeholder="t('tools.bmi-calculator.texts.placeholder-enter-weight')" /> <n-input-number-i18n
v-model:value="weight"
:placeholder="t('tools.bmi-calculator.texts.placeholder-enter-weight')"
/>
</n-form-item> </n-form-item>
<n-form-item :label="`Height (${(units === 'metric' ? 'm' : 'in')}):`" label-placement="left" mb-2> <n-form-item :label="`Height (${units === 'metric' ? 'm' : 'in'}):`" label-placement="left" mb-2>
<n-input-number-i18n v-model:value="height" :placeholder="t('tools.bmi-calculator.texts.placeholder-enter-height')" /> <n-input-number-i18n
v-model:value="height"
:placeholder="t('tools.bmi-calculator.texts.placeholder-enter-height')"
/>
</n-form-item> </n-form-item>
</n-space> </n-space>
<c-card v-if="bmi" :title="t('tools.bmi-calculator.texts.title-result')"> <c-card v-if="bmi" :title="t('tools.bmi-calculator.texts.title-result')">
<input-copyable :label="t('tools.bmi-calculator.texts.label-bmi')" label-position="left" label-width="100px" :value="bmi" mb-1 /> <input-copyable
<input-copyable :label="t('tools.bmi-calculator.texts.label-category')" label-position="left" label-width="100px" :value="bmiCategory" /> :label="t('tools.bmi-calculator.texts.label-bmi')"
label-position="left"
label-width="100px"
:value="bmi"
mb-1
/>
<input-copyable
:label="t('tools.bmi-calculator.texts.label-category')"
label-position="left"
label-width="100px"
:value="bmiCategory"
/>
</c-card> </c-card>
</c-card> </c-card>
</template> </template>
+72 -16
View File
@@ -9,8 +9,7 @@ const emailContent = ref('');
const parsedBounce = computed(() => { const parsedBounce = computed(() => {
try { try {
return { email: new EmailBounceParse().read(emailContent.value) }; return { email: new EmailBounceParse().read(emailContent.value) };
} } catch (e: any) {
catch (e: any) {
return { parsingError: e.toString() }; return { parsingError: e.toString() };
} }
}); });
@@ -39,23 +38,80 @@ const parsedBounce = computed(() => {
<c-alert v-if="parsedBounce.parsingError" mb-2> <c-alert v-if="parsedBounce.parsingError" mb-2>
{{ parsedBounce.parsingError }} {{ parsedBounce.parsingError }}
</c-alert> </c-alert>
<input-copyable v-if="parsedBounce.email?.data?.recipient" :label="t('tools.bounce-parser.texts.label-recipient')" :value="parsedBounce.email?.data?.recipient" mb-2 /> <input-copyable
v-if="parsedBounce.email?.data?.recipient"
:label="t('tools.bounce-parser.texts.label-recipient')"
:value="parsedBounce.email?.data?.recipient"
mb-2
/>
<div v-if="parsedBounce.email?.email?.error"> <div v-if="parsedBounce.email?.email?.error">
<c-card :title="t('tools.bounce-parser.texts.title-error')" mb-2> <c-card :title="t('tools.bounce-parser.texts.title-error')" mb-2>
<input-copyable v-if="parsedBounce.email?.data?.command" :label="t('tools.bounce-parser.texts.label-command')" :value="parsedBounce.email?.data?.command" /> <input-copyable
<input-copyable v-if="parsedBounce.email?.data?.error?.code?.basic || parsedBounce.email?.data?.error?.code?.enhanced" :label="t('tools.bounce-parser.texts.label-code')" :value="`${parsedBounce.email?.data?.error?.code?.basic}/${parsedBounce.email?.data?.error?.code?.enhanced}`" /> v-if="parsedBounce.email?.data?.command"
<input-copyable v-if="parsedBounce.email?.data?.error?.label" :label="t('tools.bounce-parser.texts.label-label')" :value="parsedBounce.email?.data?.error?.label" /> :label="t('tools.bounce-parser.texts.label-command')"
<input-copyable v-if="parsedBounce.email?.data?.error?.type" :label="t('tools.bounce-parser.texts.label-type')" :value="parsedBounce.email?.data?.error?.type" /> :value="parsedBounce.email?.data?.command"
<input-copyable v-if="parsedBounce.email?.data?.error?.temporary" :label="t('tools.bounce-parser.texts.label-temporary')" :value="parsedBounce.email?.data?.error?.temporary" /> />
<input-copyable v-if="parsedBounce.email?.data?.error?.permanent" :label="t('tools.bounce-parser.texts.label-permanent')" :value="parsedBounce.email?.data?.error?.permanent" /> <input-copyable
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.type" :label="t('tools.bounce-parser.texts.label-subtype')" :value="parsedBounce.email?.data?.error?.data?.type" /> v-if="parsedBounce.email?.data?.error?.code?.basic || parsedBounce.email?.data?.error?.code?.enhanced"
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.blocked" :label="t('tools.bounce-parser.texts.label-blocked')" :value="parsedBounce.email?.data?.error?.data?.blocked" /> :label="t('tools.bounce-parser.texts.label-code')"
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.spam" :label="t('tools.bounce-parser.texts.label-spam')" :value="parsedBounce.email?.data?.error?.data?.spam" /> :value="`${parsedBounce.email?.data?.error?.code?.basic}/${parsedBounce.email?.data?.error?.code?.enhanced}`"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.label"
:label="t('tools.bounce-parser.texts.label-label')"
:value="parsedBounce.email?.data?.error?.label"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.type"
:label="t('tools.bounce-parser.texts.label-type')"
:value="parsedBounce.email?.data?.error?.type"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.temporary"
:label="t('tools.bounce-parser.texts.label-temporary')"
:value="parsedBounce.email?.data?.error?.temporary"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.permanent"
:label="t('tools.bounce-parser.texts.label-permanent')"
:value="parsedBounce.email?.data?.error?.permanent"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.data?.type"
:label="t('tools.bounce-parser.texts.label-subtype')"
:value="parsedBounce.email?.data?.error?.data?.type"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.data?.blocked"
:label="t('tools.bounce-parser.texts.label-blocked')"
:value="parsedBounce.email?.data?.error?.data?.blocked"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.data?.spam"
:label="t('tools.bounce-parser.texts.label-spam')"
:value="parsedBounce.email?.data?.error?.data?.spam"
/>
</c-card> </c-card>
<c-card v-if="parsedBounce.email?.data?.server?.hostname || parsedBounce.email?.data?.server?.ip" :title="t('tools.bounce-parser.texts.title-server')" mb-2> <c-card
<input-copyable v-if="parsedBounce.email?.data?.server?.hostname" :label="t('tools.bounce-parser.texts.label-host')" :value="parsedBounce.email?.data?.server?.hostname" /> v-if="parsedBounce.email?.data?.server?.hostname || parsedBounce.email?.data?.server?.ip"
<input-copyable v-if="parsedBounce.email?.data?.server?.ip" :label="t('tools.bounce-parser.texts.label-ip')" :value="parsedBounce.email?.data?.server?.ip" /> :title="t('tools.bounce-parser.texts.title-server')"
<input-copyable v-if="parsedBounce.email?.data?.server?.port" :label="t('tools.bounce-parser.texts.label-port')" :value="parsedBounce.email?.data?.server?.port" /> mb-2
>
<input-copyable
v-if="parsedBounce.email?.data?.server?.hostname"
:label="t('tools.bounce-parser.texts.label-host')"
:value="parsedBounce.email?.data?.server?.hostname"
/>
<input-copyable
v-if="parsedBounce.email?.data?.server?.ip"
:label="t('tools.bounce-parser.texts.label-ip')"
:value="parsedBounce.email?.data?.server?.ip"
/>
<input-copyable
v-if="parsedBounce.email?.data?.server?.port"
:label="t('tools.bounce-parser.texts.label-port')"
:value="parsedBounce.email?.data?.server?.port"
/>
</c-card> </c-card>
<c-card :title="t('tools.bounce-parser.texts.title-details')" mb-2> <c-card :title="t('tools.bounce-parser.texts.title-details')" mb-2>
<textarea-copyable :value="JSON.stringify(parsedBounce.email?.data, null, 2)" /> <textarea-copyable :value="JSON.stringify(parsedBounce.email?.data, null, 2)" />
+26 -26
View File
@@ -1,36 +1,36 @@
declare module "email-bounce-parser-browser" { declare module 'email-bounce-parser-browser' {
export default class EmailBounceParse { export default class EmailBounceParse {
read(emailContent: string): { read(emailContent: string): {
bounce: boolean bounce: boolean;
email?: { email?: {
body?: string body?: string;
intro?: string intro?: string;
error?: string error?: string;
} };
data?: { data?: {
error?: { error?: {
code?: { code?: {
basic?: string basic?: string;
enhanced?:string enhanced?: string;
} };
label?: string label?: string;
type?: string type?: string;
temporary?: boolean temporary?: boolean;
permanent?: boolean permanent?: boolean;
data?: { data?: {
type?: string type?: string;
blocked?: boolean blocked?: boolean;
spam?: boolean spam?: boolean;
} };
} };
recipient?:string recipient?: string;
server?: { server?: {
hostname?: string hostname?: string;
ip?: string ip?: string;
port?: string port?: string;
} };
command?: string command?: string;
} };
} };
} }
} }
File diff suppressed because it is too large. Load diff
@@ -7,12 +7,18 @@ const { t } = useI18n();
const converter = ref(new CalendarConverter()); const converter = ref(new CalendarConverter());
const monthOptions = [ const monthOptions = [
{ label: t('tools.calendar-converter.texts.label-january'), value: 1 }, { label: t('tools.calendar-converter.texts.label-february'), value: 2 }, { label: t('tools.calendar-converter.texts.label-january'), value: 1 },
{ label: t('tools.calendar-converter.texts.label-march'), value: 3 }, { label: t('tools.calendar-converter.texts.label-april'), value: 4 }, { label: t('tools.calendar-converter.texts.label-february'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-may'), value: 5 }, { label: t('tools.calendar-converter.texts.label-june'), value: 6 }, { label: t('tools.calendar-converter.texts.label-march'), value: 3 },
{ label: t('tools.calendar-converter.texts.label-july'), value: 7 }, { label: t('tools.calendar-converter.texts.label-august'), value: 8 }, { label: t('tools.calendar-converter.texts.label-april'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-september'), value: 9 }, { label: t('tools.calendar-converter.texts.label-october'), value: 10 }, { label: t('tools.calendar-converter.texts.label-may'), value: 5 },
{ label: t('tools.calendar-converter.texts.label-november'), value: 11 }, { label: t('tools.calendar-converter.texts.label-december'), value: 12 }, { label: t('tools.calendar-converter.texts.label-june'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-july'), value: 7 },
{ label: t('tools.calendar-converter.texts.label-august'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-september'), value: 9 },
{ label: t('tools.calendar-converter.texts.label-october'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-november'), value: 11 },
{ label: t('tools.calendar-converter.texts.label-december'), value: 12 },
]; ];
const hebrewMonths = [ const hebrewMonths = [
@@ -77,12 +83,18 @@ const indianMonths = [
]; ];
const frenchMonths = [ const frenchMonths = [
{ label: t('tools.calendar-converter.texts.label-vendémiaire'), value: 1 }, { label: t('tools.calendar-converter.texts.label-brumaire'), value: 2 }, { label: t('tools.calendar-converter.texts.label-vendémiaire'), value: 1 },
{ label: t('tools.calendar-converter.texts.label-frimaire'), value: 3 }, { label: t('tools.calendar-converter.texts.label-nivôse'), value: 4 }, { label: t('tools.calendar-converter.texts.label-brumaire'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-pluviôse'), value: 5 }, { label: t('tools.calendar-converter.texts.label-ventôse'), value: 6 }, { label: t('tools.calendar-converter.texts.label-frimaire'), value: 3 },
{ label: t('tools.calendar-converter.texts.label-germinal'), value: 7 }, { label: t('tools.calendar-converter.texts.label-floréal'), value: 8 }, { label: t('tools.calendar-converter.texts.label-nivôse'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-prairial'), value: 9 }, { label: t('tools.calendar-converter.texts.label-messidor'), value: 10 }, { label: t('tools.calendar-converter.texts.label-pluviôse'), value: 5 },
{ label: t('tools.calendar-converter.texts.label-thermidor'), value: 11 }, { label: t('tools.calendar-converter.texts.label-fructidor'), value: 12 }, { label: t('tools.calendar-converter.texts.label-ventôse'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-germinal'), value: 7 },
{ label: t('tools.calendar-converter.texts.label-floréal'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-prairial'), value: 9 },
{ label: t('tools.calendar-converter.texts.label-messidor'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-thermidor'), value: 11 },
{ label: t('tools.calendar-converter.texts.label-fructidor'), value: 12 },
{ label: t('tools.calendar-converter.texts.label-sans-culottides'), value: 13 }, { label: t('tools.calendar-converter.texts.label-sans-culottides'), value: 13 },
]; ];
@@ -93,23 +105,32 @@ const frenchDecades = [
]; ];
const frenchDays = [ const frenchDays = [
{ label: t('tools.calendar-converter.texts.label-primidi-1'), value: 1 }, { label: t('tools.calendar-converter.texts.label-duodi-2'), value: 2 }, { label: t('tools.calendar-converter.texts.label-primidi-1'), value: 1 },
{ label: t('tools.calendar-converter.texts.label-tridi-3'), value: 3 }, { label: t('tools.calendar-converter.texts.label-quartidi-4'), value: 4 }, { label: t('tools.calendar-converter.texts.label-duodi-2'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-quintidi-5'), value: 5 }, { label: t('tools.calendar-converter.texts.label-sextidi-6'), value: 6 }, { label: t('tools.calendar-converter.texts.label-tridi-3'), value: 3 },
{ label: t('tools.calendar-converter.texts.label-septidi-7'), value: 7 }, { label: t('tools.calendar-converter.texts.label-octidi-8'), value: 8 }, { label: t('tools.calendar-converter.texts.label-quartidi-4'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-nonidi-9'), value: 9 }, { label: t('tools.calendar-converter.texts.label-décadi-10'), value: 10 }, { label: t('tools.calendar-converter.texts.label-quintidi-5'), value: 5 },
{ label: t('tools.calendar-converter.texts.label-vertu-1'), value: 12 }, { label: t('tools.calendar-converter.texts.label-génie-2'), value: 13 }, { label: t('tools.calendar-converter.texts.label-sextidi-6'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-travail-3'), value: 14 }, { label: t('tools.calendar-converter.texts.label-opinion-4'), value: 15 }, { label: t('tools.calendar-converter.texts.label-septidi-7'), value: 7 },
{ label: t('tools.calendar-converter.texts.label-récompenses-5'), value: 16 }, { label: t('tools.calendar-converter.texts.label-révolution-6'), value: 17 }, { label: t('tools.calendar-converter.texts.label-octidi-8'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-nonidi-9'), value: 9 },
{ label: t('tools.calendar-converter.texts.label-décadi-10'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-vertu-1'), value: 12 },
{ label: t('tools.calendar-converter.texts.label-génie-2'), value: 13 },
{ label: t('tools.calendar-converter.texts.label-travail-3'), value: 14 },
{ label: t('tools.calendar-converter.texts.label-opinion-4'), value: 15 },
{ label: t('tools.calendar-converter.texts.label-récompenses-5'), value: 16 },
{ label: t('tools.calendar-converter.texts.label-révolution-6'), value: 17 },
]; ];
</script> </script>
<template> <template>
<div> <div>
<n-p> <n-p>
{{ t('tools.calendar-converter.texts.tag-this-is-a-port-of-wonderful') }}<c-link target="_blank" href="https://www.fourmilab.ch/documents/calendar"> {{ t('tools.calendar-converter.texts.tag-this-is-a-port-of-wonderful')
{{ t('tools.calendar-converter.texts.tag-fourmilab-ch-calendar-converter') }} }}<c-link target="_blank" href="https://www.fourmilab.ch/documents/calendar">
</c-link>{{ t('tools.calendar-converter.texts.tag-by-john-walker') }} {{ t('tools.calendar-converter.texts.tag-fourmilab-ch-calendar-converter') }} </c-link
>{{ t('tools.calendar-converter.texts.tag-by-john-walker') }}
</n-p> </n-p>
<n-tabs type="line" animated> <n-tabs type="line" animated>
<!-- Gregorian --> <!-- Gregorian -->
@@ -117,7 +138,12 @@ const frenchDays = [
<n-form :model="converter.document.gregorian" label-placement="left"> <n-form :model="converter.document.gregorian" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')"> <n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.gregorian.day" style="width: 90px" mr-1 /> <n-input-number v-model:value="converter.document.gregorian.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.gregorian.month" :options="monthOptions" style="width: 160px; " mr-1 /> <n-select
v-model:value="converter.document.gregorian.month"
:options="monthOptions"
style="width: 160px"
mr-1
/>
<n-input-number v-model:value="converter.document.gregorian.year" style="width: 100px" /> <n-input-number v-model:value="converter.document.gregorian.year" style="width: 100px" />
</n-form-item> </n-form-item>
@@ -141,7 +167,14 @@ const frenchDays = [
<n-button type="primary" mr-1 @click="() => converter.calcGregorian()"> <n-button type="primary" mr-1 @click="() => converter.calcGregorian()">
{{ t('tools.calendar-converter.texts.tag-update-other-calendars') }} {{ t('tools.calendar-converter.texts.tag-update-other-calendars') }}
</n-button> </n-button>
<n-button @click="() => { converter.setDateToToday(); converter.updateFromGregorian(); }"> <n-button
@click="
() => {
converter.setDateToToday();
converter.updateFromGregorian();
}
"
>
{{ t('tools.calendar-converter.texts.tag-today') }} {{ t('tools.calendar-converter.texts.tag-today') }}
</n-button> </n-button>
</n-space> </n-space>
@@ -181,7 +214,12 @@ const frenchDays = [
<n-form :model="converter.document.juliancalendar" label-placement="left"> <n-form :model="converter.document.juliancalendar" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')"> <n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.juliancalendar.day" style="width: 90px" mr-1 /> <n-input-number v-model:value="converter.document.juliancalendar.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.juliancalendar.month" :options="monthOptions" style="width: 160px; " mr-1 /> <n-select
v-model:value="converter.document.juliancalendar.month"
:options="monthOptions"
style="width: 160px"
mr-1
/>
<n-input-number v-model:value="converter.document.juliancalendar.year" style="width: 100px" /> <n-input-number v-model:value="converter.document.juliancalendar.year" style="width: 100px" />
</n-form-item> </n-form-item>
<n-form-item :label="t('tools.calendar-converter.texts.label-leap')"> <n-form-item :label="t('tools.calendar-converter.texts.label-leap')">
@@ -218,7 +256,12 @@ const frenchDays = [
<n-form :model="converter.document.hebrew" label-placement="left"> <n-form :model="converter.document.hebrew" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')"> <n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.hebrew.day" style="width: 90px" mr-1 /> <n-input-number v-model:value="converter.document.hebrew.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.hebrew.month" :options="hebrewMonths" style="width: 220px; " mr-1 /> <n-select
v-model:value="converter.document.hebrew.month"
:options="hebrewMonths"
style="width: 220px"
mr-1
/>
<n-input-number v-model:value="converter.document.hebrew.year" style="width: 100px" /> <n-input-number v-model:value="converter.document.hebrew.year" style="width: 100px" />
</n-form-item> </n-form-item>
@@ -239,7 +282,12 @@ const frenchDays = [
<n-form :model="converter.document.islamic" label-placement="left"> <n-form :model="converter.document.islamic" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')"> <n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.islamic.day" style="width: 90px" mr-1 /> <n-input-number v-model:value="converter.document.islamic.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.islamic.month" :options="islamicMonths" style="width: 250px; " mr-1 /> <n-select
v-model:value="converter.document.islamic.month"
:options="islamicMonths"
style="width: 250px"
mr-1
/>
<n-input-number v-model:value="converter.document.islamic.year" style="width: 100px" /> <n-input-number v-model:value="converter.document.islamic.year" style="width: 100px" />
</n-form-item> </n-form-item>
@@ -264,7 +312,12 @@ const frenchDays = [
<n-form :model="converter.document.persian" label-placement="left"> <n-form :model="converter.document.persian" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')"> <n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.persian.day" style="width: 90px" mr-1 /> <n-input-number v-model:value="converter.document.persian.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.persian.month" :options="persianMonths" style="width: 220px; " mr-1 /> <n-select
v-model:value="converter.document.persian.month"
:options="persianMonths"
style="width: 220px"
mr-1
/>
<n-input-number v-model:value="converter.document.persian.year" style="width: 100px" /> <n-input-number v-model:value="converter.document.persian.year" style="width: 100px" />
</n-form-item> </n-form-item>
@@ -289,7 +342,12 @@ const frenchDays = [
<n-form :model="converter.document.persiana" label-placement="left"> <n-form :model="converter.document.persiana" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')"> <n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.persiana.day" style="width: 90px" mr-1 /> <n-input-number v-model:value="converter.document.persiana.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.persiana.month" :options="persianMonths" style="width: 220px; " mr-1 /> <n-select
v-model:value="converter.document.persiana.month"
:options="persianMonths"
style="width: 220px"
mr-1
/>
<n-input-number v-model:value="converter.document.persiana.year" style="width: 100px" /> <n-input-number v-model:value="converter.document.persiana.year" style="width: 100px" />
</n-form-item> </n-form-item>
@@ -344,7 +402,12 @@ const frenchDays = [
<n-form :model="converter.document.indiancivilcalendar" label-placement="left"> <n-form :model="converter.document.indiancivilcalendar" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')"> <n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.indiancivilcalendar.day" style="width: 90px" mr-1 /> <n-input-number v-model:value="converter.document.indiancivilcalendar.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.indiancivilcalendar.month" :options="indianMonths" style="width: 220px;" mr-1 /> <n-select
v-model:value="converter.document.indiancivilcalendar.month"
:options="indianMonths"
style="width: 220px"
mr-1
/>
<n-input-number v-model:value="converter.document.indiancivilcalendar.year" style="width: 100px" /> <n-input-number v-model:value="converter.document.indiancivilcalendar.year" style="width: 100px" />
</n-form-item> </n-form-item>
<n-form-item :label="t('tools.calendar-converter.texts.label-leap')"> <n-form-item :label="t('tools.calendar-converter.texts.label-leap')">
+16 -1
View File
@@ -5,7 +5,22 @@ export const tool = defineTool({
name: t('tools.calendar-converter.title'), name: t('tools.calendar-converter.title'),
path: '/calendar-converter', path: '/calendar-converter',
description: t('tools.calendar-converter.description'), description: t('tools.calendar-converter.description'),
keywords: ['calendar', 'gregorian', 'julian', 'hebrew', 'islamic', 'persian', 'mayan', 'indian', 'french', 'republican', 'iso-8601', 'unix', 'excel', 'converter'], keywords: [
'calendar',
'gregorian',
'julian',
'hebrew',
'islamic',
'persian',
'mayan',
'indian',
'french',
'republican',
'iso-8601',
'unix',
'excel',
'converter',
],
component: () => import('./calendar-converter.vue'), component: () => import('./calendar-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Calendar')), icon: defineAsyncComponent(() => import('@vicons/tabler/es/Calendar')),
createdAt: new Date('2026-02-21'), createdAt: new Date('2026-02-21'),
+11 -7
View File
@@ -6,7 +6,11 @@ import { useMediaRecorder } from './useMediaRecorder';
const { t } = useI18n(); const { t } = useI18n();
interface Media { type: 'image' | 'video'; value: string; createdAt: Date } interface Media {
type: 'image' | 'video';
value: string;
createdAt: Date;
}
const { const {
videoInputs: cameras, videoInputs: cameras,
@@ -58,11 +62,11 @@ onRecordAvailable((value) => {
}); });
function refreshCurrentDevices() { function refreshCurrentDevices() {
if (_.isNil(currentCamera) || !cameras.value.find(i => i.deviceId === currentCamera.value)) { if (_.isNil(currentCamera) || !cameras.value.find((i) => i.deviceId === currentCamera.value)) {
currentCamera.value = cameras.value[0]?.deviceId; currentCamera.value = cameras.value[0]?.deviceId;
} }
if (_.isNil(microphones) || !microphones.value.find(i => i.deviceId === currentMicrophone.value)) { if (_.isNil(microphones) || !microphones.value.find((i) => i.deviceId === currentMicrophone.value)) {
currentMicrophone.value = microphones.value[0]?.deviceId; currentMicrophone.value = microphones.value[0]?.deviceId;
} }
} }
@@ -92,8 +96,7 @@ onBeforeUnmount(() => stop());
async function requestPermissions() { async function requestPermissions() {
try { try {
await ensurePermissions(); await ensurePermissions();
} } catch (e) {
catch (e) {
permissionCannotBePrompted.value = true; permissionCannotBePrompted.value = true;
} }
} }
@@ -113,7 +116,8 @@ function downloadMedia({ type, value, createdAt }: Media) {
</c-card> </c-card>
<c-card v-else-if="!permissionGranted" text-center> <c-card v-else-if="!permissionGranted" text-center>
{{ t('tools.camera-recorder.texts.tag-you-need-to-grant-permission-to-use-your-camera-and-microphone') }}<c-alert v-if="permissionCannotBePrompted" mt-4 text-left> {{ t('tools.camera-recorder.texts.tag-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 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). your browser settings (usually the lock icon in the address bar).
</c-alert> </c-alert>
@@ -188,7 +192,7 @@ function downloadMedia({ type, value, createdAt }: Media) {
<div grid grid-cols-2 mt-5 gap-2> <div grid grid-cols-2 mt-5 gap-2>
<c-card v-for="({ type, value, createdAt }, index) in medias" :key="index"> <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"> <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 /> <video v-else :src="value" controls max-h-full w-full />
@@ -3,13 +3,13 @@ import { type Ref, computed, ref } from 'vue';
export { useMediaRecorder }; export { useMediaRecorder };
function useMediaRecorder({ stream }: { stream: Ref<MediaStream | undefined> }): { function useMediaRecorder({ stream }: { stream: Ref<MediaStream | undefined> }): {
isRecordingSupported: Ref<boolean> isRecordingSupported: Ref<boolean>;
recordingState: Ref<'stopped' | 'recording' | 'paused'> recordingState: Ref<'stopped' | 'recording' | 'paused'>;
startRecording: () => void startRecording: () => void;
stopRecording: () => void stopRecording: () => void;
pauseRecording: () => void pauseRecording: () => void;
resumeRecording: () => void resumeRecording: () => void;
onRecordAvailable: (cb: (url: string) => void) => void onRecordAvailable: (cb: (url: string) => void) => void;
} { } {
const isRecordingSupported = computed(() => MediaRecorder.isTypeSupported('video/webm')); const isRecordingSupported = computed(() => MediaRecorder.isTypeSupported('video/webm'));
const mediaRecorder = ref<MediaRecorder | null>(null); const mediaRecorder = ref<MediaRecorder | null>(null);
+23 -5
View File
@@ -8,7 +8,7 @@ import { useQueryParamOrStorage } from '@/composable/queryParams';
const { t } = useI18n(); const { t } = useI18n();
const cardKeys = [...Object.keys(cards).filter(k => k !== 'joker'), 'joker', 'joker']; const cardKeys = [...Object.keys(cards).filter((k) => k !== 'joker'), 'joker', 'joker'];
type CardNames = keyof typeof cards; type CardNames = keyof typeof cards;
const numberOfCards = useQueryParamOrStorage({ name: 'cards', storageName: 'card-picker:n', defaultValue: 5 }); const numberOfCards = useQueryParamOrStorage({ name: 'cards', storageName: 'card-picker:n', defaultValue: 5 });
@@ -47,23 +47,41 @@ function translateName(cardId: string) {
const cardPickedString = computed(() => cardPicked.value.map(translateName).join(', ')); const cardPickedString = computed(() => cardPicked.value.map(translateName).join(', '));
const { copy } = useCopy({ source: cardPickedString, text: t('tools.card-picker.texts.text-cards-picked-copied-to-the-clipboard') }); const { copy } = useCopy({
source: cardPickedString,
text: t('tools.card-picker.texts.text-cards-picked-copied-to-the-clipboard'),
});
</script> </script>
<template> <template>
<c-card> <c-card>
<n-space justify="space-around" mb-1> <n-space justify="space-around" mb-1>
<img v-for="(card, index) in cardPicked" :key="index" style="width:90px" mr-1 :src="`data:image/svg+xml;base64,${cards[card as CardNames]}`"> <img
v-for="(card, index) in cardPicked"
:key="index"
style="width: 90px"
mr-1
:src="`data:image/svg+xml;base64,${cards[card as CardNames]}`"
/>
</n-space> </n-space>
<div mb-2> <div mb-2>
<textarea-copyable :value="cardPickedString" readonly mb-1 /> <textarea-copyable :value="cardPickedString" readonly mb-1 />
</div> </div>
<div flex justify-center gap-3> <div flex justify-center gap-3>
<n-form-item :label="t('tools.card-picker.texts.label-number-of-cards')" label-placement="left"> <n-form-item :label="t('tools.card-picker.texts.label-number-of-cards')" label-placement="left">
<n-input-number-i18n v-model:value="numberOfCards" min="1" :max="maxCards" :placeholder="t('tools.card-picker.texts.placeholder-number-of-cards-to-pick')" /> <n-input-number-i18n
v-model:value="numberOfCards"
min="1"
:max="maxCards"
:placeholder="t('tools.card-picker.texts.placeholder-number-of-cards-to-pick')"
/>
</n-form-item> </n-form-item>
<n-form-item :label="t('tools.card-picker.texts.label-number-of-packs')" label-placement="left"> <n-form-item :label="t('tools.card-picker.texts.label-number-of-packs')" label-placement="left">
<n-input-number-i18n v-model:value="numberOfPacks" min="1" :placeholder="t('tools.card-picker.texts.placeholder-number-of-card-packs-to-pick-in')" /> <n-input-number-i18n
v-model:value="numberOfPacks"
min="1"
:placeholder="t('tools.card-picker.texts.placeholder-number-of-card-packs-to-pick-in')"
/>
</n-form-item> </n-form-item>
</div> </div>
<div mb-4 flex justify-center> <div mb-4 flex justify-center>
@@ -194,7 +194,7 @@ describe('certificate-key-parser', async () => {
const { input, pass, type, title } = format; const { input, pass, type, title } = format;
it(`Parse '${title ?? type}' format with right type (${type})`, async () => { it(`Parse '${title ?? type}' format with right type (${type})`, async () => {
const { values } = await getKeyOrCertificateInfosAsync(input, pass); const { values } = await getKeyOrCertificateInfosAsync(input, pass);
const result_type = values.find(v => v.label === 'Type:')?.value; const result_type = values.find((v) => v.label === 'Type:')?.value;
expect(result_type).toBe(type); expect(result_type).toBe(type);
}); });
@@ -1,39 +1,51 @@
import type { Buffer } from 'node:buffer'; import type { Buffer } from 'node:buffer';
import { import { parseCertificate, parseFingerprint, parseKey, parsePrivateKey, parseSignature } from 'sshpk';
parseCertificate, parseFingerprint,
parseKey,
parsePrivateKey,
parseSignature,
} from 'sshpk';
import type { import type {
AlgorithmType, AlgorithmType,
Certificate, Certificate,
CertificateFormat, CertificateFormat,
Fingerprint, Fingerprint,
Key, Key,
PrivateKey, Signature, SignatureFormatType, PrivateKey,
Signature,
SignatureFormatType,
} from 'sshpk'; } from 'sshpk';
import { Base64 } from 'js-base64'; import { Base64 } from 'js-base64';
import * as openpgp from 'openpgp'; import * as openpgp from 'openpgp';
import * as forge from 'node-forge'; import * as forge from 'node-forge';
import { type LabelValue, getCSRLabelValues, getCertificateLabelValues, getFingerprintLabelValues, getPGPPrivateKeyLabelValuesAsync, getPGPPublicKeyLabelValuesAsync, getPrivateKeyLabelValues, getPublicKeyLabelValues, getSignatureLabelValues } from './certificate-key-parser.infos'; import {
type LabelValue,
getCSRLabelValues,
getCertificateLabelValues,
getFingerprintLabelValues,
getPGPPrivateKeyLabelValuesAsync,
getPGPPublicKeyLabelValuesAsync,
getPrivateKeyLabelValues,
getPublicKeyLabelValues,
getSignatureLabelValues,
} from './certificate-key-parser.infos';
import { translate as t } from '@/plugins/i18n.plugin'; import { translate as t } from '@/plugins/i18n.plugin';
export async function getKeysOrCertificatesInfosAsync( export async function getKeysOrCertificatesInfosAsync(
keyOrCertificateValue: string | Buffer, keyOrCertificateValue: string | Buffer,
passphrase: string, passphrase: string,
add_missing_type: string | null = null) { add_missing_type: string | null = null,
) {
if (add_missing_type && !keyOrCertificateValue.toString().trim().startsWith('-----BEGIN')) { if (add_missing_type && !keyOrCertificateValue.toString().trim().startsWith('-----BEGIN')) {
keyOrCertificateValue = `-----BEGIN ${add_missing_type}-----\n${keyOrCertificateValue.toString().trim()}\n-----END ${add_missing_type}-----`; keyOrCertificateValue = `-----BEGIN ${add_missing_type}-----\n${keyOrCertificateValue.toString().trim()}\n-----END ${add_missing_type}-----`;
} }
const parts = keyOrCertificateValue.toString().trim().split(/(-----BEGIN [^-]+-----\n)/).filter(s => s !== ''); const parts = keyOrCertificateValue
.toString()
.trim()
.split(/(-----BEGIN [^-]+-----\n)/)
.filter((s) => s !== '');
if (!parts.length) { if (!parts.length) {
return [await getKeyOrCertificateInfosAsync(keyOrCertificateValue, passphrase)]; return [await getKeyOrCertificateInfosAsync(keyOrCertificateValue, passphrase)];
} }
const parsedPEMs: Array<{ const parsedPEMs: Array<{
values: LabelValue[] values: LabelValue[];
certificateX509DER?: undefined | string certificateX509DER?: undefined | string;
}> = []; }> = [];
for (let i = 0; i < parts.length; i += 2) { for (let i = 0; i < parts.length; i += 2) {
const pemPart = parts[i] + parts[i + 1]; const pemPart = parts[i] + parts[i + 1];
@@ -47,24 +59,24 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
const canParse = (value: string | Buffer, parseFunction: (value: string | Buffer) => any) => { const canParse = (value: string | Buffer, parseFunction: (value: string | Buffer) => any) => {
try { try {
return parseFunction(value); return parseFunction(value);
} } catch {
catch {
return null; return null;
} }
}; };
const canParseAsync = async (value: string | Buffer, parseFunction: (value: string | Buffer) => Promise<any>) => { const canParseAsync = async (value: string | Buffer, parseFunction: (value: string | Buffer) => Promise<any>) => {
try { try {
return await parseFunction(value); return await parseFunction(value);
} } catch {
catch {
return null; return null;
} }
}; };
const inputKeyOrCertificateValue = (typeof keyOrCertificateValue === 'string' ? keyOrCertificateValue?.trim() : keyOrCertificateValue); const inputKeyOrCertificateValue =
typeof keyOrCertificateValue === 'string' ? keyOrCertificateValue?.trim() : keyOrCertificateValue;
const privateKey = canParse(inputKeyOrCertificateValue, const privateKey = canParse(inputKeyOrCertificateValue, (value) =>
value => parsePrivateKey(value, 'auto', { passphrase })) as PrivateKey; parsePrivateKey(value, 'auto', { passphrase }),
) as PrivateKey;
if (privateKey) { if (privateKey) {
return { return {
values: getPrivateKeyLabelValues(privateKey), values: getPrivateKeyLabelValues(privateKey),
@@ -76,12 +88,16 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
return { values: getPublicKeyLabelValues(publicKey) }; return { values: getPublicKeyLabelValues(publicKey) };
} }
const pgpPrivateKey = await canParseAsync(inputKeyOrCertificateValue, value => openpgp.readPrivateKey({ armoredKey: value.toString() })) as openpgp.Key; const pgpPrivateKey = (await canParseAsync(inputKeyOrCertificateValue, (value) =>
openpgp.readPrivateKey({ armoredKey: value.toString() }),
)) as openpgp.Key;
if (pgpPrivateKey) { if (pgpPrivateKey) {
return { values: await getPGPPrivateKeyLabelValuesAsync(pgpPrivateKey) }; return { values: await getPGPPrivateKeyLabelValuesAsync(pgpPrivateKey) };
} }
const pgpPublicKey = await canParseAsync(inputKeyOrCertificateValue, value => openpgp.readKey({ armoredKey: value.toString() })) as openpgp.Key; const pgpPublicKey = (await canParseAsync(inputKeyOrCertificateValue, (value) =>
openpgp.readKey({ armoredKey: value.toString() }),
)) as openpgp.Key;
if (pgpPublicKey) { if (pgpPublicKey) {
return { values: await getPGPPublicKeyLabelValuesAsync(pgpPublicKey) }; return { values: await getPGPPublicKeyLabelValuesAsync(pgpPublicKey) };
} }
@@ -90,8 +106,7 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
for (const format of ['openssh', 'pem', 'x509']) { for (const format of ['openssh', 'pem', 'x509']) {
try { try {
return parseCertificate(value, format as CertificateFormat); return parseCertificate(value, format as CertificateFormat);
} } catch {}
catch {}
} }
return null; return null;
}) as Certificate; }) as Certificate;
@@ -99,18 +114,15 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
let certificateX509DER = ''; let certificateX509DER = '';
try { try {
certificateX509DER = Base64.fromUint8Array(cert.toBuffer('x509')); certificateX509DER = Base64.fromUint8Array(cert.toBuffer('x509'));
} } catch {}
catch {}
let forgeCertificate: forge.pki.Certificate | null = null; let forgeCertificate: forge.pki.Certificate | null = null;
try { try {
forgeCertificate = forge.pki.certificateFromPem(inputKeyOrCertificateValue?.toString(), false, false); forgeCertificate = forge.pki.certificateFromPem(inputKeyOrCertificateValue?.toString(), false, false);
} } catch {}
catch {}
if (!forgeCertificate) { if (!forgeCertificate) {
try { try {
forgeCertificate = forge.pki.certificateFromAsn1(inputKeyOrCertificateValue as never, false); forgeCertificate = forge.pki.certificateFromAsn1(inputKeyOrCertificateValue as never, false);
} } catch {}
catch {}
} }
return { values: getCertificateLabelValues(cert, forgeCertificate), certificateX509DER }; return { values: getCertificateLabelValues(cert, forgeCertificate), certificateX509DER };
@@ -123,7 +135,9 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
return { values: getCSRLabelValues(csr) }; return { values: getCSRLabelValues(csr) };
} }
const fingerprint = canParse(inputKeyOrCertificateValue, value => parseFingerprint(value.toString())) as Fingerprint; const fingerprint = canParse(inputKeyOrCertificateValue, (value) =>
parseFingerprint(value.toString()),
) as Fingerprint;
if (fingerprint) { if (fingerprint) {
return { values: getFingerprintLabelValues(fingerprint) }; return { values: getFingerprintLabelValues(fingerprint) };
} }
@@ -134,8 +148,7 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
for (const format of ['asn1', 'ssh', 'raw']) { for (const format of ['asn1', 'ssh', 'raw']) {
try { try {
return parseSignature(value, algo as AlgorithmType, format as SignatureFormatType); return parseSignature(value, algo as AlgorithmType, format as SignatureFormatType);
} } catch {}
catch {}
} }
} }
return null; return null;
@@ -149,16 +162,17 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
{ {
label: t('tools.certificate-key-parser.service.text.type'), label: t('tools.certificate-key-parser.service.text.type'),
value: t('tools.certificate-key-parser.service.text.unknown-format-or-invalid-passphrase'), value: t('tools.certificate-key-parser.service.text.unknown-format-or-invalid-passphrase'),
}], },
],
}; };
} } catch (e: any) {
catch (e: any) {
return { return {
values: [ values: [
{ {
label: t('tools.certificate-key-parser.service.text.error'), label: t('tools.certificate-key-parser.service.text.error'),
value: e.toString(), value: e.toString(),
}] as LabelValue[], },
] as LabelValue[],
}; };
} }
} }
@@ -28,8 +28,7 @@ async function onUpload(file: File) {
} }
const certificateX509DER = ref(''); const certificateX509DER = ref('');
const { download: downloadX509DER } = useDownloadFileFromBase64( const { download: downloadX509DER } = useDownloadFileFromBase64({
{
source: certificateX509DER, source: certificateX509DER,
extension: 'der', extension: 'der',
}); });
@@ -41,8 +40,7 @@ function downloadX509DERFile() {
try { try {
downloadX509DER(); downloadX509DER();
} } catch (_) {
catch (_) {
// //
} }
} }
@@ -53,8 +51,7 @@ const parsedSections = computedAsync<LabelValue[][]>(async () => {
let inputKeyOrCertificateValue: string | Buffer = ''; let inputKeyOrCertificateValue: string | Buffer = '';
if (inputType.value === 'file' && file) { if (inputType.value === 'file' && file) {
inputKeyOrCertificateValue = file; inputKeyOrCertificateValue = file;
} } else if (inputType.value === 'content' && inputContent) {
else if (inputType.value === 'content' && inputContent) {
inputKeyOrCertificateValue = inputContent; inputKeyOrCertificateValue = inputContent;
} }
try { try {
@@ -63,15 +60,11 @@ const parsedSections = computedAsync<LabelValue[][]>(async () => {
const { values, certificateX509DER: certPEM } = parsed[0]; const { values, certificateX509DER: certPEM } = parsed[0];
certificateX509DER.value = certPEM || ''; certificateX509DER.value = certPEM || '';
return [values]; return [values];
} else {
return parsed.map((p) => p.values);
} }
else { } catch (e: any) {
return parsed.map(p => p.values); return [[{ label: t('tools.certificate-key-parser.texts.label-parsing-error'), value: e.toString() }]];
}
}
catch (e: any) {
return [
[{ label: t('tools.certificate-key-parser.texts.label-parsing-error'), value: e.toString() }],
];
} }
}); });
@@ -83,7 +76,10 @@ const pemHeaders = [
{ label: t('tools.certificate-key-parser.texts.private-key-pkcs-8'), value: 'PRIVATE KEY' }, { label: t('tools.certificate-key-parser.texts.private-key-pkcs-8'), value: 'PRIVATE KEY' },
{ label: t('tools.certificate-key-parser.texts.public-key-pkcs-8'), value: 'PUBLIC KEY' }, { label: t('tools.certificate-key-parser.texts.public-key-pkcs-8'), value: 'PUBLIC KEY' },
{ label: t('tools.certificate-key-parser.texts.encrypted-private-key-pkcs-8-encrypted'), value: 'ENCRYPTED PRIVATE KEY' }, {
label: t('tools.certificate-key-parser.texts.encrypted-private-key-pkcs-8-encrypted'),
value: 'ENCRYPTED PRIVATE KEY',
},
{ label: t('tools.certificate-key-parser.texts.rsa-private-key-pkcs-1'), value: 'RSA PRIVATE KEY' }, { label: t('tools.certificate-key-parser.texts.rsa-private-key-pkcs-1'), value: 'RSA PRIVATE KEY' },
{ label: t('tools.certificate-key-parser.texts.rsa-public-key-pkcs-1'), value: 'RSA PUBLIC KEY' }, { label: t('tools.certificate-key-parser.texts.rsa-public-key-pkcs-1'), value: 'RSA PUBLIC KEY' },
@@ -107,28 +103,34 @@ const pemHeaders = [
<c-card> <c-card>
<n-radio-group v-model:value="inputType" name="radiogroup" mb-2 flex justify-center> <n-radio-group v-model:value="inputType" name="radiogroup" mb-2 flex justify-center>
<n-space> <n-space>
<n-radio <n-radio value="file" :label="t('tools.certificate-key-parser.texts.label-file')" />
value="file" <n-radio value="content" :label="t('tools.certificate-key-parser.texts.label-content')" />
:label="t('tools.certificate-key-parser.texts.label-file')"
/>
<n-radio
value="content"
:label="t('tools.certificate-key-parser.texts.label-content')"
/>
</n-space> </n-space>
</n-radio-group> </n-radio-group>
<c-file-upload <c-file-upload
v-if="inputType === 'file'" v-if="inputType === 'file'"
:title="t('tools.certificate-key-parser.texts.title-drag-and-drop-a-certificate-file-here-or-click-to-select-a-certificate-file')" :title="
t(
'tools.certificate-key-parser.texts.title-drag-and-drop-a-certificate-file-here-or-click-to-select-a-certificate-file',
)
"
@file-upload="onUpload" @file-upload="onUpload"
/> />
<c-input-text <c-input-text
v-if="inputType === 'content'" v-if="inputType === 'content'"
v-model:value="inputKeyOrCertificate" v-model:value="inputKeyOrCertificate"
:label="t('tools.certificate-key-parser.texts.label-paste-your-public-key-private-key-signature-fingerprint-certificate')" :label="
:placeholder="t('tools.certificate-key-parser.texts.placeholder-your-public-key-private-key-signature-fingerprint-certificate')" t(
'tools.certificate-key-parser.texts.label-paste-your-public-key-private-key-signature-fingerprint-certificate',
)
"
:placeholder="
t(
'tools.certificate-key-parser.texts.placeholder-your-public-key-private-key-signature-fingerprint-certificate',
)
"
multiline multiline
rows="8" rows="8"
data-test-id="input" data-test-id="input"
@@ -155,11 +157,7 @@ const pemHeaders = [
<n-divider /> <n-divider />
<c-card <c-card v-for="(part, partIndex) of parsedSections" :key="partIndex" mb-2>
v-for="(part, partIndex) of parsedSections"
:key="partIndex"
mb-2
>
<input-copyable <input-copyable
v-for="{ label, value, multiline } of part" v-for="{ label, value, multiline } of part"
:key="label" :key="label"
@@ -168,8 +166,8 @@ const pemHeaders = [
label-position="left" label-position="left"
label-width="100px" label-width="100px"
label-align="right" label-align="right"
autosize
autosize mb-2 mb-2
:multiline="multiline" :multiline="multiline"
:value="value" :value="value"
:placeholder="t('tools.certificate-key-parser.texts.placeholder-not-set')" :placeholder="t('tools.certificate-key-parser.texts.placeholder-not-set')"
+2 -1
View File
@@ -1,4 +1,5 @@
{"2.5.4.3": "CN", {
"2.5.4.3": "CN",
"2.5.4.4": "Surname", "2.5.4.4": "Surname",
"2.5.4.6": "C", "2.5.4.6": "C",
"2.5.4.7": "Cidade", "2.5.4.7": "Cidade",
@@ -17,15 +17,13 @@ async function getUInt8ArrayFromInputs() {
const file = fileInput.value; const file = fileInput.value;
if (inputType.value === 'file' && file) { if (inputType.value === 'file' && file) {
return new Uint8Array(await file.arrayBuffer()); return new Uint8Array(await file.arrayBuffer());
} } else if (inputType.value === 'content' && fileContentValue) {
else if (inputType.value === 'content' && fileContentValue) {
const uint8Array = new Uint8Array(fileContentValue.length); const uint8Array = new Uint8Array(fileContentValue.length);
for (let i = 0; i < fileContentValue.length; i++) { for (let i = 0; i < fileContentValue.length; i++) {
uint8Array[i] = fileContentValue.charCodeAt(i); uint8Array[i] = fileContentValue.charCodeAt(i);
} }
return uint8Array; return uint8Array;
} } else {
else {
return null; return null;
} }
} }
@@ -38,8 +36,7 @@ const encodings = computedAsync(async () => {
return null; return null;
} }
return chardet.analyse(buffer); return chardet.analyse(buffer);
} } catch (e: any) {
catch (e: any) {
error.value = e.toString(); error.value = e.toString();
return null; return null;
} }
@@ -54,8 +51,7 @@ async function generateEncodedOutput(encoding: string) {
return; return;
} }
contentDecoded.value = iconv.decode(Buffer.from(buffer), encoding); contentDecoded.value = iconv.decode(Buffer.from(buffer), encoding);
} } catch (e: any) {
catch (e: any) {
return e.toString(); return e.toString();
} }
} }
@@ -68,18 +64,12 @@ function onUpload(file: File) {
</script> </script>
<template> <template>
<div style="max-width: 600px;"> <div style="max-width: 600px">
<c-card :title="t('tools.charset-detector.texts.title-input')" mb-2> <c-card :title="t('tools.charset-detector.texts.title-input')" mb-2>
<n-radio-group v-model:value="inputType" name="radiogroup" mb-2 flex justify-center> <n-radio-group v-model:value="inputType" name="radiogroup" mb-2 flex justify-center>
<n-space> <n-space>
<n-radio <n-radio value="file" :label="t('tools.charset-detector.texts.label-file')" />
value="file" <n-radio value="content" :label="t('tools.charset-detector.texts.label-content')" />
:label="t('tools.charset-detector.texts.label-file')"
/>
<n-radio
value="content"
:label="t('tools.charset-detector.texts.label-content')"
/>
</n-space> </n-space>
</n-radio-group> </n-radio-group>
@@ -121,10 +111,7 @@ function onUpload(file: File) {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr <tr v-for="(enc, index) in encodings || []" :key="index">
v-for="(enc, index) in encodings || []"
:key="index"
>
<td> <td>
{{ enc.confidence }} {{ enc.confidence }}
</td> </td>
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { computeChmodOctalRepresentation, computeChmodSymbolicRepresentation, computePermissionsFromChmodOctalRepresentation, computePermissionsFromChmodSymbolicRepresentation, computeUmaskRepresentation } from './chmod-calculator.service'; import {
computeChmodOctalRepresentation,
computeChmodSymbolicRepresentation,
computePermissionsFromChmodOctalRepresentation,
computePermissionsFromChmodSymbolicRepresentation,
computeUmaskRepresentation,
} from './chmod-calculator.service';
describe('chmod-calculator', () => { describe('chmod-calculator', () => {
describe('computeChmodOctalRepresentation', () => { describe('computeChmodOctalRepresentation', () => {
@@ -248,90 +254,70 @@ describe('chmod-calculator', () => {
}); });
it('get permissions from octal representation', () => { it('get permissions from octal representation', () => {
expect( expect(computePermissionsFromChmodOctalRepresentation('777')).to.eql({
computePermissionsFromChmodOctalRepresentation('777'),
).to.eql({
owner: { read: true, write: true, execute: true }, owner: { read: true, write: true, execute: true },
group: { read: true, write: true, execute: true }, group: { read: true, write: true, execute: true },
public: { read: true, write: true, execute: true }, public: { read: true, write: true, execute: true },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('000')).to.eql({
computePermissionsFromChmodOctalRepresentation('000'),
).to.eql({
owner: { read: false, write: false, execute: false }, owner: { read: false, write: false, execute: false },
group: { read: false, write: false, execute: false }, group: { read: false, write: false, execute: false },
public: { read: false, write: false, execute: false }, public: { read: false, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('235')).to.eql({
computePermissionsFromChmodOctalRepresentation('235'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: true }, group: { read: false, write: true, execute: true },
public: { read: true, write: false, execute: true }, public: { read: true, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('421')).to.eql({
computePermissionsFromChmodOctalRepresentation('421'),
).to.eql({
owner: { read: true, write: false, execute: false }, owner: { read: true, write: false, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: false, execute: true }, public: { read: false, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('124')).to.eql({
computePermissionsFromChmodOctalRepresentation('124'),
).to.eql({
owner: { read: false, write: false, execute: true }, owner: { read: false, write: false, execute: true },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: true, write: false, execute: false }, public: { read: true, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('222')).to.eql({
computePermissionsFromChmodOctalRepresentation('222'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false }, public: { read: false, write: true, execute: false },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('7222')).to.eql({
computePermissionsFromChmodOctalRepresentation('7222'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false }, public: { read: false, write: true, execute: false },
flags: { setuid: true, setgid: true, stickybit: true }, flags: { setuid: true, setgid: true, stickybit: true },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('4222')).to.eql({
computePermissionsFromChmodOctalRepresentation('4222'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false }, public: { read: false, write: true, execute: false },
flags: { setuid: true, setgid: false, stickybit: false }, flags: { setuid: true, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('2222')).to.eql({
computePermissionsFromChmodOctalRepresentation('2222'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false }, public: { read: false, write: true, execute: false },
flags: { setuid: false, setgid: true, stickybit: false }, flags: { setuid: false, setgid: true, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodOctalRepresentation('1222')).to.eql({
computePermissionsFromChmodOctalRepresentation('1222'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false }, public: { read: false, write: true, execute: false },
@@ -346,107 +332,83 @@ describe('chmod-calculator', () => {
}); });
it('get permissions from symbolic representation', () => { it('get permissions from symbolic representation', () => {
expect( expect(computePermissionsFromChmodSymbolicRepresentation('dr-xr-xr-x')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('dr-xr-xr-x'),
).to.eql({
owner: { read: true, write: false, execute: true }, owner: { read: true, write: false, execute: true },
group: { read: true, write: false, execute: true }, group: { read: true, write: false, execute: true },
public: { read: true, write: false, execute: true }, public: { read: true, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('-rw-r--r--')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('-rw-r--r--'),
).to.eql({
owner: { read: true, write: true, execute: false }, owner: { read: true, write: true, execute: false },
group: { read: true, write: false, execute: false }, group: { read: true, write: false, execute: false },
public: { read: true, write: false, execute: false }, public: { read: true, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('rwxrwxrwx')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('rwxrwxrwx'),
).to.eql({
owner: { read: true, write: true, execute: true }, owner: { read: true, write: true, execute: true },
group: { read: true, write: true, execute: true }, group: { read: true, write: true, execute: true },
public: { read: true, write: true, execute: true }, public: { read: true, write: true, execute: true },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('---------')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('---------'),
).to.eql({
owner: { read: false, write: false, execute: false }, owner: { read: false, write: false, execute: false },
group: { read: false, write: false, execute: false }, group: { read: false, write: false, execute: false },
public: { read: false, write: false, execute: false }, public: { read: false, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('r---wxr-x')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('r---wxr-x'),
).to.eql({
owner: { read: true, write: false, execute: false }, owner: { read: true, write: false, execute: false },
group: { read: false, write: true, execute: true }, group: { read: false, write: true, execute: true },
public: { read: true, write: false, execute: true }, public: { read: true, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('r---w---x')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('r---w---x'),
).to.eql({
owner: { read: true, write: false, execute: false }, owner: { read: true, write: false, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: false, execute: true }, public: { read: false, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('--x-w-r--')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('--x-w-r--'),
).to.eql({
owner: { read: false, write: false, execute: true }, owner: { read: false, write: false, execute: true },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: true, write: false, execute: false }, public: { read: true, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('-w--w--w-')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('-w--w--w-'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false }, public: { read: false, write: true, execute: false },
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('-ws-ws-wt')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('-ws-ws-wt'),
).to.eql({
owner: { read: false, write: true, execute: true }, owner: { read: false, write: true, execute: true },
group: { read: false, write: true, execute: true }, group: { read: false, write: true, execute: true },
public: { read: false, write: true, execute: true }, public: { read: false, write: true, execute: true },
flags: { setuid: true, setgid: true, stickybit: true }, flags: { setuid: true, setgid: true, stickybit: true },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('-ws-w--w-')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('-ws-w--w-'),
).to.eql({
owner: { read: false, write: true, execute: true }, owner: { read: false, write: true, execute: true },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false }, public: { read: false, write: true, execute: false },
flags: { setuid: true, setgid: false, stickybit: false }, flags: { setuid: true, setgid: false, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('-w--ws-w-')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('-w--ws-w-'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: true }, group: { read: false, write: true, execute: true },
public: { read: false, write: true, execute: false }, public: { read: false, write: true, execute: false },
flags: { setuid: false, setgid: true, stickybit: false }, flags: { setuid: false, setgid: true, stickybit: false },
}); });
expect( expect(computePermissionsFromChmodSymbolicRepresentation('-w--w--wt')).to.eql({
computePermissionsFromChmodSymbolicRepresentation('-w--w--wt'),
).to.eql({
owner: { read: false, write: true, execute: false }, owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false }, group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: true }, public: { read: false, write: true, execute: true },
@@ -3,7 +3,13 @@ import type { GroupPermissions, Permissions, SpecialPermissions } from './chmod-
import { translate as t } from '@/plugins/i18n.plugin'; import { translate as t } from '@/plugins/i18n.plugin';
export { computeUmaskRepresentation, computeChmodOctalRepresentation, computeChmodSymbolicRepresentation, computePermissionsFromChmodOctalRepresentation, computePermissionsFromChmodSymbolicRepresentation }; export {
computeUmaskRepresentation,
computeChmodOctalRepresentation,
computeChmodSymbolicRepresentation,
computePermissionsFromChmodOctalRepresentation,
computePermissionsFromChmodSymbolicRepresentation,
};
function computeChmodOctalRepresentation({ permissions }: { permissions: Permissions }): string { function computeChmodOctalRepresentation({ permissions }: { permissions: Permissions }): string {
const permissionValue = { read: 4, write: 2, execute: 1 }; const permissionValue = { read: 4, write: 2, execute: 1 };
@@ -12,7 +18,11 @@ function computeChmodOctalRepresentation({ permissions }: { permissions: Permiss
const getGroupPermissionValue = (permission: GroupPermissions) => const getGroupPermissionValue = (permission: GroupPermissions) =>
_.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(permissionValue, key, 0) : 0), 0); _.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(permissionValue, key, 0) : 0), 0);
const getSpecialPermissionValue = (permission: SpecialPermissions) => { const getSpecialPermissionValue = (permission: SpecialPermissions) => {
const octalValue = _.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(specialPermissionValue, key, 0) : 0), 0); const octalValue = _.reduce(
permission,
(acc, isPermSet, key) => acc + (isPermSet ? _.get(specialPermissionValue, key, 0) : 0),
0,
);
return octalValue > 0 ? octalValue.toString() : ''; return octalValue > 0 ? octalValue.toString() : '';
}; };
@@ -29,8 +39,14 @@ function computeChmodSymbolicRepresentation({ permissions }: { permissions: Perm
const specialFlagPermission = 'execute'; const specialFlagPermission = 'execute';
const getGroupPermissionValue = (permission: GroupPermissions, specialFlag: null | 's' | 't') => const getGroupPermissionValue = (permission: GroupPermissions, specialFlag: null | 's' | 't') =>
_.reduce(permission, (acc, isPermSet, key) => acc + ((key === specialFlagPermission ? specialFlag : undefined) _.reduce(
|| (isPermSet ? _.get(permissionValue, key, '') : '-')), ''); permission,
(acc, isPermSet, key) =>
acc +
((key === specialFlagPermission ? specialFlag : undefined) ||
(isPermSet ? _.get(permissionValue, key, '') : '-')),
'',
);
return [ return [
getGroupPermissionValue(permissions.owner, permissions.flags?.setuid ? 's' : null), getGroupPermissionValue(permissions.owner, permissions.flags?.setuid ? 's' : null),
@@ -44,11 +60,16 @@ function computePermissionsFromChmodOctalRepresentation(octalPermissions: string
const specialPermissionValue = { setuid: 4, setgid: 2, stickybit: 1 }; const specialPermissionValue = { setuid: 4, setgid: 2, stickybit: 1 };
if (!octalPermissions || !octalPermissions.match(/^[0-7]{3,4}$/)) { if (!octalPermissions || !octalPermissions.match(/^[0-7]{3,4}$/)) {
throw new Error(t('tools.chmod-calculator.service.text.invalid-octal-permissions-must-be-3-or-4-octal-digits-octalpermissions', [octalPermissions])); throw new Error(
t('tools.chmod-calculator.service.text.invalid-octal-permissions-must-be-3-or-4-octal-digits-octalpermissions', [
octalPermissions,
]),
);
} }
const fullOctalPermissions = octalPermissions.length === 3 ? `0${octalPermissions}` : octalPermissions; const fullOctalPermissions = octalPermissions.length === 3 ? `0${octalPermissions}` : octalPermissions;
const hasSet = (position: number, flagValue: number) => (Number(fullOctalPermissions[position]) & flagValue) === flagValue; const hasSet = (position: number, flagValue: number) =>
(Number(fullOctalPermissions[position]) & flagValue) === flagValue;
function computePermissionObject<T>(permissionSet: object, position: number): T { function computePermissionObject<T>(permissionSet: object, position: number): T {
return _.reduce(permissionSet, (acc, flag, key) => ({ ...acc, [key]: hasSet(position, flag) }), {}) as T; return _.reduce(permissionSet, (acc, flag, key) => ({ ...acc, [key]: hasSet(position, flag) }), {}) as T;
} }
@@ -67,51 +88,56 @@ function computePermissionsFromChmodOctalRepresentation(octalPermissions: string
function computePermissionsFromChmodSymbolicRepresentation(symbolicPermissions: string): Permissions { function computePermissionsFromChmodSymbolicRepresentation(symbolicPermissions: string): Permissions {
const formatRegex = /^[-dlbcsp]?([r-])([w-])([xs-])([r-])([w-])([xs-])([r-])([w-])([xt-])$/; const formatRegex = /^[-dlbcsp]?([r-])([w-])([xs-])([r-])([w-])([xs-])([r-])([w-])([xt-])$/;
if (!symbolicPermissions || !symbolicPermissions.match(formatRegex)) { if (!symbolicPermissions || !symbolicPermissions.match(formatRegex)) {
throw new Error(t('tools.chmod-calculator.service.text.invalid-string-permissions-must-be-in-form-rwxrwxrwx-symbolicpermissions', [symbolicPermissions])); throw new Error(
t(
'tools.chmod-calculator.service.text.invalid-string-permissions-must-be-in-form-rwxrwxrwx-symbolicpermissions',
[symbolicPermissions],
),
);
} }
const [_, rOwner, wOwner, xOwner, rGroup, wGroup, xGroup, rAll, wAll, xAll] = formatRegex.exec(symbolicPermissions) || []; const [_, rOwner, wOwner, xOwner, rGroup, wGroup, xGroup, rAll, wAll, xAll] =
const getOctal = (flag: string, flagLetter: string, flagValue: number) => flag === flagLetter ? flagValue : 0; formatRegex.exec(symbolicPermissions) || [];
const owner = getOctal(rOwner, 'r', 4) const getOctal = (flag: string, flagLetter: string, flagValue: number) => (flag === flagLetter ? flagValue : 0);
+ getOctal(wOwner, 'w', 2) const owner =
+ getOctal(xOwner, 'x', 1) + getOctal(xOwner, 's', 1); getOctal(rOwner, 'r', 4) + getOctal(wOwner, 'w', 2) + getOctal(xOwner, 'x', 1) + getOctal(xOwner, 's', 1);
const groups = getOctal(rGroup, 'r', 4) const groups =
+ getOctal(wGroup, 'w', 2) getOctal(rGroup, 'r', 4) + getOctal(wGroup, 'w', 2) + getOctal(xGroup, 'x', 1) + getOctal(xGroup, 's', 1);
+ getOctal(xGroup, 'x', 1) + getOctal(xGroup, 's', 1); const all = getOctal(rAll, 'r', 4) + getOctal(wAll, 'w', 2) + getOctal(xAll, 'x', 1) + getOctal(xAll, 't', 1);
const all = getOctal(rAll, 'r', 4) const flags = getOctal(xOwner, 's', 4) + getOctal(xGroup, 's', 2) + getOctal(xAll, 't', 1);
+ getOctal(wAll, 'w', 2) const octalString = `${flags > 0 ? flags : ''}${owner}${groups}${all}`;
+ getOctal(xAll, 'x', 1) + getOctal(xAll, 't', 1);
const flags = getOctal(xOwner, 's', 4)
+ getOctal(xGroup, 's', 2)
+ getOctal(xAll, 't', 1);
const octalString = `${(flags > 0 ? flags : '')}${owner}${groups}${all}`;
return computePermissionsFromChmodOctalRepresentation(octalString); return computePermissionsFromChmodOctalRepresentation(octalString);
} }
function computeUmaskRepresentation({ permissions }: { permissions: Permissions }): { function computeUmaskRepresentation({ permissions }: { permissions: Permissions }): {
octal: string octal: string;
symbolic: string symbolic: string;
} { } {
const permissionValue = { read: 'r', write: 'w', execute: 'x' }; const permissionValue = { read: 'r', write: 'w', execute: 'x' };
const getGroupPermissionValue = (permission: GroupPermissions) => const getGroupPermissionValue = (permission: GroupPermissions) =>
_.reduce(permission, (acc, isPermSet, key) => acc + ((isPermSet ? _.get(permissionValue, key, '') : '')), ''); _.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(permissionValue, key, '') : ''), '');
const symbolic = `umask u=${getGroupPermissionValue(permissions.owner)},g=${getGroupPermissionValue(permissions.group)},o=${getGroupPermissionValue(permissions.public)}`; const symbolic = `umask u=${getGroupPermissionValue(permissions.owner)},g=${getGroupPermissionValue(permissions.group)},o=${getGroupPermissionValue(permissions.public)}`;
const octal = (0o777 - Number.parseInt( const octal = (
0o777 -
Number.parseInt(
computeChmodOctalRepresentation({ computeChmodOctalRepresentation({
permissions: permissions: {
{
owner: permissions.owner, owner: permissions.owner,
group: permissions.group, group: permissions.group,
public: permissions.public, public: permissions.public,
flags: { setuid: false, setgid: false, stickybit: false }, flags: { setuid: false, setgid: false, stickybit: false },
}, },
}), 8)) }),
8,
)
)
.toString(8) .toString(8)
.padStart(3, '0'); .padStart(3, '0');
return { return {
symbolic, octal, symbolic,
octal,
}; };
} }
@@ -13,5 +13,5 @@ export type SpecialPermissions = {
export type Permissions = { export type Permissions = {
[k in Group]: GroupPermissions; [k in Group]: GroupPermissions;
} & { } & {
flags: SpecialPermissions flags: SpecialPermissions;
}; };
+28 -20
View File
@@ -3,7 +3,13 @@ import { useI18n } from 'vue-i18n';
import { useThemeVars } from 'naive-ui'; import { useThemeVars } from 'naive-ui';
import InputCopyable from '../../components/InputCopyable.vue'; import InputCopyable from '../../components/InputCopyable.vue';
import { computeChmodOctalRepresentation, computeChmodSymbolicRepresentation, computePermissionsFromChmodOctalRepresentation, computePermissionsFromChmodSymbolicRepresentation, computeUmaskRepresentation } from './chmod-calculator.service'; import {
computeChmodOctalRepresentation,
computeChmodSymbolicRepresentation,
computePermissionsFromChmodOctalRepresentation,
computePermissionsFromChmodSymbolicRepresentation,
computeUmaskRepresentation,
} from './chmod-calculator.service';
import type { Group, Scope } from './chmod-calculator.types'; import type { Group, Scope } from './chmod-calculator.types';
import { useValidation } from '@/composable/validation'; import { useValidation } from '@/composable/validation';
@@ -36,23 +42,19 @@ const octalPermissionsInputValidation = useValidation({
try { try {
computePermissionsFromChmodOctalRepresentation(value.trim()); computePermissionsFromChmodOctalRepresentation(value.trim());
return true; return true;
} } catch {
catch {
return false; return false;
} }
}, },
}, },
], ],
}); });
watch( watch(octalPermissionsInput, (newPermissions) => {
octalPermissionsInput,
(newPermissions) => {
if (!octalPermissionsInputValidation.isValid) { if (!octalPermissionsInputValidation.isValid) {
return; return;
} }
permissions.value = computePermissionsFromChmodOctalRepresentation(newPermissions.trim()); permissions.value = computePermissionsFromChmodOctalRepresentation(newPermissions.trim());
}, });
);
const symbolicPermissionsInput = ref('---------'); const symbolicPermissionsInput = ref('---------');
const symbolicPermissionsInputValidation = useValidation({ const symbolicPermissionsInputValidation = useValidation({
@@ -64,23 +66,19 @@ const symbolicPermissionsInputValidation = useValidation({
try { try {
computePermissionsFromChmodSymbolicRepresentation(value.trim()); computePermissionsFromChmodSymbolicRepresentation(value.trim());
return true; return true;
} } catch {
catch {
return false; return false;
} }
}, },
}, },
], ],
}); });
watch( watch(symbolicPermissionsInput, (newPermissions) => {
symbolicPermissionsInput,
(newPermissions) => {
if (!symbolicPermissionsInputValidation.isValid) { if (!symbolicPermissionsInputValidation.isValid) {
return; return;
} }
permissions.value = computePermissionsFromChmodSymbolicRepresentation(newPermissions.trim()); permissions.value = computePermissionsFromChmodSymbolicRepresentation(newPermissions.trim());
}, });
);
const octal = computed(() => computeChmodOctalRepresentation({ permissions: permissions.value })); const octal = computed(() => computeChmodOctalRepresentation({ permissions: permissions.value }));
const symbolic = computed(() => computeChmodSymbolicRepresentation({ permissions: permissions.value })); const symbolic = computed(() => computeChmodSymbolicRepresentation({ permissions: permissions.value }));
@@ -90,9 +88,7 @@ const umask = computed(() => computeUmaskRepresentation({ permissions: permissio
<template> <template>
<div> <div>
<div mb-2 flex justify-center> <div mb-2 flex justify-center>
<c-link target="_blank" to="/chmod-memo"> <c-link target="_blank" to="/chmod-memo"> See <code>chmod</code> command cheatsheet. </c-link>
See <code>chmod</code> command cheatsheet.
</c-link>
</div> </div>
<n-space justify="center"> <n-space justify="center">
@@ -169,8 +165,20 @@ const umask = computed(() => computeUmaskRepresentation({ permissions: permissio
</c-card> </c-card>
<c-card :title="t('tools.chmod-calculator.texts.title-umask')"> <c-card :title="t('tools.chmod-calculator.texts.title-umask')">
<InputCopyable :label="t('tools.chmod-calculator.texts.label-octal')" label-position="left" label-width="100px" :value="umask.octal" readonly /> <InputCopyable
<InputCopyable :label="t('tools.chmod-calculator.texts.label-symbolic')" label-position="left" label-width="100px" :value="umask.symbolic" readonly /> :label="t('tools.chmod-calculator.texts.label-octal')"
label-position="left"
label-width="100px"
:value="umask.octal"
readonly
/>
<InputCopyable
:label="t('tools.chmod-calculator.texts.label-symbolic')"
label-position="left"
label-width="100px"
:value="umask.symbolic"
readonly
/>
</c-card> </c-card>
</div> </div>
</template> </template>
+10 -4
View File
@@ -23,14 +23,18 @@ async function loadMemo(currentLocale = locale.value) {
memoComponent.value = module.default ?? module; memoComponent.value = module.default ?? module;
} }
watch(locale, () => { watch(
locale,
() => {
loadMemo(); loadMemo();
}, { immediate: true }); },
{ immediate: true },
);
</script> </script>
<template> <template>
<div> <div>
<component :is="memoComponent" style="overflow-x: auto;" /> <component :is="memoComponent" style="overflow-x: auto" />
</div> </div>
</template> </template>
@@ -45,7 +49,9 @@ watch(locale, () => {
::v-deep(table) { ::v-deep(table) {
border-collapse: collapse; border-collapse: collapse;
} }
::v-deep(table), ::v-deep(td), ::v-deep(th) { ::v-deep(table),
::v-deep(td),
::v-deep(th) {
border: 1px solid v-bind('themeVars.textColor1'); border: 1px solid v-bind('themeVars.textColor1');
padding: 5px; padding: 5px;
} }
+16 -16
View File
@@ -1,4 +1,4 @@
**`chmod`** (*change mode*) sets who may read, write, and execute a file or directory on Unix-like systems. The mode can be written **symbolically** (`u+x`) or **numerically** (`755`) — both reach the same result. **`chmod`** (_change mode_) sets who may read, write, and execute a file or directory on Unix-like systems. The mode can be written **symbolically** (`u+x`) or **numerically** (`755`) — both reach the same result.
```bash ```bash
chmod [options] <mode> <file>... chmod [options] <mode> <file>...
@@ -17,19 +17,19 @@ chmod [options] <mode> <file>...
└─────────────── type : - file · d directory · l symlink · c/b device └─────────────── type : - file · d directory · l symlink · c/b device
``` ```
## 🧑 User Classes (*who*) ## 🧑 User Classes (_who_)
| Symbol | Class | Applies to | | Symbol | Class | Applies to |
|--------|--------|-------------------------------------------------| | ------ | ------ | ----------------------------------------------- |
| `u` | User | The file's owner | | `u` | User | The file's owner |
| `g` | Group | Members of the file's group | | `g` | Group | Members of the file's group |
| `o` | Others | Everyone else | | `o` | Others | Everyone else |
| `a` | All | `u`, `g` and `o` at once (implied when omitted) | | `a` | All | `u`, `g` and `o` at once (implied when omitted) |
## 🔐 Permission Bits (*what*) ## 🔐 Permission Bits (_what_)
| Symbol | Permission | Octal | On a file | On a directory | | Symbol | Permission | Octal | On a file | On a directory |
|--------|------------|-------|---------------------|-------------------------------------------| | ------ | ---------- | ----- | ------------------- | ----------------------------------------- |
| `r` | Read | `4` | Read the contents | List entry names (`ls`) | | `r` | Read | `4` | Read the contents | List entry names (`ls`) |
| `w` | Write | `2` | Modify the contents | Create, rename and delete entries | | `w` | Write | `2` | Modify the contents | Create, rename and delete entries |
| `x` | Execute | `1` | Run as a program | Enter it (`cd`) and reach entries by name | | `x` | Execute | `1` | Run as a program | Enter it (`cd`) and reach entries by name |
@@ -38,7 +38,7 @@ chmod [options] <mode> <file>...
## 📝 Symbolic Mode ## 📝 Symbolic Mode
| Operator | Effect | | Operator | Effect |
|----------|-------------------------------------------------------------------| | -------- | ----------------------------------------------------------------- |
| `+` | Add the listed permissions, leave the rest untouched | | `+` | Add the listed permissions, leave the rest untouched |
| `-` | Remove the listed permissions, leave the rest untouched | | `-` | Remove the listed permissions, leave the rest untouched |
| `=` | Set exactly these permissions, clearing the others for that class | | `=` | Set exactly these permissions, clearing the others for that class |
@@ -76,7 +76,7 @@ chmod --reference=<ref> <file>
Each digit is the sum of `r` (4), `w` (2) and `x` (1): Each digit is the sum of `r` (4), `w` (2) and `x` (1):
| Octal | Sum | Bits | | Octal | Sum | Bits |
|-------|-------|-------| | ----- | ----- | ----- |
| `7` | 4+2+1 | `rwx` | | `7` | 4+2+1 | `rwx` |
| `6` | 4+2 | `rw-` | | `6` | 4+2 | `rw-` |
| `5` | 4+1 | `r-x` | | `5` | 4+1 | `r-x` |
@@ -86,12 +86,12 @@ Each digit is the sum of `r` (4), `w` (2) and `x` (1):
| `1` | 1 | `--x` | | `1` | 1 | `--x` |
| `0` | 0 | `---` | | `0` | 0 | `---` |
Three digits map to **user, group, others**. An optional fourth *leading* digit sets the special bits (`chmod 4755`, see below). Three digits map to **user, group, others**. An optional fourth _leading_ digit sets the special bits (`chmod 4755`, see below).
### Common modes ### Common modes
| Mode | Symbolic | Typical use | | Mode | Symbolic | Typical use |
|-------|-------------|-------------------------------------------------------------| | ----- | ----------- | ----------------------------------------------------------- |
| `777` | `rwxrwxrwx` | Full access for everyone — ⚠️ almost never the right answer | | `777` | `rwxrwxrwx` | Full access for everyone — ⚠️ almost never the right answer |
| `755` | `rwxr-xr-x` | Scripts, binaries and directories | | `755` | `rwxr-xr-x` | Scripts, binaries and directories |
| `750` | `rwxr-x---` | Executable for the owner and their group only | | `750` | `rwxr-x---` | Executable for the owner and their group only |
@@ -115,7 +115,7 @@ chmod 600 ~/.ssh/id_ed25519
These go beyond read/write/execute and control the execution context and deletion rules. These go beyond read/write/execute and control the execution context and deletion rules.
| Bit | Octal | Symbolic | Applies to | Effect | Shown in `ls -l` as | | Bit | Octal | Symbolic | Applies to | Effect | Shown in `ls -l` as |
|----------|-------|----------|--------------------------|----------------------------------------------------------------------|-------------------------| | -------- | ----- | -------- | ------------------------ | -------------------------------------------------------------------- | ----------------------- |
| `setuid` | `4` | `u+s` | Executable files | Runs with the **file owner's** privileges | `s` in the user field | | `setuid` | `4` | `u+s` | Executable files | Runs with the **file owner's** privileges | `s` in the user field |
| `setgid` | `2` | `g+s` | Executables, directories | Runs as the file's group / new entries inherit the directory's group | `s` in the group field | | `setgid` | `2` | `g+s` | Executables, directories | Runs as the file's group / new entries inherit the directory's group | `s` in the group field |
| `sticky` | `1` | `+t` | Directories | Only the entry's owner (or root) may delete or rename it | `t` in the others field | | `sticky` | `1` | `+t` | Directories | Only the entry's owner (or root) may delete or rename it | `t` in the others field |
@@ -140,10 +140,10 @@ chmod u-s,g-s,o-t <file>
## 📂 Directory Access Matrix ## 📂 Directory Access Matrix
`x` on a directory means *traverse*, not *execute* — without it nothing below the directory can be reached, no matter how permissive the files themselves are. `x` on a directory means _traverse_, not _execute_ — without it nothing below the directory can be reached, no matter how permissive the files themselves are.
| Mode | List names (`ls`) | Details (`ls -l`, `stat`) | Enter (`cd`) | Open a known file | Create / delete entries | | Mode | List names (`ls`) | Details (`ls -l`, `stat`) | Enter (`cd`) | Open a known file | Create / delete entries |
|-------|-------------------|---------------------------|--------------|-------------------|-------------------------| | ----- | ----------------- | ------------------------- | ------------ | ----------------- | ----------------------- |
| `r--` | ✅ | ❌ | ❌ | ❌ | ❌ | | `r--` | ✅ | ❌ | ❌ | ❌ | ❌ |
| `--x` | ❌ | ✅ (by exact name) | ✅ | ✅ | ❌ | | `--x` | ❌ | ✅ (by exact name) | ✅ | ✅ | ❌ |
| `r-x` | ✅ | ✅ | ✅ | ✅ | ❌ | | `r-x` | ✅ | ✅ | ✅ | ✅ | ❌ |
@@ -172,7 +172,7 @@ find <dir> -type f -name '*.sh' -exec chmod +x {} +
## ⚙️ Useful Options ## ⚙️ Useful Options
| Option | Description | | Option | Description |
|-----------------------------|-----------------------------------------------------------------| | --------------------------- | --------------------------------------------------------------- |
| `-R`, `--recursive` | Apply to directories and everything inside them | | `-R`, `--recursive` | Apply to directories and everything inside them |
| `-v`, `--verbose` | Print a line for every file processed | | `-v`, `--verbose` | Print a line for every file processed |
| `-c`, `--changes` | Print a line only when a mode actually changed | | `-c`, `--changes` | Print a line only when a mode actually changed |
@@ -197,7 +197,7 @@ umask 027
``` ```
| umask | New files | New directories | | umask | New files | New directories |
|-------|-----------|-----------------| | ----- | --------- | --------------- |
| `022` | `644` | `755` | | `022` | `644` | `755` |
| `002` | `664` | `775` | | `002` | `664` | `775` |
| `027` | `640` | `750` | | `027` | `640` | `750` |
@@ -208,7 +208,7 @@ umask 027
## 🚑 Common Recipes ## 🚑 Common Recipes
| Goal | Command | | Goal | Command |
|-------------------------------------|------------------------------------------------------------------------------| | ----------------------------------- | ---------------------------------------------------------------------------- |
| Make a script runnable | `chmod +x deploy.sh` | | Make a script runnable | `chmod +x deploy.sh` |
| Lock down an SSH key pair | `chmod 700 ~/.ssh && chmod 600 ~/.ssh/id_* && chmod 644 ~/.ssh/*.pub` | | Lock down an SSH key pair | `chmod 700 ~/.ssh && chmod 600 ~/.ssh/id_* && chmod 644 ~/.ssh/*.pub` |
| Serve web content read-only | `chmod -R u=rwX,go=rX /var/www/site` | | Serve web content read-only | `chmod -R u=rwX,go=rX /var/www/site` |
@@ -220,7 +220,7 @@ umask 027
## 🧰 Related Commands ## 🧰 Related Commands
| Command | Purpose | | Command | Purpose |
|-----------------------------------|--------------------------------------------------------------------| | --------------------------------- | ------------------------------------------------------------------ |
| `chown <user>:<group> <file>` | Change the owner and/or group | | `chown <user>:<group> <file>` | Change the owner and/or group |
| `chgrp <group> <file>` | Change the group only | | `chgrp <group> <file>` | Change the group only |
| `ls -l` / `ls -ld <dir>` | Show permissions (`-d` for the directory itself, not its contents) | | `ls -l` / `ls -ld <dir>` | Show permissions (`-d` for the directory itself, not its contents) |
+6 -7
View File
@@ -3,7 +3,7 @@
## 🧑 用户类别 ## 🧑 用户类别
| 符号 | 含义 | | 符号 | 含义 |
|--------|----------------| | ---- | -------------- |
| `u` | 用户(所有者) | | `u` | 用户(所有者) |
| `g` | 组 | | `g` | 组 |
| `o` | 其他 | | `o` | 其他 |
@@ -12,7 +12,7 @@
## 🔐 权限类型 ## 🔐 权限类型
| 符号 | 含义 | 数字 | | 符号 | 含义 | 数字 |
|--------|----------|---------| | ---- | ---- | ---- |
| `r` | 读 | 4 | | `r` | 读 | 4 |
| `w` | 写 | 2 | | `w` | 写 | 2 |
| `x` | 执行 | 1 | | `x` | 执行 | 1 |
@@ -32,12 +32,11 @@ chmod a=r file # 为所有用户设置为只读
将用户、组和其他用户的权限值组合: 将用户、组和其他用户的权限值组合:
| 模式 | 权限 | 含义 | | 模式 | 权限 | 含义 |
|------|-------------|---------------| | ---- | --------- | -------------- |
| 777 | rwxrwxrwx | 完全访问权限 | | 777 | rwxrwxrwx | 完全访问权限 |
| 755 | rwxr-xr-x | 常用于脚本 | | 755 | rwxr-xr-x | 常用于脚本 |
| 644 | rw-r--r-- | 常用于文本文件 | | 644 | rw-r--r-- | 常用于文本文件 |
```bash ```bash
chmod 755 script.sh chmod 755 script.sh
chmod 644 notes.txt chmod 644 notes.txt
@@ -93,14 +92,14 @@ chmod 1777 /tmp
## 📂 执行(`x`)标志:文件与目录的区别 ## 📂 执行(`x`)标志:文件与目录的区别
| 上下文 | `x` 权限的效果 | | 上下文 | `x` 权限的效果 |
|-------------|----------------------------------------| | -------- | ---------------------------------------- |
| **文件** | 允许作为程序/脚本执行 | | **文件** | 允许作为程序/脚本执行 |
| **目录** | 允许进入目录(`cd`)并通过名称访问其内容 | | **目录** | 允许进入目录(`cd`)并通过名称访问其内容 |
### 🔍 目录访问矩阵 ### 🔍 目录访问矩阵
| 权限 | 可列出(`ls`) | 可进入(`cd`) | 可访问文件 | | 权限 | 可列出(`ls`) | 可进入(`cd`) | 可访问文件 |
|------------|------------------|------------------|------------------| | ----- | -------------- | -------------- | ------------------ |
| `r` | ✅ | ❌ | ✅(已知文件名时) | | `r` | ✅ | ❌ | ✅(已知文件名时) |
| `x` | ❌ | ✅ | ✅(已知文件名时) | | `x` | ❌ | ✅ | ✅(已知文件名时) |
| `r+x` | ✅ | ✅ | ✅ | | `r+x` | ✅ | ✅ | ✅ |
@@ -110,7 +109,7 @@ chmod 1777 /tmp
## 🔍 快速参考 ## 🔍 快速参考
| 命令 | 描述 | | 命令 | 描述 |
|---------------------|--------------------------------------| | ------------------ | ---------------------- |
| `chmod +x file` | 使文件可执行 | | `chmod +x file` | 使文件可执行 |
| `chmod -R 755 dir` | 递归设置权限 | | `chmod -R 755 dir` | 递归设置权限 |
| `chmod u=rwx file` | 仅将用户权限设置为 rwx | | `chmod u=rwx file` | 仅将用户权限设置为 rwx |
@@ -13,25 +13,45 @@ describe('cidr-in-cidr', () => {
expect(cidrInCidr({ baseRange: '192.168.20.*', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(false); // NOSONAR expect(cidrInCidr({ baseRange: '192.168.20.*', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(false); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.0.*', ipOrRangeToTest: '192.168.0.0/28' }).isIncluded).toBe(true); // NOSONAR expect(cidrInCidr({ baseRange: '192.168.0.*', ipOrRangeToTest: '192.168.0.0/28' }).isIncluded).toBe(true); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.12' }).isIncluded).toBe(true); // NOSONAR expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.12' }).isIncluded).toBe(
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.20' }).isIncluded).toBe(false); // NOSONAR true,
); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.20' }).isIncluded).toBe(
false,
); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.9-192.168.20.12' }).isIncluded).toBe(true); // NOSONAR expect(
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.9-192.168.20.20' }).isIncluded).toBe(false); // NOSONAR cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.9-192.168.20.12' })
.isIncluded,
).toBe(true); // NOSONAR
expect(
cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.9-192.168.20.20' })
.isIncluded,
).toBe(false); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.0-192.168.20.255', ipOrRangeToTest: '192.168.20.0/28' }).isIncluded).toBe(true); // NOSONAR expect(
expect(cidrInCidr({ baseRange: '192.168.20.0-192.168.20.255', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(false); // NOSONAR cidrInCidr({ baseRange: '192.168.20.0-192.168.20.255', ipOrRangeToTest: '192.168.20.0/28' }).isIncluded,
expect(cidrInCidr({ baseRange: '192.168.0.0-192.168.1.255', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(true); // NOSONAR ).toBe(true); // NOSONAR
expect(
cidrInCidr({ baseRange: '192.168.20.0-192.168.20.255', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded,
).toBe(false); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.0.0-192.168.1.255', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(
true,
); // NOSONAR
}); });
it('should return correct subnet', () => { it('should return correct subnet', () => {
expect(cidrInCidr({ baseRange: '192.168.0.0/16', ipOrRangeToTest: '192.168.0.1' }).baseSubnets).to.deep.eq([ // NOSONAR expect(cidrInCidr({ baseRange: '192.168.0.0/16', ipOrRangeToTest: '192.168.0.1' }).baseSubnets).to.deep.eq([
// NOSONAR
{ {
cidr: '192.168.0.0/16', // NOSONAR cidr: '192.168.0.0/16', // NOSONAR
end: '192.168.255.255', // NOSONAR end: '192.168.255.255', // NOSONAR
start: '192.168.0.0', // NOSONAR start: '192.168.0.0', // NOSONAR
}, },
]); ]);
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.3', ipOrRangeToTest: '192.168.1.0/28' }).baseSubnets).to.deep.eq([ // NOSONAR expect(
cidrInCidr({ baseRange: '192.168.20.1-192.168.20.3', ipOrRangeToTest: '192.168.1.0/28' }).baseSubnets,
).to.deep.eq([
// NOSONAR
{ {
cidr: '192.168.20.1/32', // NOSONAR cidr: '192.168.20.1/32', // NOSONAR
end: '192.168.20.1', // NOSONAR end: '192.168.20.1', // NOSONAR
@@ -1,15 +1,11 @@
import { getMatch } from 'ip-matching'; import { getMatch } from 'ip-matching';
export function cidrInCidr( export function cidrInCidr({ baseRange, ipOrRangeToTest }: { baseRange: string; ipOrRangeToTest: string }) {
{ baseRange, ipOrRangeToTest }:
{
baseRange: string
ipOrRangeToTest: string
}) {
const baseMatchMasks = getMatch(baseRange)?.convertToMasks() || []; const baseMatchMasks = getMatch(baseRange)?.convertToMasks() || [];
const ipOrRangeToTestMatchMasks = getMatch(ipOrRangeToTest)?.convertToMasks() || []; const ipOrRangeToTestMatchMasks = getMatch(ipOrRangeToTest)?.convertToMasks() || [];
const baseSubnets = baseMatchMasks.map((mask) => { const baseSubnets = baseMatchMasks
.map((mask) => {
const subnet = mask.convertToSubnet(); const subnet = mask.convertToSubnet();
if (!subnet) { if (!subnet) {
return { cidr: '', start: '', end: '' }; return { cidr: '', start: '', end: '' };
@@ -19,10 +15,13 @@ export function cidrInCidr(
start: subnet.getFirst().toString(), start: subnet.getFirst().toString(),
end: subnet.getLast().toString(), end: subnet.getLast().toString(),
}; };
}).filter(subnet => subnet.cidr !== ''); })
.filter((subnet) => subnet.cidr !== '');
return { return {
baseSubnets, baseSubnets,
isIncluded: baseMatchMasks.some(baseMask => ipOrRangeToTestMatchMasks.every(ipOrRangeMask => ipOrRangeMask.isSubsetOf(baseMask))), isIncluded: baseMatchMasks.some((baseMask) =>
ipOrRangeToTestMatchMasks.every((ipOrRangeMask) => ipOrRangeMask.isSubsetOf(baseMask)),
),
}; };
} }
@@ -11,8 +11,9 @@ describe('formatVancouverCitation', () => {
publisher: 'Publisher', publisher: 'Publisher',
url: 'https://example.com', url: 'https://example.com',
}; };
expect(formatVancouverCitation(entry)) expect(formatVancouverCitation(entry)).toBe(
.toBe('Doe J. Sample Title. Publisher; 2021. Available from: https://example.com'); 'Doe J. Sample Title. Publisher; 2021. Available from: https://example.com',
);
}); });
it('formats multiple authors correctly', () => { it('formats multiple authors correctly', () => {
@@ -25,8 +26,7 @@ describe('formatVancouverCitation', () => {
title: 'Multi Author Work', title: 'Multi Author Work',
publisher: 'TechPress', publisher: 'TechPress',
}; };
expect(formatVancouverCitation(entry)) expect(formatVancouverCitation(entry)).toBe('Doe J, Smith J. Multi Author Work. TechPress; 2020.');
.toBe('Doe J, Smith J. Multi Author Work. TechPress; 2020.');
}); });
it('uses et al. when more than 6 authors', () => { it('uses et al. when more than 6 authors', () => {
@@ -44,8 +44,9 @@ describe('formatVancouverCitation', () => {
title: 'Big Team Paper', title: 'Big Team Paper',
publisher: 'SciencePub', publisher: 'SciencePub',
}; };
expect(formatVancouverCitation(entry)) expect(formatVancouverCitation(entry)).toBe(
.toBe('One A, Two B, Three C, Four D, Five E, Six F, et al. Big Team Paper. SciencePub; 2019.'); 'One A, Two B, Three C, Four D, Five E, Six F, et al. Big Team Paper. SciencePub; 2019.',
);
}); });
it('handles multiple initials in first name', () => { it('handles multiple initials in first name', () => {
@@ -53,8 +54,7 @@ describe('formatVancouverCitation', () => {
authors: [{ first: 'John Michael', last: 'Doe' }], authors: [{ first: 'John Michael', last: 'Doe' }],
title: 'Initials Test', title: 'Initials Test',
}; };
expect(formatVancouverCitation(entry)) expect(formatVancouverCitation(entry)).toBe('Doe JM. Initials Test.');
.toBe('Doe JM. Initials Test.');
}); });
it('falls back to Anonymous if no authors', () => { it('falls back to Anonymous if no authors', () => {
@@ -62,8 +62,7 @@ describe('formatVancouverCitation', () => {
title: 'No Author Work', title: 'No Author Work',
year: '2022', year: '2022',
}; };
expect(formatVancouverCitation(entry)) expect(formatVancouverCitation(entry)).toBe('Anonymous. No Author Work. 2022.');
.toBe('Anonymous. No Author Work. 2022.');
}); });
it('handles missing title gracefully', () => { it('handles missing title gracefully', () => {
@@ -71,8 +70,7 @@ describe('formatVancouverCitation', () => {
authors: [{ first: 'Jane', last: 'Smith' }], authors: [{ first: 'Jane', last: 'Smith' }],
year: '2023', year: '2023',
}; };
expect(formatVancouverCitation(entry)) expect(formatVancouverCitation(entry)).toBe('Smith J. [No title]. 2023.');
.toBe('Smith J. [No title]. 2023.');
}); });
it('handles missing publisher and year', () => { it('handles missing publisher and year', () => {
@@ -80,7 +78,6 @@ describe('formatVancouverCitation', () => {
authors: [{ first: 'Jane', last: 'Smith' }], authors: [{ first: 'Jane', last: 'Smith' }],
title: 'Untimed Work', title: 'Untimed Work',
}; };
expect(formatVancouverCitation(entry)) expect(formatVancouverCitation(entry)).toBe('Smith J. Untimed Work.');
.toBe('Smith J. Untimed Work.');
}); });
}); });
@@ -1,10 +1,13 @@
interface Author { first?: string; last?: string } interface Author {
first?: string;
last?: string;
}
interface CitationInput { interface CitationInput {
authors?: Author[] authors?: Author[];
year?: string year?: string;
title?: string title?: string;
publisher?: string publisher?: string;
url?: string url?: string;
} }
export function formatVancouverCitation(entry: CitationInput): string { export function formatVancouverCitation(entry: CitationInput): string {
@@ -14,7 +17,7 @@ export function formatVancouverCitation(entry: CitationInput): string {
} }
const initials = (author.first || '') const initials = (author.first || '')
.split(/\s+/) .split(/\s+/)
.map(name => name.charAt(0).toUpperCase()) .map((name) => name.charAt(0).toUpperCase())
.join(''); .join('');
return `${author.last} ${initials}`; return `${author.last} ${initials}`;
}; };
@@ -22,9 +25,7 @@ export function formatVancouverCitation(entry: CitationInput): string {
const authors = Array.isArray(entry.authors) ? entry.authors.map(formatAuthor).filter(Boolean) : []; const authors = Array.isArray(entry.authors) ? entry.authors.map(formatAuthor).filter(Boolean) : [];
let authorStr = 'Anonymous'; let authorStr = 'Anonymous';
if (authors.length > 0) { if (authors.length > 0) {
authorStr = authors.length > 6 authorStr = authors.length > 6 ? `${authors.slice(0, 6).join(', ')}, et al` : authors.join(', ');
? `${authors.slice(0, 6).join(', ')}, et al`
: authors.join(', ');
} }
const title = entry.title?.trim() || '[No title]'; const title = entry.title?.trim() || '[No title]';
@@ -1,68 +1,69 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { buildEditedCommand, buildOptionsObject, extractOptions, isOption, sanitizeOption } from './cli-command-editor.service'; import {
buildEditedCommand,
buildOptionsObject,
extractOptions,
isOption,
sanitizeOption,
} from './cli-command-editor.service';
describe('cli-command-editor', () => { describe('cli-command-editor', () => {
describe('extractOptions', () => { describe('extractOptions', () => {
it('extracts all the options from a command', () => { it('extracts all the options from a command', () => {
expect(extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer')[0]).toContain(
'--load-balancer-name',
);
expect( expect(
extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer')[0], extractOptions(
'aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy',
)[0],
).toContain('--load-balancer-name'); ).toContain('--load-balancer-name');
expect( expect(
extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy')[0], extractOptions(
).toContain('--load-balancer-name'); 'aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy',
)[1],
expect(
extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy')[1],
).toContain('--debug'); ).toContain('--debug');
expect( expect(
extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy')[2], extractOptions(
'aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy',
)[2],
).toContain('--query'); ).toContain('--query');
}); });
it('extracts all the option from a command with a mix of hyphen and double hyphens', () => { it('extracts all the option from a command with a mix of hyphen and double hyphens', () => {
expect( expect(extractOptions('npm i lodash -g --legacy-peer-deps')[0]).toContain('-g');
extractOptions('npm i lodash -g --legacy-peer-deps')[0],
).toContain('-g');
expect( expect(extractOptions('npm i lodash -g --legacy-peer-deps')[1]).toContain('--legacy-peer-deps');
extractOptions('npm i lodash -g --legacy-peer-deps')[1],
).toContain('--legacy-peer-deps');
}); });
it('shouldn\'t extract any options from a command without options', () => { it("shouldn't extract any options from a command without options", () => {
expect( expect(extractOptions('npm i lodash')).toEqual([]);
extractOptions('npm i lodash'),
).toEqual([]);
}); });
it('shouldn\'t return any options if command is not passed', () => { it("shouldn't return any options if command is not passed", () => {
expect(extractOptions()).toEqual([]); expect(extractOptions()).toEqual([]);
}); });
}); });
describe('buildOptionsObject', () => { describe('buildOptionsObject', () => {
it('returns a valid options object with the given options', () => { it('returns a valid options object with the given options', () => {
expect( expect(buildOptionsObject(['--debug', '--load-balancer-names'])).toEqual({
buildOptionsObject(['--debug', '--load-balancer-names']),
).toEqual({
'--debug': '', '--debug': '',
'--load-balancer-names': '', '--load-balancer-names': '',
}); });
}); });
it('returns an empty obnject with blank options array', () => { it('returns an empty obnject with blank options array', () => {
expect( expect(buildOptionsObject([])).toEqual({});
buildOptionsObject([]),
).toEqual({});
}); });
}); });
describe('sanitizeOption', () => { describe('sanitizeOption', () => {
it('returns the sanitized option without `id` suffix', () => { it('returns the sanitized option without `id` suffix', () => {
expect(sanitizeOption('--debug-id-1dfsj')) expect(sanitizeOption('--debug-id-1dfsj')).toEqual('--debug');
.toEqual('--debug');
}); });
it('returns the blank string', () => { it('returns the blank string', () => {
@@ -87,54 +88,66 @@ describe('cli-command-editor', () => {
describe('buildEditedCommand', () => { describe('buildEditedCommand', () => {
it('returns the edited command', () => { it('returns the edited command', () => {
expect( expect(
buildEditedCommand({ buildEditedCommand(
{
'--debug-id-1dfsj': 'stdin', '--debug-id-1dfsj': 'stdin',
'-p': '', '-p': '',
'-m': 'nahhhh', '-m': 'nahhhh',
}, { },
{
'--debug-id-1dfsj': 'stdin', '--debug-id-1dfsj': 'stdin',
'-p': '', '-p': '',
'-m': 'nahhhh', '-m': 'nahhhh',
}, 'aws node --debug stdio -p -m okayyy'), },
'aws node --debug stdio -p -m okayyy',
),
).toEqual('aws node --debug stdin -p -m nahhhh'); ).toEqual('aws node --debug stdin -p -m nahhhh');
expect( expect(
buildEditedCommand({ buildEditedCommand(
{
'-d-id-1dfsj': '', '-d-id-1dfsj': '',
'-p-id-fdsd': '4444:3333', '-p-id-fdsd': '4444:3333',
'-p-id-fddd': '3333:4444', '-p-id-fddd': '3333:4444',
'--name-id-nnnn': 'clickhouse-server', '--name-id-nnnn': 'clickhouse-server',
'--ulimit-id-uuuu': 'nofile=3333:4444', '--ulimit-id-uuuu': 'nofile=3333:4444',
}, { },
{
'-d-id-1dfsj': '', '-d-id-1dfsj': '',
'-p-id-fdsd': '4444:3333', '-p-id-fdsd': '4444:3333',
'-p-id-fddd': '3333:4444', '-p-id-fddd': '3333:4444',
'--name-id-nnnn': 'clickhouse-server', '--name-id-nnnn': 'clickhouse-server',
'--ulimit-id-uuuu': 'nofile=3333:4444', '--ulimit-id-uuuu': 'nofile=3333:4444',
}, 'docker run -d -p 18123:8123 -p 19000:9000 --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server'), },
).toEqual('docker run -d -p 4444:3333 -p 3333:4444 --name clickhouse-server --ulimit nofile=3333:4444 clickhouse/clickhouse-server'); 'docker run -d -p 18123:8123 -p 19000:9000 --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server',
),
).toEqual(
'docker run -d -p 4444:3333 -p 3333:4444 --name clickhouse-server --ulimit nofile=3333:4444 clickhouse/clickhouse-server',
);
}); });
it('returns the edited command when options object and CLI options order doesn\'t match', () => { it("returns the edited command when options object and CLI options order doesn't match", () => {
expect( expect(
buildEditedCommand({ buildEditedCommand(
{
'-d-id-t1dd3': 'true', '-d-id-t1dd3': 'true',
'--install-id-only123': 'nodemon', '--install-id-only123': 'nodemon',
}, { },
{
'--install-id-only123': 'nodem', '--install-id-only123': 'nodem',
'-d-id-t1dd3': 'false', '-d-id-t1dd3': 'false',
}, 'npm --install nodem -d false'), },
'npm --install nodem -d false',
),
).toBe('npm --install nodemon -d true'); ).toBe('npm --install nodemon -d true');
}); });
it('returns the original command', () => { it('returns the original command', () => {
expect( expect(buildEditedCommand({}, {}, 'npm install nodemon')).toBe('npm install nodemon');
buildEditedCommand({}, {}, 'npm install nodemon'),
).toBe('npm install nodemon');
expect( expect(buildEditedCommand({}, {}, 'aws load-balancer describe-load-balancers all')).toBe(
buildEditedCommand({}, {}, 'aws load-balancer describe-load-balancers all'), 'aws load-balancer describe-load-balancers all',
).toBe('aws load-balancer describe-load-balancers all'); );
}); });
}); });
}); });
@@ -14,7 +14,8 @@ export function extractOptions(command: string = ''): string[] {
const tokens = command.split(' '); const tokens = command.split(' ');
// map each token of the command to an option // map each token of the command to an option
const options = tokens.map((token: string) => { const options = tokens
.map((token: string) => {
// every option in a starts with either a hyphen or double hyphens // every option in a starts with either a hyphen or double hyphens
if (isOption(token)) { if (isOption(token)) {
const randomId = generateRandomId(); const randomId = generateRandomId();
@@ -22,7 +23,8 @@ export function extractOptions(command: string = ''): string[] {
} }
return ''; return '';
}).filter((option: string): boolean => !!option); })
.filter((option: string): boolean => !!option);
return options; return options;
} }
@@ -40,7 +42,11 @@ export function sanitizeOption(option: string): string {
return option.split('-id')?.[0]; return option.split('-id')?.[0];
} }
export function buildEditedCommand(options: Record<string, string>, originalOptions: Record<string, string>, command: string): string { export function buildEditedCommand(
options: Record<string, string>,
originalOptions: Record<string, string>,
command: string,
): string {
if (!Object.keys(options).length) { if (!Object.keys(options).length) {
return command; return command;
} }
@@ -53,8 +59,7 @@ export function buildEditedCommand(options: Record<string, string>, originalOpti
// order as they appear in the original command, this is done // order as they appear in the original command, this is done
// to handle the interpolation of edited option values into the // to handle the interpolation of edited option values into the
// command // command
originalOptions = Object.entries(options) originalOptions = Object.entries(options).reduce((previousValue: Record<string, string>, currentValue: string[]) => {
.reduce((previousValue: Record<string, string>, currentValue: string[]) => {
previousValue[currentValue[0]] = currentValue[1]; previousValue[currentValue[0]] = currentValue[1];
return previousValue; return previousValue;
@@ -92,8 +97,7 @@ export function buildEditedCommand(options: Record<string, string>, originalOpti
if (originalOptions[key]) { if (originalOptions[key]) {
editedCommand = editedCommand.replace(`$${i}`, `${keyWithoutIdSuffix} ${originalOptions[key]}`); editedCommand = editedCommand.replace(`$${i}`, `${keyWithoutIdSuffix} ${originalOptions[key]}`);
} } else {
else {
const value = defaultValues[`$${i}`]; const value = defaultValues[`$${i}`];
const replaceValue = value ? `${keyWithoutIdSuffix} ${value}` : keyWithoutIdSuffix; const replaceValue = value ? `${keyWithoutIdSuffix} ${value}` : keyWithoutIdSuffix;
editedCommand = editedCommand.replace(`$${i}`, replaceValue); editedCommand = editedCommand.replace(`$${i}`, replaceValue);
@@ -25,7 +25,11 @@ const command = ref('');
:placeholder="$t('tools.cli-command-editor.placeholder')" :placeholder="$t('tools.cli-command-editor.placeholder')"
:aria-placeholder="t('tools.cli-command-editor.placeholder')" :aria-placeholder="t('tools.cli-command-editor.placeholder')"
raw-text raw-text
@update:value="() => { command = inputCommand }" @update:value="
() => {
command = inputCommand;
}
"
/> />
<div v-for="option in options" :key="option" flex justify-center> <div v-for="option in options" :key="option" flex justify-center>
<c-input-text <c-input-text
@@ -38,17 +42,15 @@ const command = ref('');
:placeholder="service.sanitizeOption(option)" :placeholder="service.sanitizeOption(option)"
:aria-placeholder="service.sanitizeOption(option)" :aria-placeholder="service.sanitizeOption(option)"
mt-6 mt-6
@update:value="() => { command = service.buildEditedCommand(optionsInput, optionsObject, inputCommand) }" @update:value="
() => {
command = service.buildEditedCommand(optionsInput, optionsObject, inputCommand);
}
"
/> />
</div> </div>
<c-text-copyable <c-text-copyable v-if="command" :value="command" :show-icon="false" mt-6 font-mono />
v-if="command"
:value="command"
:show-icon="false"
mt-6 font-mono
/>
</n-gi> </n-gi>
</n-grid> </n-grid>
</c-card> </c-card>
+23 -12
View File
@@ -26,15 +26,25 @@ const themes = ref<{ value: string; label: string }[]>(
value: item.id, value: item.id,
label: item.displayName, label: item.displayName,
}; };
})); }),
);
const langs = ref<{ value: string; label: string }[]>( const langs = ref<{ value: string; label: string }[]>(
bundledLanguagesInfo.map(item => ({ bundledLanguagesInfo.map((item) => ({
value: item.id, value: item.id,
label: item.name, label: item.name,
}))); })),
);
const currentTheme = useQueryParamOrStorage({ name: 'theme', storageName: 'code-highlighter:theme', defaultValue: 'dark-plus' }); const currentTheme = useQueryParamOrStorage({
const currentLang = useQueryParamOrStorage({ name: 'lang', storageName: 'code-highlighter:lang', defaultValue: 'typescript' }); name: 'theme',
storageName: 'code-highlighter:theme',
defaultValue: 'dark-plus',
});
const currentLang = useQueryParamOrStorage({
name: 'lang',
storageName: 'code-highlighter:lang',
defaultValue: 'typescript',
});
const showLineNumbers = ref(false); const showLineNumbers = ref(false);
@@ -46,8 +56,7 @@ const formattedCodeHtml = computedAsync(async () => {
const lineNumberWidth = Math.log10(codeValue.split('\n').length) + 2; const lineNumberWidth = Math.log10(codeValue.split('\n').length) + 2;
const highlighter = await createHighlighter( const highlighter = await createHighlighter({
{
langs: [currentLangValue], langs: [currentLangValue],
themes: [currentThemeValue], themes: [currentThemeValue],
}); });
@@ -59,16 +68,17 @@ const formattedCodeHtml = computedAsync(async () => {
postprocess(html: string) { postprocess(html: string) {
// when copied to clipboard and pasted to LibreOffice, // when copied to clipboard and pasted to LibreOffice,
// formatting of first line is only kept if there is a line break before... // formatting of first line is only kept if there is a line break before...
const ensureFirstLineFormattedWhenCopied const ensureFirstLineFormattedWhenCopied = (html: string) => html.replace('<code>', '<code>\n');
= (html: string) => html.replace('<code>', '<code>\n');
if (!needLineNumbers) { if (!needLineNumbers) {
return ensureFirstLineFormattedWhenCopied(html); return ensureFirstLineFormattedWhenCopied(html);
} }
let lineNumber = 1; let lineNumber = 1;
return html.replace(/<span class="line/g, (m) => { return html
.replace(/<span class="line/g, (m) => {
const lineNumberFormatted = (lineNumber++).toString().padStart(lineNumberWidth, ' '); const lineNumberFormatted = (lineNumber++).toString().padStart(lineNumberWidth, ' ');
return `<span class="line-number" style="white-space-collapse: preserve">${lineNumberFormatted} </span>${m}`; return `<span class="line-number" style="white-space-collapse: preserve">${lineNumberFormatted} </span>${m}`;
}).replace('<code>', '<code>\n'); })
.replace('<code>', '<code>\n');
}, },
}, },
], ],
@@ -120,7 +130,8 @@ const { copy: copyText } = useCopy({ source: code });
</c-button> </c-button>
</div> </div>
<div v-html="formattedCodeHtml" /><!-- //NOSONAR --> <div v-html="formattedCodeHtml" />
<!-- //NOSONAR -->
</div> </div>
</template> </template>
@@ -12,18 +12,18 @@ function removeAlphaChannelWhenOpaque(hexColor: string) {
function buildColorFormat({ function buildColorFormat({
label, label,
parse = value => colord(value), parse = (value) => colord(value),
format, format,
placeholder, placeholder,
invalidMessage = t('tools.color-converter.models.text.invalid-label-tolowercase-format', [label.toLowerCase()]), invalidMessage = t('tools.color-converter.models.text.invalid-label-tolowercase-format', [label.toLowerCase()]),
type = 'text', type = 'text',
}: { }: {
label: string label: string;
parse?: (value: string) => Colord parse?: (value: string) => Colord;
format: (value: Colord) => string format: (value: Colord) => string;
placeholder?: string placeholder?: string;
invalidMessage?: string invalidMessage?: string;
type?: 'text' | 'color-picker' type?: 'text' | 'color-picker';
}) { }) {
const value = ref(''); const value = ref('');
@@ -39,7 +39,8 @@ function buildColorFormat({
rules: [ rules: [
{ {
message: invalidMessage, message: invalidMessage,
validator: v => withDefaultOnError(() => { validator: (v) =>
withDefaultOnError(() => {
if (v === '') { if (v === '') {
return true; return true;
} }
@@ -49,6 +50,5 @@ function buildColorFormat({
}, },
], ],
}), }),
}; };
} }
+14 -12
View File
@@ -58,25 +58,25 @@ const formats = {
label: t('tools.color-converter.texts.label-lab'), label: t('tools.color-converter.texts.label-lab'),
format: (v: Colord) => colordx(v.toHex()).toLabString(), format: (v: Colord) => colordx(v.toHex()).toLabString(),
placeholder: 'e.g. lab(54.29 80.8 69.89)', placeholder: 'e.g. lab(54.29 80.8 69.89)',
parse: value => colord(colordx(value).toHex()), parse: (value) => colord(colordx(value).toHex()),
}), }),
xyz: buildColorFormat({ xyz: buildColorFormat({
label: t('tools.color-converter.texts.label-xyz'), label: t('tools.color-converter.texts.label-xyz'),
format: (v: Colord) => JSON.stringify(v.toXyz()), format: (v: Colord) => JSON.stringify(v.toXyz()),
placeholder: 'e.g. { x: 95.047, y: 100, z: 108.883, a: 1 }', placeholder: 'e.g. { x: 95.047, y: 100, z: 108.883, a: 1 }',
parse: value => colord(JSON.parse(value)), parse: (value) => colord(JSON.parse(value)),
}), }),
oklab: buildColorFormat({ oklab: buildColorFormat({
label: t('tools.color-converter.texts.label-oklab'), label: t('tools.color-converter.texts.label-oklab'),
format: (v: Colord) => colordx(v.toHex()).toOklabString(), format: (v: Colord) => colordx(v.toHex()).toOklabString(),
placeholder: 'e.g. oklab(40.1% 0.1143 0.045)', placeholder: 'e.g. oklab(40.1% 0.1143 0.045)',
parse: value => colord(colordx(value).toHex()), parse: (value) => colord(colordx(value).toHex()),
}), }),
oklch: buildColorFormat({ oklch: buildColorFormat({
label: t('tools.color-converter.texts.label-oklch'), label: t('tools.color-converter.texts.label-oklch'),
format: (v: Colord) => colordx(v.toHex()).toOklchString(), format: (v: Colord) => colordx(v.toHex()).toOklchString(),
placeholder: 'e.g. oklch(40.1% 0.123 21.57)', placeholder: 'e.g. oklch(40.1% 0.123 21.57)',
parse: value => colord(colordx(value).toHex()), parse: (value) => colord(colordx(value).toHex()),
}), }),
name: buildColorFormat({ name: buildColorFormat({
label: t('tools.color-converter.texts.label-name'), label: t('tools.color-converter.texts.label-name'),
@@ -91,9 +91,7 @@ const grayscale = ref(false);
const invert = ref(false); const invert = ref(false);
let lastColor = colord('#1ea54c'); let lastColor = colord('#1ea54c');
watch([saturation, brightness, grayscale, invert], watch([saturation, brightness, grayscale, invert], () => updateColorValue(lastColor));
() => updateColorValue(lastColor),
);
updateColorValue(lastColor); updateColorValue(lastColor);
@@ -119,16 +117,14 @@ function updateColorValue(value: Colord | undefined, omitLabel?: string) {
const saturationFloat = saturation.value / 100.0; const saturationFloat = saturation.value / 100.0;
if (saturationFloat > 0) { if (saturationFloat > 0) {
correctedValue = correctedValue.saturate(saturationFloat); correctedValue = correctedValue.saturate(saturationFloat);
} } else if (saturationFloat < 0) {
else if (saturationFloat < 0) {
correctedValue = correctedValue.desaturate(-saturationFloat); correctedValue = correctedValue.desaturate(-saturationFloat);
} }
const brightnessFloat = brightness.value / 100.0; const brightnessFloat = brightness.value / 100.0;
if (brightnessFloat > 0) { if (brightnessFloat > 0) {
correctedValue = correctedValue.lighten(brightnessFloat); correctedValue = correctedValue.lighten(brightnessFloat);
} } else if (brightnessFloat < 0) {
else if (brightnessFloat < 0) {
correctedValue = correctedValue.darken(-brightnessFloat); correctedValue = correctedValue.darken(-brightnessFloat);
} }
@@ -181,7 +177,13 @@ function updateColorValue(value: Colord | undefined, omitLabel?: string) {
@update:value="(v: string) => updateColorValue(parse(v), key)" @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-form-item
v-else-if="type === 'color-picker'"
:label="`${label}:`"
label-width="100"
label-placement="left"
:show-feedback="false"
>
<n-color-picker <n-color-picker
v-model:value="formats[key].value.value" v-model:value="formats[key].value.value"
placement="bottom-end" placement="bottom-end"
+9 -32
View File
@@ -33,11 +33,11 @@ const harmonyTypes: { type: HarmonyType; label: string }[] = [
]; ];
const colorList = computed(() => { const colorList = computed(() => {
return colors.value.map(item => colord(item.rgb).toHex()); return colors.value.map((item) => colord(item.rgb).toHex());
}); });
function handleChangeGradient(harmonyColors: Harmony[]) { function handleChangeGradient(harmonyColors: Harmony[]) {
const newColors = harmonyColors.map(color => colord(color.rgb).toHex()); const newColors = harmonyColors.map((color) => colord(color.rgb).toHex());
const [base, secondary] = newColors; const [base, secondary] = newColors;
@@ -50,27 +50,15 @@ function handleChangeGradient(harmonyColors: Harmony[]) {
return null; return null;
}); });
const secondaryRgb = colord(secondary).toRgb(); const secondaryRgb = colord(secondary).toRgb();
rootEl.style.setProperty( rootEl.style.setProperty('--color-interactive', `${secondaryRgb.r}, ${secondaryRgb.g}, ${secondaryRgb.b}`);
'--color-interactive',
`${secondaryRgb.r}, ${secondaryRgb.g}, ${secondaryRgb.b}`,
);
if (newColors.length === 3) { if (newColors.length === 3) {
const lightColor = colord(base).saturate(0.25).toRgb(); const lightColor = colord(base).saturate(0.25).toRgb();
const darkColor = colord(base).desaturate(0.25).toRgb(); const darkColor = colord(base).desaturate(0.25).toRgb();
rootEl.style.setProperty( rootEl.style.setProperty('--color4', `${lightColor.r}, ${lightColor.g}, ${lightColor.b}`);
'--color4', rootEl.style.setProperty('--color5', `${darkColor.r}, ${darkColor.g}, ${darkColor.b}`);
`${lightColor.r}, ${lightColor.g}, ${lightColor.b}`,
);
rootEl.style.setProperty(
'--color5',
`${darkColor.r}, ${darkColor.g}, ${darkColor.b}`,
);
} }
isColorReadable.value = colord(base).isReadable( isColorReadable.value = colord(base).isReadable(isDarkTheme.value ? '#fff' : '#000', { level: 'AAA' });
isDarkTheme.value ? '#fff' : '#000',
{ level: 'AAA' },
);
} }
function handleChangeColors(harmonyColors: Harmony[]) { function handleChangeColors(harmonyColors: Harmony[]) {
@@ -92,20 +80,13 @@ watch(
<div> <div>
<c-card :title="t('tools.color-wheel.texts.title-pick-a-color')" mb-2> <c-card :title="t('tools.color-wheel.texts.title-pick-a-color')" mb-2>
<n-color-picker v-model:value="inputColor" :show-alpha="false" /> <n-color-picker v-model:value="inputColor" :show-alpha="false" />
<div <div :style="{ backgroundColor: inputColor }" />
:style="{ backgroundColor: inputColor }"
/>
</c-card> </c-card>
<c-card :title="t('tools.color-wheel.texts.title-pick-a-palette-type')" mb-2> <c-card :title="t('tools.color-wheel.texts.title-pick-a-palette-type')" mb-2>
<n-radio-group v-model:value="currentType" name="radiogroup"> <n-radio-group v-model:value="currentType" name="radiogroup">
<n-space> <n-space>
<n-radio <n-radio v-for="v in harmonyTypes" :key="v.type" :value="v.type" :label="v.label" />
v-for="v in harmonyTypes"
:key="v.type"
:value="v.type"
:label="v.label"
/>
</n-space> </n-space>
</n-radio-group> </n-radio-group>
</c-card> </c-card>
@@ -122,11 +103,7 @@ watch(
/> />
</div> </div>
</c-card> </c-card>
<div <div v-for="(color, i) in colorList" :key="i" mt-1 flex items-center justify-center gap-1>
v-for="(color, i) in colorList"
:key="i"
mt-1 flex items-center justify-center gap-1
>
<div <div
p-1 p-1
:style="{ :style="{
@@ -23,14 +23,18 @@ async function loadMemo(currentLocale = locale.value) {
memoComponent.value = module.default ?? module; memoComponent.value = module.default ?? module;
} }
watch(locale, () => { watch(
locale,
() => {
loadMemo(); loadMemo();
}, { immediate: true }); },
{ immediate: true },
);
</script> </script>
<template> <template>
<div> <div>
<component :is="memoComponent" style="overflow-x: auto;" /> <component :is="memoComponent" style="overflow-x: auto" />
</div> </div>
</template> </template>
@@ -45,7 +49,9 @@ watch(locale, () => {
::v-deep(table) { ::v-deep(table) {
border-collapse: collapse; border-collapse: collapse;
} }
::v-deep(table), ::v-deep(td), ::v-deep(th) { ::v-deep(table),
::v-deep(td),
::v-deep(th) {
border: 1px solid v-bind('themeVars.textColor1'); border: 1px solid v-bind('themeVars.textColor1');
padding: 5px; padding: 5px;
} }
+2 -2
View File
@@ -1,4 +1,4 @@
Patterns you reach for again and again, written for the **JavaScript/PCRE** flavour. Drop the surrounding anchors (`^`…`$`) when you want to *find* matches inside a longer text instead of validating a whole string. Patterns you reach for again and again, written for the **JavaScript/PCRE** flavour. Drop the surrounding anchors (`^`…`$`) when you want to _find_ matches inside a longer text instead of validating a whole string.
> ⚠️ Validation by regex is always an approximation. For emails, phone numbers, URLs and credit cards, a regex is a cheap first filter — the real check is a library, or sending the confirmation. > ⚠️ Validation by regex is always an approximation. For emails, phone numbers, URLs and credit cards, a regex is a cheap first filter — the real check is a library, or sending the confirmation.
@@ -134,7 +134,7 @@ https?:\/\/[^\s<>"']+
^P(?!$)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$ ^P(?!$)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$
``` ```
> ℹ️ These check the *shape*, not the calendar — `2026-02-31` passes. Parse the value if the date has to be real. > ℹ️ These check the _shape_, not the calendar — `2026-02-31` passes. Parse the value if the date has to be real.
## 🔐 Password Rules ## 🔐 Password Rules
+50 -45
View File
@@ -1,47 +1,46 @@
### 常用正则表达式 ### 常用正则表达式
#### 1\. 数字 #### 1\. 数字
* [整数](https://www.regexpal.com/?fam=104020) – `/^\d+$/` - [整数](https://www.regexpal.com/?fam=104020) – `/^\d+$/`
* [小数](https://www.regexpal.com/?fam=104021) – `/^\d*\.\d+$/` - [小数](https://www.regexpal.com/?fam=104021) – `/^\d*\.\d+$/`
* [整数 + 小数](https://www.regexpal.com/?fam=104022) – `/^\d*(\.\d+)?$/` - [整数 + 小数](https://www.regexpal.com/?fam=104022) – `/^\d*(\.\d+)?$/`
* [负数、正数的整数 + 小数](https://www.regexpal.com/?fam=104023) – `/^-?\d*(\.\d+)?$/` - [负数、正数的整数 + 小数](https://www.regexpal.com/?fam=104023) – `/^-?\d*(\.\d+)?$/`
* [整数 + 小数 + 分数](https://www.regexpal.com/94462) – `/[-]?[0-9]+[,.]?[0-9]*([\/][0-9]+[,.]?[0-9]*)*/` - [整数 + 小数 + 分数](https://www.regexpal.com/94462) – `/[-]?[0-9]+[,.]?[0-9]*([\/][0-9]+[,.]?[0-9]*)*/`
#### 2\. 字母数字字符 #### 2\. 字母数字字符
* [不含空格的字母数字](https://www.regexpal.com/?fam=104024) – `/^[a-zA-Z0-9]*$/` - [不含空格的字母数字](https://www.regexpal.com/?fam=104024) – `/^[a-zA-Z0-9]*$/`
* [含空格的字母数字](https://www.regexpal.com/?fam=104025) – `/^[a-zA-Z0-9 ]*$/` - [含空格的字母数字](https://www.regexpal.com/?fam=104025) – `/^[a-zA-Z0-9 ]*$/`
#### 3\. 邮箱 #### 3\. 邮箱
* [常见邮箱地址](https://www.regexpal.com/?fam=104026) – `/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$/` - [常见邮箱地址](https://www.regexpal.com/?fam=104026) – `/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$/`
* [不常见邮箱地址](https://www.regexpal.com/?fam=104027) – `/^([a-z0-9_\.\+-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/` - [不常见邮箱地址](https://www.regexpal.com/?fam=104027) – `/^([a-z0-9_\.\+-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/`
#### 4\. 密码强度 #### 4\. 密码强度
* [复杂](https://www.regexpal.com/?fam=104028):需包含 1 个小写字母、1 个大写字母、1 个数字、1 个特殊字符,且至少 8 个字符长 - [复杂](https://www.regexpal.com/?fam=104028):需包含 1 个小写字母、1 个大写字母、1 个数字、1 个特殊字符,且至少 8 个字符长
/(?=(.\*\[0-9\]))(?=.\*\[\\!@#$%^&\*()\\\\\[\\\]{}\\-\_+=~\`|:;"'<>,./?\])(?=.\*\[a-z\])(?=(.\*\[A-Z\]))(?=(.\*)).{8,}/ /(?=(.\*\[0-9\]))(?=.\*\[\\!@#$%^&\*()\\\\\[\\\]{}\\-\_+=~\`|:;"'<>,./?\])(?=.\*\[a-z\])(?=(.\*\[A-Z\]))(?=(.\*)).{8,}/
* [中等](https://www.regexpal.com/?fam=104029):需包含 1 个小写字母、1 个大写字母、1 个数字,且至少 8 个字符长 - [中等](https://www.regexpal.com/?fam=104029):需包含 1 个小写字母、1 个大写字母、1 个数字,且至少 8 个字符长
/(?=(.\*\[0-9\]))((?=.\*\[A-Za-z0-9\])(?=.\*\[A-Z\])(?=.\*\[a-z\]))^.{8,}$/ /(?=(.\*\[0-9\]))((?=.\*\[A-Za-z0-9\])(?=.\*\[A-Z\])(?=.\*\[a-z\]))^.{8,}$/
#### 5\. 用户名 #### 5\. 用户名
* [字母数字字符串](https://www.regexpal.com/?fam=104030),可包含 \_ 和 –,长度为 3 到 16 个字符 – `/^[a-z0-9_-]{3,16}$/` - [字母数字字符串](https://www.regexpal.com/?fam=104030),可包含 \_ 和 –,长度为 3 到 16 个字符 – `/^[a-z0-9_-]{3,16}$/`
#### 6\. URL #### 6\. URL
* 包含 [http(s) 协议](https://www.regexpal.com/?fam=104034) - 包含 [http(s) 协议](https://www.regexpal.com/?fam=104034)
``` ```
/https?:\\/\\/(www\\.)?\[-a-zA-Z0-9@:%.\_\\+~#=\]{2,256}\\.\[a-z\]{2,6}\\b(\[-a-zA-Z0-9@:%\_\\+.~#()?&//=\]\*)/ /https?:\\/\\/(www\\.)?\[-a-zA-Z0-9@:%.\_\\+~#=\]{2,256}\\.\[a-z\]{2,6}\\b(\[-a-zA-Z0-9@:%\_\\+.~#()?&//=\]\*)/
``` ```
* [协议可选](https://www.regexpal.com/?fam=104035) - [协议可选](https://www.regexpal.com/?fam=104035)
``` ```
/(https?:\\/\\/)?(www\\.)?\[-a-zA-Z0-9@:%.\_\\+~#=\]{2,256}\\.\[a-z\]{2,6}\\b(\[-a-zA-Z0-9@:%\_\\+.~#?&//=\]\*)/ /(https?:\\/\\/)?(www\\.)?\[-a-zA-Z0-9@:%.\_\\+~#=\]{2,256}\\.\[a-z\]{2,6}\\b(\[-a-zA-Z0-9@:%\_\\+.~#?&//=\]\*)/
@@ -49,71 +48,76 @@
#### 7\. IP 地址 #### 7\. IP 地址
* [IPv4 地址](https://www.regexpal.com/?fam=104036) - [IPv4 地址](https://www.regexpal.com/?fam=104036)
``` ```
/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/ /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/
``` ```
* [IPv6 地址](https://www.regexpal.com/?fam=104037)
- [IPv6 地址](https://www.regexpal.com/?fam=104037)
``` ```
/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/ /(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/
``` ```
* 同时匹配 [IPv4、IPv6 地址](https://www.regexpal.com/?fam=104038) - 同时匹配 [IPv4、IPv6 地址](https://www.regexpal.com/?fam=104038)
``` ```
/((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))/ /((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))/
``` ```
#### 8\. 日期 #### 8\. 日期
* 日期格式 [YYYY-MM-dd](https://www.regexpal.com/?fam=104039),使用分隔符 `-` - 日期格式 [YYYY-MM-dd](https://www.regexpal.com/?fam=104039),使用分隔符 `-`
`/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/` `/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/`
* 日期格式 [dd-MM-YYYY](https://regexr.com/?346hf),使用分隔符 `-` 或 `.` 或 `/` - 日期格式 [dd-MM-YYYY](https://regexr.com/?346hf),使用分隔符 `-` 或 `.` 或 `/`
`/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/` `/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/`
* 日期格式 [dd-mmm-YYYY](https://regexr.com/39tr1),使用分隔符 `-` 或 `.` 或 `/` - 日期格式 [dd-mmm-YYYY](https://regexr.com/39tr1),使用分隔符 `-` 或 `.` 或 `/`
`/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/` `/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/`
#### 9\. 时间 #### 9\. 时间
* 时间格式 [HH:MM 12 小时制](https://www.regexpal.com/?fam=104040),前导 0 可选 - 时间格式 [HH:MM 12 小时制](https://www.regexpal.com/?fam=104040),前导 0 可选
`/^(0?[1-9]|1[0-2]):[0-5][0-9]$/` `/^(0?[1-9]|1[0-2]):[0-5][0-9]$/`
* 时间格式 HH:MM 12 小时制,前导 0 可选,**[带 AM/PM 标识](https://www.regexpal.com/?fam=104041)** - 时间格式 HH:MM 12 小时制,前导 0 可选,**[带 AM/PM 标识](https://www.regexpal.com/?fam=104041)**
`/((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/` `/((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/`
* 时间格式 [HH:MM 24 小时制](https://www.regexpal.com/?fam=104042),带前导 0 - 时间格式 [HH:MM 24 小时制](https://www.regexpal.com/?fam=104042),带前导 0
`/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/` `/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/`
* 时间格式 [HH:MM 24 小时制,前导 0 可选](https://www.regexpal.com/?fam=104043) - 时间格式 [HH:MM 24 小时制,前导 0 可选](https://www.regexpal.com/?fam=104043)
`/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/` `/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/`
* 时间格式 [HH:MM:SS 24 小时制](https://www.regexpal.com/?fam=104044) - 时间格式 [HH:MM:SS 24 小时制](https://www.regexpal.com/?fam=104044)
`/(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/` `/(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/`
#### 10\. HTML 标签 #### 10\. HTML 标签
* [带属性的元素](https://www.regexpal.com/95941) `/<\/?[\w\s]*>|<.+[\W]>/` - [带属性的元素](https://www.regexpal.com/95941) `/<\/?[\w\s]*>|<.+[\W]>/`
#### 11\. JavaScript 处理器 #### 11\. JavaScript 处理器
* [内联 JS 处理器](https://www.regexpal.com/?fam=104055) `/\bon\w+=\S+(?=.*>)/` - [内联 JS 处理器](https://www.regexpal.com/?fam=104055) `/\bon\w+=\S+(?=.*>)/`
* [带元素的内联 JS 处理器](https://www.regexpal.com/94641) `/(?:<[^>]+\s)(on\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/` - [带元素的内联 JS 处理器](https://www.regexpal.com/94641) `/(?:<[^>]+\s)(on\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/`
#### 12\. Slug #### 12\. Slug
* [Slug](https://www.regexpal.com/?fam=104056) `/^[a-z0-9]+(?:-[a-z0-9]+)*$/` - [Slug](https://www.regexpal.com/?fam=104056) `/^[a-z0-9]+(?:-[a-z0-9]+)*$/`
#### 13\. 匹配字符串中的重复项 #### 13\. 匹配字符串中的重复项
* [搜索重复项](https://www.regexpal.com/?fam=104060) `/(\b\w+\b)(?=.*\b\1\b)/` - [搜索重复项](https://www.regexpal.com/?fam=104060) `/(\b\w+\b)(?=.*\b\1\b)/`
#### 14\. 电话号码 #### 14\. 电话号码
* [国际电话号码](https://www.regexpal.com/?fam=99127) – 带可选的国家代码/分机号 - [国际电话号码](https://www.regexpal.com/?fam=99127) – 带可选的国家代码/分机号
``` ```
`/* International Phone Numbers */` `/* International Phone Numbers */`
/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:``#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/ /^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:``#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/
@@ -123,19 +127,19 @@ _注意:_ **仅**在没有其他选择时才使用正则表达式验证电话
#### 15\. 文件路径 #### 15\. 文件路径
* [带文件名和扩展名的文件路径](https://www.regexpal.com/?fam=104047) - [带文件名和扩展名的文件路径](https://www.regexpal.com/?fam=104047)
``` ```
/((\\/|\\\\|\\/\\/|https?:\\\\\\\\|https?:\\/\\/)\[a-z0-9 \_@\\-^!#$%&+={}.\\/\\\\\\\[\\\]\]+)+\\.\[a-z\]+$/ /((\\/|\\\\|\\/\\/|https?:\\\\\\\\|https?:\\/\\/)\[a-z0-9 \_@\\-^!#$%&+={}.\\/\\\\\\\[\\\]\]+)+\\.\[a-z\]+$/
``` ```
* 带可选文件名、扩展名的文件路径 - 带可选文件名、扩展名的文件路径
``` ```
/^(.+)/(\[^/\]+)$/ /^(.+)/(\[^/\]+)$/
``` ```
* [带 3 字符扩展名的文件名](https://www.regexpal.com/?fam=104048) - [带 3 字符扩展名的文件名](https://www.regexpal.com/?fam=104048)
``` ```
/^\[\\w,\\s-\]+\\.\[A-Za-z\]{3}$/ /^\[\\w,\\s-\]+\\.\[A-Za-z\]{3}$/
@@ -153,7 +157,7 @@ _注意:_ **仅**在没有其他选择时才使用正则表达式验证电话
#### 3\. 身份证件 #### 3\. 身份证件
* 社会保障号 – [参考](https://www.codeproject.com/Articles/651609/Validating-Social-Security-Numbers-through-Regular) - 社会保障号 – [参考](https://www.codeproject.com/Articles/651609/Validating-Social-Security-Numbers-through-Regular)
``` ```
/\* can use either hypen(-) or space( ) character as separator \*/ /\* can use either hypen(-) or space( ) character as separator \*/
@@ -161,14 +165,15 @@ _注意:_ **仅**在没有其他选择时才使用正则表达式验证电话
/^((?!219-09-9999|078-05-1120)(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4})|((?!219 09 9999|078 05 1120)(?!666|000|9\\d{2})\\d{3} (?!00)\\d{2} (?!0{4})\\d{4})|((?!219099999|078051120)(?!666|000|9\\d{2})\\d{3}(?!00)\\d{2}(?!0{4})\\d{4})$/ /^((?!219-09-9999|078-05-1120)(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4})|((?!219 09 9999|078 05 1120)(?!666|000|9\\d{2})\\d{3} (?!00)\\d{2} (?!0{4})\\d{4})|((?!219099999|078051120)(?!666|000|9\\d{2})\\d{3}(?!00)\\d{2}(?!0{4})\\d{4})$/
``` ```
* 护照 – `/^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$/` - 护照 – `/^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$/`
#### 参考文献 #### 参考文献
* [https://www.codeproject.com/validate-passport-number](https://www.codeproject.com/Questions/1046445/How-to-validate-passport-number-using-javascript)
* [https://gist.github.com/](https://gist.github.com/nerdsrescueme/1237767) - [https://www.codeproject.com/validate-passport-number](https://www.codeproject.com/Questions/1046445/How-to-validate-passport-number-using-javascript)
* [https://code.tutsplus.com/regular-expressions](https://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149) - [https://gist.github.com/](https://gist.github.com/nerdsrescueme/1237767)
* [https://www.regular-expressions.info](https://www.regular-expressions.info/) - [https://code.tutsplus.com/regular-expressions](https://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149)
* [http://www.regexlib.com/](http://www.regexlib.com/) - [https://www.regular-expressions.info](https://www.regular-expressions.info/)
* [https://projects.lukehaas.me/regexhub/](https://projects.lukehaas.me/regexhub/) - [http://www.regexlib.com/](http://www.regexlib.com/)
* [http://wiki.zoolz.com/commonly-used-regular-expressions/](http://wiki.zoolz.com/commonly-used-regular-expressions/) - [https://projects.lukehaas.me/regexhub/](https://projects.lukehaas.me/regexhub/)
* [https://www.smashingmagazine.com/advanced-regular-expressions/](https://www.smashingmagazine.com/2009/05/introduction-to-advanced-regular-expressions/) - [http://wiki.zoolz.com/commonly-used-regular-expressions/](http://wiki.zoolz.com/commonly-used-regular-expressions/)
- [https://www.smashingmagazine.com/advanced-regular-expressions/](https://www.smashingmagazine.com/2009/05/introduction-to-advanced-regular-expressions/)
+23 -6
View File
@@ -8,7 +8,10 @@ const { t } = useI18n();
const cookieHeader = useQueryParam({ tool: 'cookies-parser', name: 'cookies', defaultValue: '' }); const cookieHeader = useQueryParam({ tool: 'cookies-parser', name: 'cookies', defaultValue: '' });
const parsedCookies = computed(() => { const parsedCookies = computed(() => {
return (cookieHeader.value || '').replace(/^Cookie:\s*/, '').split('; ').map((cookie) => { return (cookieHeader.value || '')
.replace(/^Cookie:\s*/, '')
.split('; ')
.map((cookie) => {
const [name, ...values] = cookie.split('='); const [name, ...values] = cookie.split('=');
return { name, value: decodeURIComponent(values?.join('=') || '') }; return { name, value: decodeURIComponent(values?.join('=') || '') };
}); });
@@ -18,15 +21,29 @@ const parsedCookies = computed(() => {
<template> <template>
<n-card :title="t('tools.cookies-parser.texts.title-cookie-parser')"> <n-card :title="t('tools.cookies-parser.texts.title-cookie-parser')">
<n-space vertical> <n-space vertical>
<n-input v-model:value="cookieHeader" :placeholder="t('tools.cookies-parser.texts.placeholder-enter-cookie-header')" type="text" /> <n-input
v-model:value="cookieHeader"
:placeholder="t('tools.cookies-parser.texts.placeholder-enter-cookie-header')"
type="text"
/>
</n-space> </n-space>
<n-p> <n-p>
{{ t('tools.cookies-parser.texts.tag-tip-navigate-to-a-website-to-test-open-f12-console-and-run') }}<n-tag :bordered="false"> {{ t('tools.cookies-parser.texts.tag-tip-navigate-to-a-website-to-test-open-f12-console-and-run')
<code>{{ t('tools.cookies-parser.texts.tag-window-copy-document-cookie') }}</code> }}<n-tag :bordered="false">
</n-tag>{{ t('tools.cookies-parser.texts.tag-this-will-copy-the-cookie-string-to-your-clipboard-note-this-will-only-copy-cookies-available-to-javascript-http-only-and-secure-cookies-will-be-omitted') }} <code>{{ t('tools.cookies-parser.texts.tag-window-copy-document-cookie') }}</code> </n-tag
>{{
t(
'tools.cookies-parser.texts.tag-this-will-copy-the-cookie-string-to-your-clipboard-note-this-will-only-copy-cookies-available-to-javascript-http-only-and-secure-cookies-will-be-omitted',
)
}}
</n-p> </n-p>
<n-table v-if="parsedCookies.length"> <n-table v-if="parsedCookies.length">
<thead><tr><th>{{ t('tools.cookies-parser.texts.tag-name') }}</th><th>{{ t('tools.cookies-parser.texts.tag-value') }}</th></tr></thead> <thead>
<tr>
<th>{{ t('tools.cookies-parser.texts.tag-name') }}</th>
<th>{{ t('tools.cookies-parser.texts.tag-value') }}</th>
</tr>
</thead>
<tbody> <tbody>
<tr v-for="cookie in parsedCookies" :key="cookie.name"> <tr v-for="cookie in parsedCookies" :key="cookie.name">
<td> <td>
+1 -1
View File
@@ -1,3 +1,3 @@
declare module "vue3-flip-countdown" { declare module 'vue3-flip-countdown' {
export function Countdown(): any; export function Countdown(): any;
} }
@@ -101,7 +101,7 @@ describe('crc-calculator', () => {
it('re-encodes every checksum of "Hello, World!" as the ui does', () => { it('re-encodes every checksum of "Hello, World!" as the ui does', () => {
const hashes = getCRCs('Hello, World!'); const hashes = getCRCs('Hello, World!');
expect(algoNames.map(algo => formatHexWithEncoding(hashes[algo], 'Hex'))).toEqual([ expect(algoNames.map((algo) => formatHexWithEncoding(hashes[algo], 'Hex'))).toEqual([
'69', '69',
'87', '87',
'9c', '9c',
@@ -116,7 +116,7 @@ describe('crc-calculator', () => {
'19270120', '19270120',
'13b53c2f', '13b53c2f',
]); ]);
expect(algoNames.map(algo => formatHexWithEncoding(hashes[algo], 'Base64'))).toEqual([ expect(algoNames.map((algo) => formatHexWithEncoding(hashes[algo], 'Base64'))).toEqual([
'aQ==', 'aQ==',
'hw==', 'hw==',
'nA==', 'nA==',
+6 -2
View File
@@ -5,7 +5,10 @@ export const tool = defineTool({
name: t('tools.crc-calculator.title'), name: t('tools.crc-calculator.title'),
path: '/crc-calculator', path: '/crc-calculator',
description: t('tools.crc-calculator.description'), description: t('tools.crc-calculator.description'),
keywords: ['crc', 'checksum', 'crc1', keywords: [
'crc',
'checksum',
'crc1',
'crc8', 'crc8',
'crc8 1-wire', 'crc8 1-wire',
'crc8 dvb-s2', 'crc8 dvb-s2',
@@ -17,7 +20,8 @@ export const tool = defineTool({
'crc24', 'crc24',
'crc32', 'crc32',
'crc32 mpeg-2', 'crc32 mpeg-2',
'crcjam'], 'crcjam',
],
component: () => import('./crc-calculator.vue'), component: () => import('./crc-calculator.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/EyeOff')), icon: defineAsyncComponent(() => import('@vicons/tabler/es/EyeOff')),
createdAt: new Date('2024-05-11'), createdAt: new Date('2024-05-11'),
@@ -15,7 +15,7 @@ const parsed = computed(() => {
</script> </script>
<template> <template>
<div style="max-width: 600px;"> <div style="max-width: 600px">
<c-input-text <c-input-text
v-model:value="cardNumber" v-model:value="cardNumber"
:label="t('tools.credit-card-checker.texts.label-credit-card-number')" :label="t('tools.credit-card-checker.texts.label-credit-card-number')"
@@ -27,13 +27,48 @@ const parsed = computed(() => {
<n-alert v-if="parsed && !parsed.validates" type="error"> <n-alert v-if="parsed && !parsed.validates" type="error">
{{ t('tools.credit-card-checker.texts.tag-invlid-credit-card-number') }} {{ t('tools.credit-card-checker.texts.tag-invlid-credit-card-number') }}
</n-alert> </n-alert>
<n-card v-if="parsed && parsed.validates" :title="t('tools.credit-card-checker.texts.title-credit-card-number-info')"> <n-card
<input-copyable :label="t('tools.credit-card-checker.texts.label-formatted')" label-position="left" label-width="150px" mb-1 :value="parsed.formatted" /> v-if="parsed && parsed.validates"
<input-copyable :label="t('tools.credit-card-checker.texts.label-pan-truncated')" label-position="left" label-width="150px" mb-1 :value="parsed.truncate" /> :title="t('tools.credit-card-checker.texts.title-credit-card-number-info')"
<input-copyable :label="t('tools.credit-card-checker.texts.label-scheme')" label-position="left" label-width="150px" mb-1 :value="parsed.scheme || 'Unknown'" /> >
<input-copyable :label="t('tools.credit-card-checker.texts.label-major-industry-identifier')" mb-1 :value="parsed.mii" /> <input-copyable
<input-copyable :label="t('tools.credit-card-checker.texts.label-issuer-identifier-number')" mb-1 :value="parsed.iin" /> :label="t('tools.credit-card-checker.texts.label-formatted')"
<input-copyable :label="t('tools.credit-card-checker.texts.label-cvv-length')" label-position="left" label-width="150px" mb-1 :value="parsed.cvv" /> label-position="left"
label-width="150px"
mb-1
:value="parsed.formatted"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-pan-truncated')"
label-position="left"
label-width="150px"
mb-1
:value="parsed.truncate"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-scheme')"
label-position="left"
label-width="150px"
mb-1
:value="parsed.scheme || 'Unknown'"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-major-industry-identifier')"
mb-1
:value="parsed.mii"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-issuer-identifier-number')"
mb-1
:value="parsed.iin"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-cvv-length')"
label-position="left"
label-width="150px"
mb-1
:value="parsed.cvv"
/>
</n-card> </n-card>
</div> </div>
</template> </template>
+8 -8
View File
@@ -1,11 +1,11 @@
declare module 'creditcard' { declare module 'creditcard' {
export function parse(creditCardNumber: string): { export function parse(creditCardNumber: string): {
formatted: string formatted: string;
truncate: string truncate: string;
scheme: string scheme: string;
mii: string mii: string;
iin: string iin: string;
validates: boolean validates: boolean;
cvv: number cvv: number;
} };
} }
@@ -11,7 +11,7 @@ function looksLikeAwsExpression(cronExpression: string) {
return /(?:^|\s)\?(?:\s|$)/.test(cronExpression); return /(?:^|\s)\?(?:\s|$)/.test(cronExpression);
} }
export function getLastExecutionTimes(cronExpression: string, tz?: string | undefined, count: number = 5) { export function getLastExecutionTimes(cronExpression: string, tz?: string, count: number = 5) {
const cronType = getCronType(cronExpression); const cronType = getCronType(cronExpression);
if (cronType === 'standard') { if (cronType === 'standard') {
@@ -46,8 +46,7 @@ function isStandardExpression(cronExpression: string) {
CronExpressionParser.parse(cronExpression); CronExpressionParser.parse(cronExpression);
cronstrue.toString(cronExpression, { throwExceptionOnParseError: true }); cronstrue.toString(cronExpression, { throwExceptionOnParseError: true });
return true; return true;
} } catch (_) {
catch (_) {
return false; return false;
} }
} }
@@ -57,8 +56,7 @@ function isAwsExpression(cronExpression: string) {
const parsed = new EventCronParser(cronExpression); const parsed = new EventCronParser(cronExpression);
parsed.validate(); parsed.validate();
return true; return true;
} } catch (_) {
catch (_) {
return false; return false;
} }
} }
+1 -1
View File
@@ -1,3 +1,3 @@
declare module "get-timezone-offset" { declare module 'get-timezone-offset' {
export default function (timeZoneName: string, date: Date); export default function (timeZoneName: string, date: Date);
} }
+2 -4
View File
@@ -11,8 +11,7 @@ export function getViewportDimensions(
width: maxWidth, width: maxWidth,
height: maxWidth / ratio, height: maxWidth / ratio,
}; };
} } else {
else {
return { return {
width: maxHeight * ratio, width: maxHeight * ratio,
height: maxHeight, height: maxHeight,
@@ -41,8 +40,7 @@ export function getBaseDimensions(
width: vH * iRatio, width: vH * iRatio,
height: vH, height: vH,
}; };
} } else {
else {
// Portrait relative to viewport // Portrait relative to viewport
return { return {
width: vW, width: vW,
@@ -1,49 +1,61 @@
import { pki } from 'node-forge'; import { pki } from 'node-forge';
import { generateRSAPairs, getSubjectAlternativeNames } from '@/utils/crypto'; import { generateRSAPairs, getSubjectAlternativeNames } from '@/utils/crypto';
export async function generateCSR(config: { export async function generateCSR(
bits?: number config: {
password?: string bits?: number;
commonName?: string password?: string;
countryName?: string commonName?: string;
city?: string countryName?: string;
state?: string city?: string;
organizationName?: string state?: string;
organizationalUnit?: string organizationName?: string;
subjectAlternativeNames?: string organizationalUnit?: string;
contactEmail?: string subjectAlternativeNames?: string;
} = {}): Promise<{ contactEmail?: string;
publicKeyPem: string } = {},
privateKeyPem: string ): Promise<{
csrPem: string publicKeyPem: string;
privateKeyPem: string;
csrPem: string;
}> { }> {
const { privateKey, publicKey } = await generateRSAPairs(config); const { privateKey, publicKey } = await generateRSAPairs(config);
// create a certification request (CSR) // create a certification request (CSR)
const csr = pki.createCertificationRequest(); const csr = pki.createCertificationRequest();
csr.publicKey = publicKey; csr.publicKey = publicKey;
csr.setSubject([{ csr.setSubject(
[
{
name: 'commonName', name: 'commonName',
value: config.commonName, value: config.commonName,
}, { },
{
name: 'countryName', name: 'countryName',
value: config.countryName, value: config.countryName,
}, { },
{
name: 'stateOrProvinceName', name: 'stateOrProvinceName',
value: config.state, value: config.state,
}, { },
{
name: 'localityName', name: 'localityName',
value: config.city, value: config.city,
}, { },
{
name: 'organizationName', name: 'organizationName',
value: config.organizationName, value: config.organizationName,
}, { },
{
name: 'organizationalUnitName', name: 'organizationalUnitName',
value: config.organizationalUnit, value: config.organizationalUnit,
}, { },
{
name: 'emailAddress', name: 'emailAddress',
value: config.contactEmail, value: config.contactEmail,
}].filter(attr => attr.value !== null && attr.value?.trim() !== '')); },
].filter((attr) => attr.value !== null && attr.value?.trim() !== ''),
);
const extensions = []; const extensions = [];
const sanExtension = getSubjectAlternativeNames(config.subjectAlternativeNames); const sanExtension = getSubjectAlternativeNames(config.subjectAlternativeNames);
@@ -51,10 +63,12 @@ export async function generateCSR(config: {
extensions.push(sanExtension); extensions.push(sanExtension);
} }
if (extensions.length) { if (extensions.length) {
csr.setAttributes([{ csr.setAttributes([
{
name: 'extensionRequest', name: 'extensionRequest',
extensions, extensions,
}]); },
]);
} }
// sign certification request // sign certification request
@@ -68,8 +82,6 @@ export async function generateCSR(config: {
return { return {
csrPem, csrPem,
publicKeyPem: pki.publicKeyToPem(publicKey), publicKeyPem: pki.publicKeyToPem(publicKey),
privateKeyPem: config?.password privateKeyPem: config?.password ? pki.encryptRsaPrivateKey(privateKey, config?.password) : privateUnencryptedKeyPem,
? pki.encryptRsaPrivateKey(privateKey, config?.password)
: privateUnencryptedKeyPem,
}; };
} }
+25 -48
View File
@@ -15,7 +15,7 @@ const commonNameValidation = useValidation({
rules: [ rules: [
{ {
message: t('tools.csr-generator.texts.message-common-name-domain-name-must-not-be-empty'), message: t('tools.csr-generator.texts.message-common-name-domain-name-must-not-be-empty'),
validator: value => value?.trim() !== '', validator: (value) => value?.trim() !== '',
}, },
], ],
}); });
@@ -36,13 +36,14 @@ const { attrs: bitsValidationAttrs } = useValidation({
rules: [ rules: [
{ {
message: t('tools.csr-generator.texts.bits-should-be-256-less-than-bits-less-than-16384-and-be-a-multiple-of-8'), message: t('tools.csr-generator.texts.bits-should-be-256-less-than-bits-less-than-16384-and-be-a-multiple-of-8'),
validator: value => value >= 256 && value <= 16384 && value % 8 === 0, validator: (value) => value >= 256 && value <= 16384 && value % 8 === 0,
}, },
], ],
}); });
const [certs, refreshCerts] = computedRefreshableAsync( const [certs, refreshCerts] = computedRefreshableAsync(
() => withDefaultOnErrorAsync(() => { () =>
withDefaultOnErrorAsync(() => {
if (!commonNameValidation.isValid) { if (!commonNameValidation.isValid) {
return emptyCSR; return emptyCSR;
} }
@@ -59,9 +60,9 @@ const [certs, refreshCerts] = computedRefreshableAsync(
subjectAlternativeNames: subjectAlternativeNames.value, subjectAlternativeNames: subjectAlternativeNames.value,
contactEmail: contactEmail.value, contactEmail: contactEmail.value,
}); });
}, }, emptyCSR),
emptyCSR, emptyCSR,
), emptyCSR); );
</script> </script>
<template> <template>
@@ -83,7 +84,8 @@ const [certs, refreshCerts] = computedRefreshableAsync(
<div> <div>
<n-form-item <n-form-item
:label="t('tools.csr-generator.texts.label-organization-name')" :label="t('tools.csr-generator.texts.label-organization-name')"
label-placement="left" label-width="100" label-placement="left"
label-width="100"
> >
<n-input <n-input
v-model:value="organizationName" v-model:value="organizationName"
@@ -95,7 +97,8 @@ const [certs, refreshCerts] = computedRefreshableAsync(
<div> <div>
<n-form-item <n-form-item
:label="t('tools.csr-generator.texts.label-organization-unit')" :label="t('tools.csr-generator.texts.label-organization-unit')"
label-placement="left" label-width="100" label-placement="left"
label-width="100"
> >
<n-input <n-input
v-model:value="organizationalUnit" v-model:value="organizationalUnit"
@@ -105,58 +108,31 @@ const [certs, refreshCerts] = computedRefreshableAsync(
</div> </div>
<div> <div>
<n-form-item <n-form-item :label="t('tools.csr-generator.texts.label-state')" label-placement="left" label-width="100">
:label="t('tools.csr-generator.texts.label-state')" <n-input v-model:value="state" :placeholder="t('tools.csr-generator.texts.placeholder-state')" />
label-placement="left" label-width="100"
>
<n-input
v-model:value="state"
:placeholder="t('tools.csr-generator.texts.placeholder-state')"
/>
</n-form-item> </n-form-item>
</div> </div>
<div> <div>
<n-form-item <n-form-item :label="t('tools.csr-generator.texts.label-city')" label-placement="left" label-width="100">
:label="t('tools.csr-generator.texts.label-city')" <n-input v-model:value="city" :placeholder="t('tools.csr-generator.texts.placeholder-city')" />
label-placement="left" label-width="100"
>
<n-input
v-model:value="city"
:placeholder="t('tools.csr-generator.texts.placeholder-city')"
/>
</n-form-item> </n-form-item>
</div> </div>
<div> <div>
<n-form-item <n-form-item :label="t('tools.csr-generator.texts.label-country')" label-placement="left" label-width="100">
:label="t('tools.csr-generator.texts.label-country')" <n-input v-model:value="country" :placeholder="t('tools.csr-generator.texts.placeholder-country')" />
label-placement="left" label-width="100"
>
<n-input
v-model:value="country"
:placeholder="t('tools.csr-generator.texts.placeholder-country')"
/>
</n-form-item> </n-form-item>
</div> </div>
<div> <div>
<n-form-item <n-form-item :label="t('tools.csr-generator.texts.label-contact-email')" label-placement="left" label-width="100">
:label="t('tools.csr-generator.texts.label-contact-email')" <n-input v-model:value="contactEmail" :placeholder="t('tools.csr-generator.texts.placeholder-contact-email')" />
label-placement="left" label-width="100"
>
<n-input
v-model:value="contactEmail"
:placeholder="t('tools.csr-generator.texts.placeholder-contact-email')"
/>
</n-form-item> </n-form-item>
</div> </div>
<div> <div>
<n-form-item <n-form-item :label="t('tools.csr-generator.texts.label-subject-alternative-names')" label-placement="top">
:label="t('tools.csr-generator.texts.label-subject-alternative-names')"
label-placement="top"
>
<n-input <n-input
v-model:value="subjectAlternativeNames" v-model:value="subjectAlternativeNames"
:placeholder="t('tools.csr-generator.texts.placeholder-dns-names-emails-ip-uri')" :placeholder="t('tools.csr-generator.texts.placeholder-dns-names-emails-ip-uri')"
@@ -166,10 +142,7 @@ const [certs, refreshCerts] = computedRefreshableAsync(
</div> </div>
<div> <div>
<n-form-item <n-form-item :label="t('tools.csr-generator.texts.label-private-key-passphrase')" label-placement="top">
:label="t('tools.csr-generator.texts.label-private-key-passphrase')"
label-placement="top"
>
<n-input <n-input
v-model:value="password" v-model:value="password"
type="password" type="password"
@@ -180,7 +153,11 @@ const [certs, refreshCerts] = computedRefreshableAsync(
</div> </div>
<div> <div>
<n-form-item :label="t('tools.csr-generator.texts.label-rsa-bits')" v-bind="bitsValidationAttrs as any" label-placement="left"> <n-form-item
:label="t('tools.csr-generator.texts.label-rsa-bits')"
v-bind="bitsValidationAttrs as any"
label-placement="left"
>
<n-input-number-i18n v-model:value="bits" min="256" max="16384" step="8" /> <n-input-number-i18n v-model:value="bits" min="256" max="16384" step="8" />
</n-form-item> </n-form-item>
</div> </div>
@@ -17,9 +17,7 @@ const gradientCSS = computed(() => {
const stops = _.orderBy(colorStops.value, 'position') const stops = _.orderBy(colorStops.value, 'position')
.map(({ color, position }) => `${color} ${position}%`) .map(({ color, position }) => `${color} ${position}%`)
.join(', '); .join(', ');
return gradientType.value === 'linear' return gradientType.value === 'linear' ? `linear-gradient(${angle.value}deg, ${stops})` : `radial-gradient(${stops})`;
? `linear-gradient(${angle.value}deg, ${stops})`
: `radial-gradient(${stops})`;
}); });
function addStop() { function addStop() {
@@ -46,7 +44,10 @@ function removeStop(index: number) {
</NRadioGroup> </NRadioGroup>
</NFormItem> </NFormItem>
<NFormItem v-if="gradientType === 'linear'" :label="t('tools.css-gradient-generator.texts.label-angle-degrees')"> <NFormItem
v-if="gradientType === 'linear'"
:label="t('tools.css-gradient-generator.texts.label-angle-degrees')"
>
<NSlider v-model:value="angle" :min="0" :max="360" :step="1" mr-1 /> <NSlider v-model:value="angle" :min="0" :max="360" :step="1" mr-1 />
<n-input-number :value="angle" /> <n-input-number :value="angle" />
</NFormItem> </NFormItem>
@@ -54,19 +55,9 @@ function removeStop(index: number) {
<c-card :title="t('tools.css-gradient-generator.texts.title-color-stops')"> <c-card :title="t('tools.css-gradient-generator.texts.title-color-stops')">
<div class="color-stop-list" w-full> <div class="color-stop-list" w-full>
<div <div v-for="(stop, index) in colorStops" :key="index" class="color-stop-item">
v-for="(stop, index) in colorStops"
:key="index"
class="color-stop-item"
>
<NColorPicker v-model:value="stop.color" /> <NColorPicker v-model:value="stop.color" />
<NInputNumber <NInputNumber v-model:value="stop.position" :min="0" :max="100" :step="1" style="width: 150px" />
v-model:value="stop.position"
:min="0"
:max="100"
:step="1"
style="width: 150px"
/>
<NButton size="small" type="error" @click="removeStop(index)"> <NButton size="small" type="error" @click="removeStop(index)">
{{ t('tools.css-gradient-generator.texts.tag-remove') }} {{ t('tools.css-gradient-generator.texts.tag-remove') }}
</NButton> </NButton>
@@ -54,9 +54,7 @@ const minifyOutput = computed(() =>
if (!minifyInput.value) { if (!minifyInput.value) {
return ''; return '';
} }
return selectedLanguage.value === 'css' return selectedLanguage.value === 'css' ? minifyCss(minifyInput.value) : minifyJs(minifyInput.value);
? minifyCss(minifyInput.value)
: minifyJs(minifyInput.value);
}, ''), }, ''),
); );
</script> </script>
Loaded 100 of 791 files, more files were not shown because too many files have changed in this diff. Show more