Compare commits

..
Author SHA1 Message Date
Robert Dobre 4379630758 feat(integer base converter): bit fields (#605)
Read single bits and bit fields (ranges) of the input number:
- positions as a list: 2, 12, 4-7, 7:4 (0 = LSB); invalid, negative,
  duplicate or too large positions are skipped and reported
- interactive bit strip: click to toggle a bit, drag or Shift+click to
  add a field, keyboard navigation with arrow keys
- results table with click to copy, overlap hints and optional field
  values in hex, octal, base64, a custom base and decimal
- positions and selected bases are kept in the URL and local storage
2026-11-29 21:47:18 +01:00
ShareVB 4da56575c2 fix(Fortune Wheel): some string hashcode
Fix #597
2026-11-29 21:35:50 +01:00
ShareVB 2b77e593cd i18n: extract remaining 2026-11-29 21:06:45 +01:00
ShareVB 9bc5d66211 feat(Passphrase/Token Generators): strength + interlink
Fix #602
2026-11-29 20:23:26 +01:00
ShareVB 941312ccc6 feat(Running Pace): Presets + new Running Planner tool
Fix part of #598
2026-11-29 20:23:26 +01:00
ShareVB 4c721e3124 feat(Mac Address Converter): add address validation
Fix part of #598
2026-11-29 20:23:26 +01:00
ShareVB 8e73a01af5 feat(new tool): SSH Key Formats Converter
Fix #603
2026-11-29 20:23:18 +01:00
21 changed files with 2531 additions and 15 deletions

No files matched your search

+121
View File
@@ -192,6 +192,13 @@ tools:
placeholder-put-characters-to-deny-from-token: Put characters to deny from token
label-number-of-token-to-generate: Number of token to generate
label-allow-ambiguous-characters: Allows Visually Ambigous Characters
tool:
texts:
very-strong: Very Strong
strong: Strong
fair: Fair
weak: Weak
very-weak: Very Weak
percentage-calculator:
title: Percentage calculator
description: >-
@@ -3239,6 +3246,15 @@ tools:
settings, try to change words count
words-words: Words ({0})
label-min-passphrase-len: 'Min passphrase len:'
tag-passphrase: Passphrase
tag-strength: Strength
link-to-token-generator: Use Token Generator to generate password or tokens
link-to-passphase-generator: Use Passphrase Generator to generate passphases
very-weak: Very Weak
weak: Weak
fair: Fair
very-strong: Very Strong
strong: Strong
paste-as-markdown:
title: Paste as Markdown
description: Paste cells/tables and links from clipboard content as Markdown
@@ -6215,6 +6231,45 @@ tools:
model:
text:
invalid-digit-digit-for-base-finalfrombase: Invalid digit "{0}" for base {1}.
bit-fields:
title: Bit fields
hint: 'Positions start at 0 (LSB), separated by commas or spaces. A field is a single bit (5) or a range (4-7 or 7:4).'
label-positions: Bit positions
placeholder-positions: 'ex: 2, 5, 12, 4-7'
ignored: 'Ignored: {0}'
reason-negative: negative
reason-invalid: not a position
reason-too-large: above 4095
reason-duplicate: duplicate
strip-label: Bits of the number. Arrow keys move, Enter toggles a bit, Shift+Enter adds a field.
bit-title: Bit {0}
bit-in-fields: in {0}
bit-selected-times: selected {0} times
how-to: Click a bit to add or remove it. Drag or Shift+click for a field.
legend-selected: selected
legend-multiple: more than once
drawn-note: Showing bits 0 to {0} of {1}. The table includes every requested bit.
values-in: 'Field values in:'
values-in-note: shown for fields
base-hex: Hex
base-octal: Octal
base-base64: Base64
base-custom: Custom
base-decimal: Decimal
custom-base: Custom base
header-field: Field
header-binary: Binary
header-base-n: Base {0}
header-dec: Dec
clear-all: Clear all
remove: Remove {0}
empty: Type bit positions above, or click bits in the strip. Click any value in the results to copy it.
also-in: also in {0}
overlaps: overlaps {0}
copy-value: Copy {0}
copied: 'Copied: {0}'
copy-values: Copy values
copy-as-text: Copy as text
menu-bar:
text:
fix-tables: Fix tables
@@ -9906,6 +9961,18 @@ tools:
tag-km: km
tag-mile: mile
tag-calculate: Calculate
marathon: Marathon
half-marathon: Half Marathon
resulttype: '{0}:'
two-of-time-length-and-pace-must-be-provided-nspeed-is-only-valid-when-pace-is-given-or-calculated: >-
Two of "time", "length" and "pace" must be provided.\nSpeed is only
valid when pace is given or calculated.
speed-0: Speed
speed-is-only-valid-when-only-pace-is-given-or-calculated-0: Speed is only valid when (only) pace is given or calculated
pace: Pace
speed: Speed
speed-is-only-valid-when-only-pace-is-given-or-calculated: Speed is only valid when (only) pace is given or calculated
only-two-of-time-length-and-pace-may-be-provided-at-any-time: Only two of "time", "length" and "pace" may be provided at any time
saml-parser:
title: SAML Parser
description: >-
@@ -10420,6 +10487,60 @@ tools:
texts:
the-provided-xmls-are-the-same: The provided XMLs are the same
only-show-differences: Only show differences
running-planner:
title: Running Pace Planner
description: >-
Running pace planner tool to help you plan your running pace and training
schedule.
externalAccess: null
texts:
label-kilometers: Kilometers
label-miles: Miles
label-5k: 5K
label-10k: 10K
label-15k: 15K
label-10-mile: 10 Mile
label-20k: 20K
label-half-marathon: Half Marathon
label-25k: 25K
label-30k: 30K
label-marathon: Marathon
label-50k-ultra: 50K Ultra
label-every-1-km: Every 1 km
label-every-2-km: Every 2 km
label-every-5-km: Every 5 km
label-every-10-km: Every 10 km
label-every-1-mile: Every 1 mile
label-every-2-miles: Every 2 miles
label-every-5-miles: Every 5 miles
label-unit: 'Unit:'
label-race: Race
placeholder-minutes: Minutes
placeholder-seconds: Seconds
label-checkpoints: 'Checkpoints:'
label-estimated-finish-time: Estimated Finish Time
title-projected-checkpoints: Projected Checkpoints
distance-unit: 'Distance ({0}):'
pace-unitlabel: 'Pace ({0}):'
custom-distance: Custom Distance
target: Target
distance-unit-value: Distance ({0})
target-0: Target
ssh-key-converter:
title: SSH Key Format Converter
description: Convert SSH keys between different formats
externalAccess: null
texts:
label-auto-detect: Auto Detect
label-openssh: OpenSSH
label-rfc4716: RFC4716
label-pem: PEM
label-pkcs8: PKCS8
label-source-format: Source Format
label-target-format: Target Format
label-input-key: Input Key
placeholder-paste-ssh-key-here: Paste SSH key here...
title-output-key: Output Key
analogSignalConverter:
texts:
title-input: Input
+1 -1
View File
@@ -222,7 +222,7 @@
"highlight.js": "^11.11.1",
"html-to-text": "^10.0.0",
"htmlfy": "^1.0.2",
"htmlparser2": "^12.0.0",
"htmlparser2": "^10.1.0",
"hyparquet": "^1.26.2",
"hyparquet-compressors": "^1.1.1",
"ibantools": "^4.5.4",
+2 -2
View File
@@ -744,8 +744,8 @@ importers:
specifier: ^1.0.2
version: 1.0.2
htmlparser2:
specifier: ^12.0.0
version: 12.0.0
specifier: ^10.1.0
version: 10.1.0
hyparquet:
specifier: ^1.26.2
version: 1.26.2
+2 -2
View File
@@ -60,7 +60,7 @@ function getContrastColor(hue: number, saturation: number, lightness: number): s
const m = l - c / 2;
// Compact RGB calculation using array indexing
const hueSegment = Math.floor(h * 6);
const hueSegment = Math.floor(Math.abs(h) * 6);
const rgbValues = [
[c, x, 0], // 0-60°
[x, c, 0], // 60-120°
@@ -70,7 +70,7 @@ function getContrastColor(hue: number, saturation: number, lightness: number): s
[c, 0, x], // 300-360°
];
const [r, g, b] = rgbValues[hueSegment].map((val) => (val + m) * 255);
const [r, g, b] = rgbValues[hueSegment % 6].map((val) => (val + m) * 255);
// Calculate relative luminance and return appropriate contrast color
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
@@ -0,0 +1,168 @@
import { describe, expect, it } from 'vitest';
import {
extractBitField,
formatBitFieldBinary,
getBitCoverage,
getBitFieldLabel,
getDisplayedBitCount,
getOverlappingFields,
parseBitPositions,
removeBitPositionToken,
toggleBitPosition,
toggleBitRange,
tokenizeBitPositions,
} from './bit-fields.model';
const fieldsOf = (text: string) => parseBitPositions(text).fields.map(({ lo, hi }) => [lo, hi]);
const ignoredOf = (text: string) => parseBitPositions(text).ignored;
describe('bit-fields', () => {
describe('tokenizeBitPositions', () => {
it('splits on commas, semicolons and whitespace', () => {
expect(tokenizeBitPositions('2, 5;12 4-7')).toEqual(['2', '5', '12', '4-7']);
expect(tokenizeBitPositions('2,,5,')).toEqual(['2', '5']);
expect(tokenizeBitPositions(' ')).toEqual([]);
});
it('joins ranges written with spaces or with dash variants', () => {
expect(tokenizeBitPositions('4 - 7, 7 : 4, 0 .. 3')).toEqual(['4-7', '7:4', '0..3']);
expect(tokenizeBitPositions('4–7, 4—7, −2')).toEqual(['4-7', '4-7', '-2']);
});
it('keeps a space-separated negative number apart', () => {
expect(tokenizeBitPositions('2 -3')).toEqual(['2', '-3']);
});
});
describe('parseBitPositions', () => {
it('parses single bits and ranges in any order', () => {
expect(fieldsOf('2, 12, 4-7, 7:4, 0..3, 4-4')).toEqual([
[2, 2],
[12, 12],
[4, 7],
[0, 3],
[4, 4],
]);
expect(fieldsOf('007')).toEqual([[7, 7]]);
});
it('keeps the index of the token each field comes from', () => {
expect(parseBitPositions('x, 3, 4-5').fields.map(({ tokenIndex }) => tokenIndex)).toEqual([1, 2]);
});
it('ignores and reports negative positions', () => {
expect(fieldsOf('2, -3, 5')).toEqual([
[2, 2],
[5, 5],
]);
expect(ignoredOf('2, -3, 5')).toEqual([{ token: '-3', reason: 'negative' }]);
expect(ignoredOf('−2')).toEqual([{ token: '-2', reason: 'negative' }]);
expect(ignoredOf('4--7')).toEqual([{ token: '4--7', reason: 'negative' }]);
});
it('ignores and reports invalid tokens', () => {
for (const token of ['2.5', 'abc', '0x10', '3-', '-', '3-1-2']) {
expect(ignoredOf(token)).toEqual([{ token, reason: 'invalid' }]);
}
});
it('ignores and reports positions above the maximum', () => {
expect(ignoredOf('5000')).toEqual([{ token: '5000', reason: 'too-large' }]);
expect(ignoredOf('99999999999999999999')).toEqual([{ token: '99999999999999999999', reason: 'too-large' }]);
expect(fieldsOf('4095')).toEqual([[4095, 4095]]);
expect(ignoredOf('16')).toEqual([]);
expect(parseBitPositions('16', { maxBitPosition: 15 }).ignored).toEqual([{ token: '16', reason: 'too-large' }]);
});
it('ignores and reports exact duplicates', () => {
expect(fieldsOf('2, 2, 02')).toEqual([[2, 2]]);
expect(ignoredOf('2, 2, 02')).toEqual([
{ token: '2', reason: 'duplicate' },
{ token: '02', reason: 'duplicate' },
]);
expect(ignoredOf('7:4, 4-7')).toEqual([{ token: '4-7', reason: 'duplicate' }]);
});
});
describe('extractBitField', () => {
it('extracts single bits and fields', () => {
expect(extractBitField(0x1234n, { lo: 2, hi: 2 })).toEqual(1n);
expect(extractBitField(0x1234n, { lo: 3, hi: 3 })).toEqual(0n);
expect(extractBitField(0x1234n, { lo: 4, hi: 7 })).toEqual(3n);
expect(extractBitField(0x1234n, { lo: 12, hi: 15 })).toEqual(1n);
});
it('returns 0 for bits above the value', () => {
expect(extractBitField(0xffn, { lo: 300, hi: 300 })).toEqual(0n);
});
it('works on numbers wider than 64 bits', () => {
const value = BigInt('0xDEADBEEFCAFEBABE0123456789ABCDEF');
expect(extractBitField(value, { lo: 120, hi: 127 })).toEqual(0xden);
expect(extractBitField(value, { lo: 0, hi: 7 })).toEqual(0xefn);
});
});
describe('formatBitFieldBinary', () => {
it('pads the binary value to the field width', () => {
expect(formatBitFieldBinary(0x1234n, { lo: 4, hi: 7 })).toEqual('0011');
expect(formatBitFieldBinary(0n, { lo: 0, hi: 7 })).toEqual('00000000');
expect(formatBitFieldBinary(0x1234n, { lo: 2, hi: 2 })).toEqual('1');
});
});
describe('getBitFieldLabel', () => {
it('names single bits and fields', () => {
expect(getBitFieldLabel({ lo: 5, hi: 5 })).toEqual('bit 5');
expect(getBitFieldLabel({ lo: 4, hi: 7 })).toEqual('bits 7..4');
});
});
describe('getBitCoverage and getOverlappingFields', () => {
const { fields } = parseBitPositions('2, 12, 4-7, 5, 3-10');
it('counts how many fields contain each bit', () => {
const coverage = getBitCoverage(fields);
expect(coverage.get(5)).toEqual([2, 3, 4]);
expect(coverage.get(2)).toEqual([0]);
expect(coverage.get(0)).toBeUndefined();
});
it('lists the fields sharing bits with a field', () => {
expect(getOverlappingFields(fields, 2)).toEqual([3, 4]);
expect(getOverlappingFields(fields, 0)).toEqual([]);
});
});
describe('getDisplayedBitCount', () => {
it('rounds up to whole bytes, covering the value and the selected bits', () => {
expect(getDisplayedBitCount(0n, [])).toEqual(8);
expect(getDisplayedBitCount(0x1234n, [])).toEqual(16);
expect(getDisplayedBitCount(0xffn, parseBitPositions('20').fields)).toEqual(24);
});
});
describe('editing helpers', () => {
it('toggles single bits', () => {
expect(toggleBitPosition('2, 4-7', 5)).toEqual('2, 4-7, 5');
expect(toggleBitPosition('2, 4-7, 5', 5)).toEqual('2, 4-7');
expect(toggleBitPosition('', 0)).toEqual('0');
});
it('keeps invalid tokens when editing', () => {
expect(toggleBitPosition('-3, 2, 4-7', 2)).toEqual('-3, 4-7');
expect(removeBitPositionToken('-3, 2, 4-7', 2)).toEqual('-3, 2');
});
it('toggles ranges in either direction', () => {
expect(toggleBitRange('2', 11, 8)).toEqual('2, 8-11');
expect(toggleBitRange('2, 8-11', 8, 11)).toEqual('2');
expect(toggleBitRange('2, 11:8', 11, 8)).toEqual('2');
expect(toggleBitRange('2', 3, 3)).toEqual('2, 3');
});
it('replaces the start bit of a Shift+click selection', () => {
expect(toggleBitRange('2, 15', 15, 13, { replaceBit: 15 })).toEqual('2, 13-15');
});
});
});
@@ -0,0 +1,179 @@
export const MAX_BIT_POSITION = 4095;
export interface BitField {
/** Lowest bit position of the field (0 = LSB) */
lo: number;
/** Highest bit position of the field */
hi: number;
/** Index of the token this field was parsed from, see tokenizeBitPositions */
tokenIndex: number;
}
export type IgnoredReason = 'negative' | 'invalid' | 'too-large' | 'duplicate';
export interface IgnoredToken {
token: string;
reason: IgnoredReason;
}
/**
* Splits a list of bit positions into tokens.
* Separators: commas, semicolons and whitespace.
* En/em dashes and minus signs count as "-", so ranges pasted from datasheets work.
* "4 - 7" and "7 : 4" are ranges; "2 -3" is the position 2 and the (negative) token -3.
*/
export function tokenizeBitPositions(text: string): string[] {
return (text ?? '')
.replace(/[‐-―−﹣-]/g, '-')
.replace(/(\d)\s+-\s+(\d)/g, '$1-$2')
.replace(/\s*(:|\.\.)\s*/g, '$1')
.split(/[\s,;]+/)
.filter(Boolean);
}
/**
* Parses bit positions like "2, 12, 4-7, 7:4, 0..3".
* Never throws: invalid tokens are skipped and reported in `ignored`.
*/
export function parseBitPositions(text: string, { maxBitPosition = MAX_BIT_POSITION } = {}) {
const fields: BitField[] = [];
const ignored: IgnoredToken[] = [];
const seen = new Set<string>();
tokenizeBitPositions(text).forEach((token, tokenIndex) => {
let lo: number;
let hi: number;
const range = token.match(/^(\d+)(?:-|:|\.\.)(\d+)$/);
if (/^\d+$/.test(token)) {
lo = hi = Number(token);
} else if (range) {
lo = Math.min(Number(range[1]), Number(range[2]));
hi = Math.max(Number(range[1]), Number(range[2]));
} else {
const isNegative = /^-+\d/.test(token) || /\d(?:-|:|\.\.)-\d/.test(token);
ignored.push({ token, reason: isNegative ? 'negative' : 'invalid' });
return;
}
if (hi > maxBitPosition) {
ignored.push({ token, reason: 'too-large' });
return;
}
const key = `${lo}:${hi}`;
if (seen.has(key)) {
ignored.push({ token, reason: 'duplicate' });
return;
}
seen.add(key);
fields.push({ lo, hi, tokenIndex });
});
return { fields, ignored };
}
export function getBitFieldWidth(field: Pick<BitField, 'lo' | 'hi'>) {
return field.hi - field.lo + 1;
}
export function isSingleBit(field: Pick<BitField, 'lo' | 'hi'>) {
return field.lo === field.hi;
}
export function extractBitField(value: bigint, field: Pick<BitField, 'lo' | 'hi'>): bigint {
const mask = (1n << BigInt(getBitFieldWidth(field))) - 1n;
return (value >> BigInt(field.lo)) & mask;
}
/** Field value in binary, left-padded to the field width */
export function formatBitFieldBinary(value: bigint, field: Pick<BitField, 'lo' | 'hi'>) {
return extractBitField(value, field).toString(2).padStart(getBitFieldWidth(field), '0');
}
export function getBitFieldLabel(field: Pick<BitField, 'lo' | 'hi'>) {
return isSingleBit(field) ? `bit ${field.lo}` : `bits ${field.hi}..${field.lo}`;
}
export function getBitFieldShortLabel(field: Pick<BitField, 'lo' | 'hi'>) {
return isSingleBit(field) ? `${field.lo}` : `${field.hi}..${field.lo}`;
}
/** For each bit position, the indexes (in `fields`) of the fields containing it */
export function getBitCoverage(fields: BitField[]) {
const coverage = new Map<number, number[]>();
fields.forEach((field, index) => {
for (let bit = field.lo; bit <= field.hi; bit++) {
coverage.set(bit, [...(coverage.get(bit) ?? []), index]);
}
});
return coverage;
}
/** Indexes of the other fields sharing at least one bit with fields[index] */
export function getOverlappingFields(fields: BitField[], index: number) {
const { lo, hi } = fields[index];
return fields
.map((other, otherIndex) => ({ other, otherIndex }))
.filter(({ other, otherIndex }) => otherIndex !== index && other.lo <= hi && other.hi >= lo)
.map(({ otherIndex }) => otherIndex);
}
/** Number of bits to draw: whole bytes, at least 8, enough for the value and every selected bit */
export function getDisplayedBitCount(value: bigint, fields: BitField[]) {
const valueBits = value > 0n ? value.toString(2).length : 1;
const selectedBits = fields.reduce((max, field) => Math.max(max, field.hi + 1), 0);
return Math.ceil(Math.max(8, valueBits, selectedBits) / 8) * 8;
}
// Editing helpers: they return the new positions text and keep invalid tokens as they are.
function joinTokens(tokens: (string | null)[]) {
return tokens.filter((token): token is string => token !== null).join(', ');
}
export function removeBitPositionToken(text: string, tokenIndex: number) {
const tokens: (string | null)[] = tokenizeBitPositions(text);
if (tokenIndex >= 0 && tokenIndex < tokens.length) {
tokens[tokenIndex] = null;
}
return joinTokens(tokens);
}
/** Adds the single bit, or removes it if it is already listed as a single bit */
export function toggleBitPosition(text: string, bit: number) {
const existing = parseBitPositions(text).fields.find((field) => field.lo === bit && field.hi === bit);
if (existing) {
return removeBitPositionToken(text, existing.tokenIndex);
}
return joinTokens([...tokenizeBitPositions(text), String(bit)]);
}
/**
* Adds the field from..to, or removes it if it is already listed.
* replaceBit: a single bit to drop at the same time (the start of a Shift+click selection).
*/
export function toggleBitRange(text: string, from: number, to: number, { replaceBit }: { replaceBit?: number } = {}) {
const lo = Math.min(from, to);
const hi = Math.max(from, to);
if (lo === hi) {
return toggleBitPosition(text, lo);
}
const { fields } = parseBitPositions(text);
const tokens: (string | null)[] = tokenizeBitPositions(text);
if (replaceBit !== undefined) {
const single = fields.find((field) => field.lo === replaceBit && field.hi === replaceBit);
if (single) {
tokens[single.tokenIndex] = null;
}
}
const existing = fields.find((field) => field.lo === lo && field.hi === hi);
if (existing) {
tokens[existing.tokenIndex] = null;
} else {
tokens.push(`${lo}-${hi}`);
}
return joinTokens(tokens);
}
@@ -0,0 +1,986 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { useThemeVars } from 'naive-ui';
import {
type BitField,
type IgnoredReason,
extractBitField,
formatBitFieldBinary,
getBitCoverage,
getBitFieldLabel,
getBitFieldShortLabel,
getDisplayedBitCount,
getOverlappingFields,
isSingleBit,
parseBitPositions,
removeBitPositionToken,
toggleBitPosition,
toggleBitRange,
} from './bit-fields.model';
import { convertBase } from './integer-base-converter.model';
import { useCopy } from '@/composable/copy';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { useStyleStore } from '@/stores/style.store';
const props = defineProps<{ value: bigint | null }>();
const { t } = useI18n();
const themeVars = useThemeVars();
const styleStore = useStyleStore();
const { copy } = useCopy();
const MAX_DRAWN_BITS = 256;
const positions = useQueryParamOrStorage({ name: 'bits', storageName: 'int-base-conv:bits', defaultValue: '' });
const selectedBases = useQueryParamOrStorage({ name: 'fbases', storageName: 'int-base-conv:fbases', defaultValue: '' });
const customBase = useQueryParamOrStorage({ name: 'fcbase', storageName: 'int-base-conv:fcbase', defaultValue: 32 });
const baseOptions = computed(() => [
{ key: 'hex', label: t('tools.integer-base-converter.bit-fields.base-hex') },
{ key: 'oct', label: t('tools.integer-base-converter.bit-fields.base-octal') },
{ key: 'b64', label: t('tools.integer-base-converter.bit-fields.base-base64') },
{ key: 'custom', label: t('tools.integer-base-converter.bit-fields.base-custom') },
{ key: 'dec', label: t('tools.integer-base-converter.bit-fields.base-decimal') },
]);
const activeBases = computed(() => new Set(selectedBases.value.split(',').filter(Boolean)));
function toggleBase(key: string) {
const next = new Set(activeBases.value);
if (next.has(key)) {
next.delete(key);
} else {
next.add(key);
}
selectedBases.value = baseOptions.value
.map(({ key }) => key)
.filter((k) => next.has(k))
.join(',');
}
function toBase(value: bigint, base: number) {
return convertBase({ value: value.toString(10), fromBase: 10, toBase: base });
}
// Field value columns, in a fixed order with decimal last
const valueColumns = computed(() => {
const base = Math.min(64, Math.max(2, Math.round(customBase.value) || 32));
const columns: { key: string; header: string; format: (v: bigint) => string }[] = [];
const active = activeBases.value;
if (active.has('hex')) {
columns.push({
key: 'hex',
header: t('tools.integer-base-converter.bit-fields.base-hex'),
format: (v) => `0x${v.toString(16).toUpperCase()}`,
});
}
if (active.has('oct')) {
columns.push({
key: 'oct',
header: t('tools.integer-base-converter.bit-fields.base-octal'),
format: (v) => `0o${v.toString(8)}`,
});
}
if (active.has('b64')) {
columns.push({
key: 'b64',
header: t('tools.integer-base-converter.bit-fields.base-base64'),
format: (v) => toBase(v, 64),
});
}
if (active.has('custom')) {
columns.push({
key: 'custom',
header: t('tools.integer-base-converter.bit-fields.header-base-n', [base]),
format: (v) => toBase(v, base),
});
}
if (active.has('dec')) {
columns.push({
key: 'dec',
header: t('tools.integer-base-converter.bit-fields.header-dec'),
format: (v) => v.toString(10),
});
}
return columns;
});
const parsed = computed(() => parseBitPositions(positions.value));
const fields = computed(() => parsed.value.fields);
const coverage = computed(() => getBitCoverage(fields.value));
const hasRange = computed(() => fields.value.some((field) => !isSingleBit(field)));
const reasonLabels = computed<Record<IgnoredReason, string>>(() => ({
negative: t('tools.integer-base-converter.bit-fields.reason-negative'),
invalid: t('tools.integer-base-converter.bit-fields.reason-invalid'),
'too-large': t('tools.integer-base-converter.bit-fields.reason-too-large'),
duplicate: t('tools.integer-base-converter.bit-fields.reason-duplicate'),
}));
const ignoredMessage = computed(() =>
parsed.value.ignored.length
? t('tools.integer-base-converter.bit-fields.ignored', [
parsed.value.ignored.map(({ token, reason }) => `"${token}" (${reasonLabels.value[reason]})`).join(', '),
])
: '',
);
const displayedBitCount = computed(() => (props.value === null ? 0 : getDisplayedBitCount(props.value, fields.value)));
const drawnBitCount = computed(() => Math.min(displayedBitCount.value, MAX_DRAWN_BITS));
// Bytes from the most significant one, each listing its bits from MSB to LSB
const bytes = computed(() =>
Array.from({ length: drawnBitCount.value / 8 }, (_, i) => {
const start = drawnBitCount.value - 8 * (i + 1);
return Array.from({ length: 8 }, (_, j) => start + 7 - j);
}),
);
function bitValue(bit: number) {
return props.value === null ? 0 : Number((props.value >> BigInt(bit)) & 1n);
}
function selectionCount(bit: number) {
return coverage.value.get(bit)?.length ?? 0;
}
function bitTitle(bit: number) {
const parents = (coverage.value.get(bit) ?? []).map((i) => fields.value[i]).filter((field) => !isSingleBit(field));
const count = selectionCount(bit);
return [
t('tools.integer-base-converter.bit-fields.bit-title', [bit]),
parents.length
? t('tools.integer-base-converter.bit-fields.bit-in-fields', [parents.map(getBitFieldShortLabel).join(', ')])
: '',
count > 1 ? t('tools.integer-base-converter.bit-fields.bit-selected-times', [count]) : '',
]
.filter(Boolean)
.join(', ');
}
const rows = computed(() => {
if (props.value === null) {
return [];
}
const value = props.value;
return fields.value.map((field, index) => {
const single = isSingleBit(field);
const binary = formatBitFieldBinary(value, field);
const fieldValue = extractBitField(value, field);
const values = single ? [] : valueColumns.value.map((column) => column.format(fieldValue));
const overlaps = getOverlappingFields(fields.value, index).map((i) => getBitFieldShortLabel(fields.value[i]));
return {
index,
field,
single,
label: getBitFieldLabel(field),
binary,
values,
all: single ? binary : [`0b${binary}`, ...values].join(', '),
overlaps,
};
});
});
const allValues = computed(() => rows.value.map((row) => (row.single ? row.binary : `0b${row.binary}`)).join(', '));
const allAsText = computed(() => rows.value.map((row) => `${row.label} = ${row.all}`).join('\n'));
// Last bit clicked on the strip (start of a Shift+click field), and the single bit that click added
const lastClickedBit = ref<number | null>(null);
const justAddedBit = ref<number | null>(null);
// Copy with a short flash on the clicked element
const flashed = ref('');
async function copyValue(text: string, key: string) {
await copy(text, {
notificationMessage: t('tools.integer-base-converter.bit-fields.copied', [text.replace(/\n/g, ' | ')]),
});
flashed.value = key;
setTimeout(() => {
if (flashed.value === key) {
flashed.value = '';
}
}, 700);
}
function removeField(field: BitField) {
positions.value = removeBitPositionToken(positions.value, field.tokenIndex);
justAddedBit.value = null;
}
function clearAll() {
positions.value = '';
justAddedBit.value = null;
lastClickedBit.value = null;
}
// Strip selection: click toggles a bit, drag or Shift+click adds a field
const drag = ref<{ start: number; end: number; moved: boolean; shift: boolean } | null>(null);
function toggleBit(bit: number) {
const isListed = fields.value.some((field) => field.lo === bit && field.hi === bit);
positions.value = toggleBitPosition(positions.value, bit);
justAddedBit.value = isListed ? null : bit;
}
function addRange(from: number, to: number, fromShift = false) {
positions.value = toggleBitRange(positions.value, from, to, {
replaceBit: fromShift && justAddedBit.value !== null ? justAddedBit.value : undefined,
});
justAddedBit.value = null;
}
function isInDragPreview(bit: number) {
if (!drag.value?.moved) {
return false;
}
return bit >= Math.min(drag.value.start, drag.value.end) && bit <= Math.max(drag.value.start, drag.value.end);
}
function bitAt(x: number, y: number) {
const element = (document.elementFromPoint(x, y) as HTMLElement | null)?.closest<HTMLElement>('[data-bit]');
return element ? Number(element.dataset.bit) : null;
}
function onPointerDown(event: PointerEvent, bit: number) {
if (event.button !== 0) {
return;
}
event.preventDefault();
(event.currentTarget as HTMLElement).focus();
drag.value = { start: bit, end: bit, moved: false, shift: event.shiftKey };
}
function onPointerMove(event: PointerEvent) {
if (!drag.value) {
return;
}
const bit = bitAt(event.clientX, event.clientY);
if (bit !== null && bit !== drag.value.end) {
drag.value.end = bit;
drag.value.moved ||= bit !== drag.value.start;
}
}
function onPointerUp() {
if (!drag.value) {
return;
}
const { start, end, moved, shift } = drag.value;
drag.value = null;
if (moved) {
justAddedBit.value = null;
addRange(start, end);
lastClickedBit.value = end;
} else if (shift && lastClickedBit.value !== null) {
addRange(lastClickedBit.value, start, true);
lastClickedBit.value = start;
} else {
toggleBit(start);
lastClickedBit.value = start;
}
}
useEventListener(document, 'pointermove', onPointerMove);
useEventListener(document, 'pointerup', onPointerUp);
useEventListener(document, 'pointercancel', () => (drag.value = null));
// Keyboard: one tab stop on the strip, arrows move, Enter/Space toggles, Shift+Enter adds a field
const focusedBit = ref(0);
const stripRef = ref<HTMLElement | null>(null);
watch(drawnBitCount, (count) => {
if (focusedBit.value >= count) {
focusedBit.value = 0;
}
});
function focusBit(bit: number) {
focusedBit.value = Math.min(drawnBitCount.value - 1, Math.max(0, bit));
nextTick(() => stripRef.value?.querySelector<HTMLElement>(`[data-bit="${focusedBit.value}"]`)?.focus());
}
function onBitKeydown(event: KeyboardEvent, bit: number) {
const moves: Record<string, number> = {
ArrowLeft: bit + 1,
ArrowRight: bit - 1,
ArrowUp: bit + 8,
ArrowDown: bit - 8,
Home: drawnBitCount.value - 1,
End: 0,
};
if (event.key in moves) {
event.preventDefault();
focusBit(moves[event.key]);
return;
}
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
if (event.shiftKey && lastClickedBit.value !== null) {
addRange(lastClickedBit.value, bit, true);
} else {
toggleBit(bit);
}
lastClickedBit.value = bit;
}
}
// Mouse hover links the strip and the table (not on touch, where hover would stick)
const hoveredBit = ref<number | null>(null);
const hoveredRow = ref<number | null>(null);
function isBitHighlighted(bit: number) {
if (hoveredRow.value === null) {
return false;
}
const field = fields.value[hoveredRow.value];
return !!field && bit >= field.lo && bit <= field.hi;
}
function isRowHighlighted(index: number) {
if (hoveredRow.value === index) {
return true;
}
return hoveredBit.value !== null && (coverage.value.get(hoveredBit.value) ?? []).includes(index);
}
function onBitHover(event: PointerEvent, bit: number | null) {
hoveredBit.value = event.pointerType === 'mouse' && !drag.value ? bit : null;
}
function onRowHover(event: PointerEvent, index: number | null) {
hoveredRow.value = event.pointerType === 'mouse' ? index : null;
}
const colors = computed(() => ({
primary: themeVars.value.primaryColor,
primaryStrong: themeVars.value.primaryColorPressed,
badge: styleStore.isDarkTheme ? themeVars.value.primaryColorHover : themeVars.value.primaryColorPressed,
border: themeVars.value.borderColor,
muted: themeVars.value.textColor3,
text: themeVars.value.textColor1,
card: themeVars.value.cardColor,
hover: themeVars.value.hoverColor,
error: themeVars.value.errorColor,
warning: themeVars.value.warningColor,
highlight: styleStore.isDarkTheme ? 'rgba(240, 160, 32, 0.15)' : 'rgba(240, 160, 32, 0.12)',
}));
</script>
<template>
<div class="bit-fields">
<h3 class="title">
{{ t('tools.integer-base-converter.bit-fields.title') }}
</h3>
<p class="hint">
{{ t('tools.integer-base-converter.bit-fields.hint') }}
</p>
<c-input-text
v-model:value="positions"
:label="t('tools.integer-base-converter.bit-fields.label-positions')"
:placeholder="t('tools.integer-base-converter.bit-fields.placeholder-positions')"
label-position="left"
label-width="110px"
label-align="right"
clearable
raw-text
autocomplete="off"
spellcheck="false"
test-id="bit-positions"
/>
<n-alert
v-if="ignoredMessage"
type="warning"
:show-icon="false"
class="ignored"
data-test-id="bit-positions-ignored"
>
{{ ignoredMessage }}
</n-alert>
<template v-if="value !== null">
<div
ref="stripRef"
class="strip"
role="group"
:aria-label="t('tools.integer-base-converter.bit-fields.strip-label')"
@pointerleave="hoveredBit = null"
>
<div v-for="(byteBits, byteIndex) in bytes" :key="byteIndex" class="byte">
<button
v-for="bit in byteBits"
:key="bit"
type="button"
class="bit"
:class="{
selected: selectionCount(bit) > 0,
multiple: selectionCount(bit) > 1,
preview: isInDragPreview(bit),
linked: isBitHighlighted(bit),
}"
:data-bit="bit"
:data-count="selectionCount(bit)"
:tabindex="bit === focusedBit ? 0 : -1"
:aria-pressed="selectionCount(bit) > 0"
:title="bitTitle(bit)"
@pointerdown="onPointerDown($event, bit)"
@pointerover="onBitHover($event, bit)"
@keydown="onBitKeydown($event, bit)"
@focus="focusedBit = bit"
>
<span class="bit-value">{{ bitValue(bit) }}</span>
<span class="bit-index">{{ bit }}</span>
</button>
</div>
</div>
<div class="under-strip">
<p class="how-to">
{{ t('tools.integer-base-converter.bit-fields.how-to') }}
</p>
<div class="legend">
<span><i class="swatch" />{{ t('tools.integer-base-converter.bit-fields.legend-selected') }}</span>
<span><i class="swatch strong" />{{ t('tools.integer-base-converter.bit-fields.legend-multiple') }}</span>
</div>
</div>
<p v-if="displayedBitCount > MAX_DRAWN_BITS" class="drawn-note">
{{ t('tools.integer-base-converter.bit-fields.drawn-note', [MAX_DRAWN_BITS - 1, displayedBitCount]) }}
</p>
<div class="bases" :class="{ dim: !hasRange }">
<span class="bases-label">{{ t('tools.integer-base-converter.bit-fields.values-in') }}</span>
<template v-for="option in baseOptions" :key="option.key">
<c-button
size="small"
:type="activeBases.has(option.key) ? 'primary' : 'default'"
:aria-pressed="activeBases.has(option.key)"
:data-test-id="`bit-fields-base-${option.key}`"
@click="toggleBase(option.key)"
>
{{ option.label }}
</c-button>
<n-input-number
v-if="option.key === 'custom' && activeBases.has('custom')"
v-model:value="customBase"
:min="2"
:max="64"
:precision="0"
size="small"
class="custom-base"
:aria-label="t('tools.integer-base-converter.bit-fields.custom-base')"
/>
</template>
<span v-if="!hasRange" class="bases-note">{{
t('tools.integer-base-converter.bit-fields.values-in-note')
}}</span>
</div>
<p v-if="!rows.length" class="empty">
{{ t('tools.integer-base-converter.bit-fields.empty') }}
</p>
<div v-else class="table-wrapper">
<table class="results" data-test-id="bit-fields-results">
<thead>
<tr>
<th>{{ t('tools.integer-base-converter.bit-fields.header-field') }}</th>
<th>{{ t('tools.integer-base-converter.bit-fields.header-binary') }}</th>
<template v-if="hasRange">
<th v-for="column in valueColumns" :key="column.key" class="num">
{{ column.header }}
</th>
</template>
<th class="actions">
<button
type="button"
class="icon-button clear-all"
:title="t('tools.integer-base-converter.bit-fields.clear-all')"
:aria-label="t('tools.integer-base-converter.bit-fields.clear-all')"
@click="clearAll"
>
<icon-mdi-close />
</button>
</th>
</tr>
</thead>
<tbody @pointerleave="hoveredRow = null">
<tr
v-for="row in rows"
:key="`${row.field.tokenIndex}-${row.label}`"
:class="{ linked: isRowHighlighted(row.index) }"
@pointerover="onRowHover($event, row.index)"
>
<td class="label-cell">
<button
type="button"
class="cell"
:class="{ flashed: flashed === `${row.index}-all` }"
:title="t('tools.integer-base-converter.bit-fields.copy-value', [row.all])"
@click="copyValue(row.all, `${row.index}-all`)"
>
<span class="mono">{{ row.label }}</span>
<icon-mdi-content-copy class="copy-icon" />
<small v-if="row.overlaps.length">
{{
row.single
? t('tools.integer-base-converter.bit-fields.also-in', [row.overlaps.join(', ')])
: t('tools.integer-base-converter.bit-fields.overlaps', [row.overlaps.join(', ')])
}}
</small>
</button>
</td>
<td class="value-cell" :data-label="t('tools.integer-base-converter.bit-fields.header-binary')">
<button
type="button"
class="cell mono strong"
:class="{ one: row.single && row.binary === '1', flashed: flashed === `${row.index}-bin` }"
:title="t('tools.integer-base-converter.bit-fields.copy-value', [row.binary])"
@click="copyValue(row.binary, `${row.index}-bin`)"
>
{{ row.binary }}<icon-mdi-content-copy class="copy-icon" />
</button>
</td>
<template v-if="hasRange">
<td
v-for="(column, columnIndex) in valueColumns"
:key="column.key"
class="value-cell num"
:class="{ blank: row.single }"
:data-label="column.header"
>
<button
v-if="!row.single"
type="button"
class="cell mono"
:class="{ flashed: flashed === `${row.index}-${column.key}` }"
:title="t('tools.integer-base-converter.bit-fields.copy-value', [row.values[columnIndex]])"
@click="copyValue(row.values[columnIndex], `${row.index}-${column.key}`)"
>
{{ row.values[columnIndex] }}<icon-mdi-content-copy class="copy-icon" />
</button>
</td>
</template>
<td class="actions">
<button
type="button"
class="icon-button"
:aria-label="t('tools.integer-base-converter.bit-fields.remove', [row.label])"
:title="t('tools.integer-base-converter.bit-fields.remove', [row.label])"
@click="removeField(row.field)"
>
<icon-mdi-close />
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="rows.length" class="copy-all">
<c-button @click="copyValue(allValues, 'values')">
{{ t('tools.integer-base-converter.bit-fields.copy-values') }}
</c-button>
<c-button @click="copyValue(allAsText, 'text')">
{{ t('tools.integer-base-converter.bit-fields.copy-as-text') }}
</c-button>
</div>
</template>
</div>
</template>
<style lang="less" scoped>
.bit-fields {
.title {
margin: 0 0 4px;
font-size: 18px;
font-weight: 500;
}
.hint,
.how-to,
.drawn-note,
.bases-note,
.empty {
margin: 0;
font-size: 13px;
color: v-bind('colors.muted');
}
.hint {
margin-bottom: 12px;
}
.ignored {
margin-top: 6px;
font-size: 13px;
}
.mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
}
.strip {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 16px 14px;
margin: 20px 0 4px;
user-select: none;
}
.byte {
display: flex;
gap: 2px;
.bit:nth-child(5) {
margin-left: 6px;
}
}
.bit {
position: relative;
width: 26px;
padding: 3px 0 2px;
border: 1px solid v-bind('colors.border');
border-radius: 3px;
background: transparent;
color: v-bind('colors.text');
text-align: center;
cursor: pointer;
touch-action: none;
font: inherit;
.bit-value {
display: block;
font:
600 15px/1.3 ui-monospace,
SFMono-Regular,
Menlo,
Consolas,
monospace;
}
.bit-index {
display: block;
font-size: 10px;
color: v-bind('colors.muted');
}
&:focus-visible {
outline: 2px solid v-bind('colors.primary');
outline-offset: 1px;
}
&.selected {
background: v-bind('colors.primary');
border-color: v-bind('colors.primary');
color: #fff;
.bit-index {
color: rgba(255, 255, 255, 0.8);
}
}
&.multiple {
background: v-bind('colors.primaryStrong');
border-color: v-bind('colors.primaryStrong');
&::after {
content: attr(data-count);
position: absolute;
top: -11px;
right: -7px;
min-width: 15px;
height: 15px;
padding: 0 3px;
border: 1px solid v-bind('colors.badge');
border-radius: 8px;
background: v-bind('colors.card');
color: v-bind('colors.badge');
font: 600 10px/13px sans-serif;
}
}
&.preview {
outline: 2px dashed v-bind('colors.primary');
outline-offset: 1px;
}
&.linked {
box-shadow:
0 0 0 2px v-bind('colors.card'),
0 0 0 4px #f0a020;
}
}
@media (hover: hover) {
.bit:hover {
border-color: v-bind('colors.primary');
}
}
.under-strip {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: baseline;
gap: 4px 16px;
margin: 4px 0 6px;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 14px;
margin-left: auto;
font-size: 12px;
color: v-bind('colors.muted');
span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 2px;
background: v-bind('colors.primary');
&.strong {
background: v-bind('colors.primaryStrong');
}
}
}
.drawn-note {
text-align: right;
}
.bases {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
margin: 14px 0 0;
.bases-label {
margin-right: 4px;
font-size: 13px;
color: v-bind('colors.muted');
}
&.dim .c-button,
&.dim .custom-base {
opacity: 0.55;
}
.custom-base {
width: 90px;
}
}
.empty {
padding-top: 12px;
}
.table-wrapper {
margin-top: 12px;
overflow-x: auto;
}
.results {
width: 100%;
border-collapse: collapse;
font-size: 14px;
th {
padding: 6px 8px;
border-bottom: 1px solid v-bind('colors.border');
text-align: left;
font-weight: 500;
white-space: nowrap;
color: v-bind('colors.muted');
}
td {
padding: 4px;
border-bottom: 1px solid v-bind('colors.border');
white-space: nowrap;
}
.num {
text-align: right;
}
.actions {
width: 36px;
text-align: center;
}
tr.linked td {
background: v-bind('colors.highlight');
}
small {
display: block;
font-size: 11px;
color: v-bind('colors.muted');
}
}
.cell {
width: 100%;
padding: 4px 6px;
border: 0;
border-radius: 3px;
background: transparent;
color: v-bind('colors.text');
font: inherit;
text-align: inherit;
cursor: pointer;
&.strong {
font-weight: 600;
}
&.one {
color: v-bind('colors.primary');
}
&:focus-visible {
outline: none;
background: v-bind('colors.hover');
.copy-icon {
opacity: 1;
}
}
&.flashed {
background: v-bind('colors.primary');
color: #fff;
.copy-icon {
color: #fff;
}
}
.copy-icon {
margin-left: 6px;
font-size: 12px;
vertical-align: -1px;
color: v-bind('colors.primary');
opacity: 0;
}
}
@media (hover: hover) {
.cell:hover {
background: v-bind('colors.hover');
.copy-icon {
opacity: 1;
}
}
}
@media (hover: none) {
.cell .copy-icon {
opacity: 0.4;
}
}
.icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border: 0;
border-radius: 3px;
background: transparent;
color: v-bind('colors.muted');
font-size: 16px;
cursor: pointer;
&.clear-all {
color: v-bind('colors.error');
font-size: 18px;
}
&:focus-visible {
outline: 2px solid v-bind('colors.primary');
}
}
@media (hover: hover) {
.icon-button:hover {
background: v-bind('colors.hover');
color: v-bind('colors.error');
}
}
.copy-all {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
// Phones: each result becomes a small card
@media (max-width: 600px) {
.table-wrapper {
overflow-x: visible;
}
.results {
thead tr {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid v-bind('colors.border');
}
thead th {
display: none;
border: 0;
&:first-child,
&:last-child {
display: block;
}
}
tbody tr {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
padding: 4px 0;
border-bottom: 1px solid v-bind('colors.border');
}
td {
padding: 1px 0;
border: 0;
white-space: normal;
}
.label-cell {
grid-column: 1;
grid-row: 1;
}
td.actions {
grid-column: 2;
grid-row: 1;
}
.value-cell {
display: flex;
grid-column: 1 / -1;
align-items: center;
text-align: left;
&::before {
content: attr(data-label);
flex: none;
width: 80px;
padding-left: 6px;
font-size: 12px;
color: v-bind('colors.muted');
}
.cell {
width: auto;
}
&.blank {
display: none;
}
}
}
}
</style>
+16 -1
View File
@@ -5,7 +5,22 @@ export const tool = defineTool({
name: t('tools.base-converter.title'),
path: '/base-converter',
description: t('tools.base-converter.description'),
keywords: ['integer', 'number', 'base', 'conversion', 'decimal', 'hexadecimal', 'binary', 'octal', 'base64'],
keywords: [
'integer',
'number',
'base',
'conversion',
'decimal',
'hexadecimal',
'binary',
'octal',
'base64',
'bit',
'bits',
'bit field',
'register',
'mask',
],
component: () => import('./integer-base-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/ArrowsLeftRight')),
category: 'Converters',
@@ -0,0 +1,67 @@
import { expect, test } from '@playwright/test';
test.describe('Tool - Integer base converter - Bit fields', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/base-converter?num=0x1234');
});
test('Extracts single bits and fields', async ({ page }) => {
await page.getByTestId('bit-positions').fill('2, 12, 7:4, 5');
const rows = page.getByTestId('bit-fields-results').locator('tbody tr');
await expect(rows).toHaveCount(4);
await expect(rows.nth(0)).toContainText('bit 2');
await expect(rows.nth(0)).toContainText('1');
await expect(rows.nth(2)).toContainText('bits 7..4');
await expect(rows.nth(2)).toContainText('0011');
await expect(rows.nth(3)).toContainText('also in 7..4');
});
test('Shows the selected bases for fields only', async ({ page }) => {
await page.getByTestId('bit-positions').fill('2, 7:4');
await page.getByTestId('bit-fields-base-hex').click();
await page.getByTestId('bit-fields-base-dec').click();
const header = page.getByTestId('bit-fields-results').locator('thead');
await expect(header).toContainText('Hex');
await expect(header).toContainText('Dec');
const fieldRow = page.getByTestId('bit-fields-results').locator('tbody tr').nth(1);
await expect(fieldRow).toContainText('0x3');
});
test('Ignores invalid positions and reports them', async ({ page }) => {
await page.getByTestId('bit-positions').fill('2, -3, abc');
await expect(page.getByTestId('bit-positions-ignored')).toContainText('"-3" (negative)');
await expect(page.getByTestId('bit-positions-ignored')).toContainText('"abc" (not a position)');
await expect(page.getByTestId('bit-fields-results').locator('tbody tr')).toHaveCount(1);
});
test('Selects bits and fields on the strip', async ({ page }) => {
const positions = page.getByTestId('bit-positions');
await positions.fill('');
await page.locator('[data-bit="2"]').click();
await expect(positions).toHaveValue('2');
const from = await page.locator('[data-bit="11"]').boundingBox();
const to = await page.locator('[data-bit="8"]').boundingBox();
if (!from || !to) {
throw new Error('Bits are not visible');
}
await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2, { steps: 5 });
await page.mouse.up();
await expect(positions).toHaveValue('2, 8-11');
await page.locator('[data-bit="2"]').click();
await expect(positions).toHaveValue('8-11');
});
test('Clears all positions', async ({ page }) => {
await page.getByTestId('bit-positions').fill('2, 4-7');
await page.getByRole('button', { name: 'Clear all' }).click();
await expect(page.getByTestId('bit-positions')).toHaveValue('');
});
});
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import InputCopyable from '../../components/InputCopyable.vue';
import BitFields from './bit-fields.vue';
import { convertBase, hasNumberPrefix, formatWithSpaces } from './integer-base-converter.model';
import { getErrorMessageIfThrows } from '@/utils/error';
import { useQueryParam } from '@/composable/queryParams';
@@ -64,6 +65,15 @@ function formattedConvert(args: Parameters<typeof convertBase>[0]) {
}
}
// The input as a number, for the bit fields section (null while the input is invalid)
const inputValue = computed<bigint | null>(() => {
try {
return BigInt(convertBase({ value: input.value, fromBase: inputBase.value, toBase: 10 }));
} catch {
return null;
}
});
const error = computed(() =>
getErrorMessageIfThrows(() =>
convertBase({ value: input.value, fromBase: inputBase.value, toBase: outputBase.value }),
@@ -213,6 +223,9 @@ const error = computed(() =>
:placeholder="`Base ${outputBase} will be here...`"
/>
</div>
<n-divider />
<BitFields :value="inputValue" />
</c-card>
</div>
</template>
@@ -56,3 +56,66 @@ export function convertMacCanonicalIEEE(mac: string): string {
export function convertMacCISCO(mac: string): string {
return convertMac(mac.toLocaleLowerCase(), 4, '.');
}
/**
* Validates MAC/EUI addresses.
*
* Supported formats:
* - XX:XX:XX:XX:XX:XX
* - XX-XX-XX-XX-XX-XX
* - XXXX.XXXX.XXXX
* - XXXXXXXXXXXX
*
* - XX:XX:XX:XX:XX:XX:XX:XX
* - XX-XX-XX-XX-XX-XX-XX-XX
* - XXXX.XXXX.XXXX.XXXX
* - XXXXXXXXXXXXXXXX
*/
export function isValidMacAddress(value: string): boolean {
if (!value?.trim()) {
return false;
}
const mac = value.trim();
// Raw hex (12 or 16 chars)
if (/^[0-9A-Fa-f]{12}$/.test(mac)) {
return true;
}
if (/^[0-9A-Fa-f]{16}$/.test(mac)) {
return true;
}
// Colon-separated EUI-48
if (/^(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/.test(mac)) {
return true;
}
// Hyphen-separated EUI-48
if (/^(?:[0-9A-Fa-f]{2}-){5}[0-9A-Fa-f]{2}$/.test(mac)) {
return true;
}
// Colon-separated EUI-64
if (/^(?:[0-9A-Fa-f]{2}:){7}[0-9A-Fa-f]{2}$/.test(mac)) {
return true;
}
// Hyphen-separated EUI-64
if (/^(?:[0-9A-Fa-f]{2}-){7}[0-9A-Fa-f]{2}$/.test(mac)) {
return true;
}
// Cisco EUI-48
if (/^(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4}$/.test(mac)) {
return true;
}
// Cisco EUI-64
if (/^(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4}$/.test(mac)) {
return true;
}
return false;
}
@@ -11,6 +11,7 @@ import {
convertMacToEUI64CanonicalIETF,
convertMacToLinkLocalIPv6,
convertMacToNumber,
isValidMacAddress,
} from './mac-address-converter.service';
import { useQueryParam } from '@/composable/queryParams';
@@ -31,6 +32,17 @@ const convertMulti = (value: string, converter: (mac: string) => string): string
.join('\n');
};
const invalidMacAddresses = computed(() => {
const macs = input.value.split(/[\s,;]+/).filter((mac) => mac.trim() !== '');
return macs.filter((mac) => {
try {
return !isValidMacAddress(mac);
} catch (error) {
return true;
}
});
});
const formats = computed(() => [
{
label: t('tools.mac-address-converter.texts.label-canonical-ietf-format'),
@@ -112,6 +124,12 @@ const inputLabelAlignmentConfig = {
<div my-16px divider />
<c-alert v-if="invalidMacAddresses.length > 0" type="error" mb-5>
<div v-for="mac in invalidMacAddresses" :key="mac">
{{ t('tools.mac-address-converter.texts.error-invalid-mac-address', [mac]) }}
</div>
</c-alert>
<InputCopyable
v-for="format in formats"
:key="format.label"
@@ -5,6 +5,10 @@ import { useCopy } from '@/composable/copy';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { computedRefreshable } from '@/composable/computedRefreshable';
import { zxcvbn, zxcvbnOptions } from '@zxcvbn-ts/core';
import * as zxcvbnCommonPackage from '@zxcvbn-ts/language-common';
import * as zxcvbnEnPackage from '@zxcvbn-ts/language-en';
const { t } = useI18n();
const count = useQueryParamOrStorage({ name: 'count', storageName: 'pass-generator:count', defaultValue: 1 });
@@ -43,6 +47,43 @@ const [passphrases, refreshPassphrases] = computedRefreshable(() =>
}).join('\n'),
);
const options = {
dictionary: {
...zxcvbnCommonPackage.dictionary,
...zxcvbnEnPackage.dictionary,
},
graphs: zxcvbnCommonPackage.adjacencyGraphs,
translations: zxcvbnEnPackage.translations,
};
zxcvbnOptions.setOptions(options);
const passphrasesStrength = computed(() => {
return passphrases.value
.split('\n')
.filter((passphrase) => !passphrase.match(/^#/))
.map((passphrase) => {
const result = zxcvbn(passphrase);
const score = result.score;
const labels = [
t('tools.passphrase-generator.texts.very-weak'),
t('tools.passphrase-generator.texts.weak'),
t('tools.passphrase-generator.texts.fair'),
t('tools.passphrase-generator.texts.strong'),
t('tools.passphrase-generator.texts.very-strong'),
];
const statuses = ['error', 'warning', 'info', 'success', 'success'] as const;
const percent = (score / 4) * 100;
const colorMap = ['#d32f2f', '#f57c00', '#fbc02d', '#388e3c', '#2e7d32'];
return {
passphrase,
percent,
label: labels[score],
status: statuses[score],
color: colorMap[score],
};
});
});
const { copy } = useCopy({
source: passphrases,
text: t('tools.passphrase-generator.texts.text-passphrase-s-copied-to-clipboard'),
@@ -51,6 +92,12 @@ const { copy } = useCopy({
<template>
<div>
<n-space justify="center" mb-3>
<c-link target="_blank" to="/token-generator">
{{ t('tools.passphrase-generator.texts.link-to-token-generator') }}
</c-link>
</n-space>
<c-card>
<n-space>
<n-form-item :label="t('tools.passphrase-generator.texts.words-words', [words])" label-placement="left">
@@ -120,6 +167,30 @@ const { copy } = useCopy({
{{ t('tools.passphrase-generator.texts.tag-refresh') }}
</c-button>
</div>
<n-table v-if="passphrasesStrength.length" mt-3>
<thead>
<tr>
<th>{{ t('tools.passphrase-generator.texts.tag-passphrase') }}</th>
<th>{{ t('tools.passphrase-generator.texts.tag-strength') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in passphrasesStrength" :key="row.passphrase">
<td>{{ row.passphrase }}</td>
<td>
<n-progress
:percentage="row.percent"
:color="row.color"
:status="row.status"
indicator-placement="inside"
>
{{ row.percent }}% - {{ row.label }}
</n-progress>
</td>
</tr>
</tbody>
</n-table>
</c-card>
</div>
</template>
@@ -39,29 +39,39 @@ function calculateStuff() {
try {
if (options.time && options.length && options.pace) {
throw new Error('Only two of "time", "length" and "pace" may be provided at any time');
throw new Error(
t('tools.running-pace-calculator.texts.only-two-of-time-length-and-pace-may-be-provided-at-any-time'),
);
} else if (options.time && options.pace) {
if (options.speed) {
throw new Error('Speed is only valid when (only) pace is given or calculated');
throw new Error(
t('tools.running-pace-calculator.texts.speed-is-only-valid-when-only-pace-is-given-or-calculated'),
);
}
resultType.value = 'Length';
resultType.value = t('tools.token-generator.length');
result.value = `${runPace.calculateLength(options)}`;
} else if (options.time && options.length) {
const label = options.speed ? 'Speed' : 'Pace';
const label = options.speed
? t('tools.running-pace-calculator.texts.speed')
: t('tools.running-pace-calculator.texts.pace');
resultType.value = label;
result.value = `${runPace.calculatePace(options)}`;
} else if (options.pace && options.length) {
if (options.speed) {
throw new Error('Speed is only valid when (only) pace is given or calculated');
throw new Error(
t('tools.running-pace-calculator.texts.speed-is-only-valid-when-only-pace-is-given-or-calculated-0'),
);
}
resultType.value = 'Time';
resultType.value = t('tools.ttl-calculator.texts.label-time');
result.value = `${runPace.calculateTime(options)}`;
} else if (options.pace && options.speed) {
resultType.value = 'Speed';
resultType.value = t('tools.running-pace-calculator.texts.speed-0');
result.value = `${runPace.paceToSpeed(options)}`;
} else {
throw new Error(
'Two of "time", "length" and "pace" must be provided.\nSpeed is only valid when pace is given or calculated.',
t(
'tools.running-pace-calculator.texts.two-of-time-length-and-pace-must-be-provided-nspeed-is-only-valid-when-pace-is-given-or-calculated',
),
);
}
} catch (e: any) {
@@ -73,6 +83,25 @@ function calculateStuff() {
<template>
<div>
<NForm label-placement="left" label-width="70px">
<NFormItem label="Presets:">
<n-space>
<NButton size="small" @click="length = '100m'">100m</NButton>
<NButton size="small" @click="length = '200m'">200m</NButton>
<NButton size="small" @click="length = '400m'">400m</NButton>
<NButton size="small" @click="length = '800m'">800m</NButton>
<NButton size="small" @click="length = '1km'">1km</NButton>
<NButton size="small" @click="length = '5km'">5km</NButton>
<NButton size="small" @click="length = '10km'">10km</NButton>
<NButton size="small" @click="length = '21.0975km'">{{
$t('tools.running-pace-calculator.texts.half-marathon')
}}</NButton>
<NButton size="small" @click="length = '42.195km'">{{
$t('tools.running-pace-calculator.texts.marathon')
}}</NButton>
<NButton size="small" @click="length = '50km'">50km</NButton>
</n-space>
</NFormItem>
<NFormItem :label="t('tools.running-pace-calculator.texts.label-length')">
<NInput
v-model:value="length"
@@ -124,7 +153,11 @@ function calculateStuff() {
</c-alert>
<c-card v-if="result" :title="t('tools.running-pace-calculator.texts.title-result')">
<input-copyable :label="`${resultType}:`" label-position="left" :value="result" />
<input-copyable
:label="$t('tools.running-pace-calculator.texts.resulttype', [resultType])"
label-position="left"
:value="result"
/>
</c-card>
</div>
</template>
+13
View File
@@ -0,0 +1,13 @@
import { translate as t } from '@/plugins/i18n.plugin';
import { defineTool } from '../tool';
export const tool = defineTool({
name: t('tools.running-planner.title'),
path: '/running-planner',
description: t('tools.running-planner.description'),
keywords: ['running', 'pace', 'marathon', 'planner'],
component: () => import('./running-planner.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Run')),
createdAt: new Date('2026-11-29'),
category: 'Data',
});
@@ -0,0 +1,366 @@
<template>
<div>
<n-grid :cols="24" :x-gap="16">
<n-grid-item :span="6">
<n-form-item :label="t('tools.running-planner.texts.label-unit')" label-placement="left">
<n-select v-model:value="unit" :options="unitOptions" />
</n-form-item>
</n-grid-item>
<n-grid-item :span="10">
<n-form-item :label="t('tools.running-planner.texts.label-race')" label-placement="left">
<n-select :value="selectedRace" :options="raceOptions" clearable @update:value="onRaceSelect" />
</n-form-item>
</n-grid-item>
<n-grid-item :span="8">
<n-form-item :label="$t('tools.running-planner.texts.distance-unit', [unit])" label-placement="left">
<n-input-number v-model:value="distance" :min="1" :max="100" :step="0.1" style="width: 100%" />
</n-form-item>
</n-grid-item>
</n-grid>
<n-grid :cols="24" :x-gap="16">
<n-grid-item :span="12">
<n-form-item :label="$t('tools.running-planner.texts.pace-unitlabel', [unitLabel])" label-placement="left">
<n-grid :cols="2" :x-gap="8">
<n-grid-item>
<n-input-number
v-model:value="paceMinutes"
:placeholder="t('tools.running-planner.texts.placeholder-minutes')"
:min="0"
:max="30"
style="width: 100%"
/>
</n-grid-item>
<n-grid-item>
<n-input-number
v-model:value="paceSeconds"
:placeholder="t('tools.running-planner.texts.placeholder-seconds')"
:min="0"
:max="59"
style="width: 100%"
/>
</n-grid-item>
</n-grid>
</n-form-item>
</n-grid-item>
<n-grid-item :span="12">
<n-form-item :label="t('tools.running-planner.texts.label-checkpoints')" label-placement="left">
<n-select v-model:value="splitInterval" :options="intervalOptions" />
</n-form-item>
</n-grid-item>
</n-grid>
<n-space justify="center" mb-3>
<n-button v-for="race in racePresets" :key="race.value" secondary @click="applyRace(race)">
{{ race.label }}
</n-button>
</n-space>
<n-card>
<n-grid :cols="2">
<n-grid-item>
<n-statistic :label="t('tools.running-planner.texts.label-race')" :value="distanceName" />
</n-grid-item>
<n-grid-item>
<n-statistic
:label="t('tools.running-planner.texts.label-estimated-finish-time')"
:value="estimatedFinishTime"
/>
</n-grid-item>
</n-grid>
</n-card>
<n-card :title="t('tools.running-planner.texts.title-projected-checkpoints')">
<n-data-table :columns="columns" :data="rows" :pagination="{ pageSize: 20 }" :bordered="false" />
</n-card>
</div>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
import { computed, h, ref } from 'vue';
import { NTag, type DataTableColumns } from 'naive-ui';
type Unit = 'km' | 'mi';
const KM_PER_MILE = 1.609344;
const unit = ref<Unit>('km');
const paceMinutes = ref(5);
const paceSeconds = ref(0);
const distance = ref(42.195);
const splitInterval = ref(5);
const selectedRace = ref<string | null>('marathon');
const unitOptions = [
{
label: t('tools.running-planner.texts.label-kilometers'),
value: 'km',
},
{
label: t('tools.running-planner.texts.label-miles'),
value: 'mi',
},
];
const racePresets = [
{
label: t('tools.running-planner.texts.label-5k'),
value: '5k',
distanceKm: 5,
},
{
label: t('tools.running-planner.texts.label-10k'),
value: '10k',
distanceKm: 10,
},
{
label: t('tools.running-planner.texts.label-15k'),
value: '15k',
distanceKm: 15,
},
{
label: t('tools.running-planner.texts.label-10-mile'),
value: '10mile',
distanceKm: 16.09344,
},
{
label: t('tools.running-planner.texts.label-20k'),
value: '20k',
distanceKm: 20,
},
{
label: t('tools.running-planner.texts.label-half-marathon'),
value: 'half',
distanceKm: 21.0975,
},
{
label: t('tools.running-planner.texts.label-25k'),
value: '25k',
distanceKm: 25,
},
{
label: t('tools.running-planner.texts.label-30k'),
value: '30k',
distanceKm: 30,
},
{
label: t('tools.running-planner.texts.label-marathon'),
value: 'marathon',
distanceKm: 42.195,
},
{
label: t('tools.running-planner.texts.label-50k-ultra'),
value: '50k',
distanceKm: 50,
},
];
const raceOptions = racePresets.map((r) => ({
label: r.label,
value: r.value,
}));
const unitLabel = computed(() => (unit.value === 'km' ? 'min/km' : 'min/mi'));
function kmToMiles(km: number) {
return km / KM_PER_MILE;
}
function milesToKm(mi: number) {
return mi * KM_PER_MILE;
}
function formatDuration(totalSeconds: number) {
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = Math.round(totalSeconds % 60);
return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}
function paceToLabel(seconds: number) {
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m}:${String(s).padStart(2, '0')}/${unit.value}`;
}
function applyRace(race: (typeof racePresets)[number]) {
selectedRace.value = race.value;
distance.value = unit.value === 'km' ? race.distanceKm : kmToMiles(race.distanceKm);
}
function onRaceSelect(value: string | null) {
if (!value) {
return;
}
const found = racePresets.find((r) => r.value === value);
if (found) {
applyRace(found);
}
}
const intervalOptions = computed(() => {
return unit.value === 'km'
? [
{
label: t('tools.running-planner.texts.label-every-1-km'),
value: 1,
},
{
label: t('tools.running-planner.texts.label-every-2-km'),
value: 2,
},
{
label: t('tools.running-planner.texts.label-every-5-km'),
value: 5,
},
{
label: t('tools.running-planner.texts.label-every-10-km'),
value: 10,
},
]
: [
{
label: t('tools.running-planner.texts.label-every-1-mile'),
value: 1,
},
{
label: t('tools.running-planner.texts.label-every-2-miles'),
value: 2,
},
{
label: t('tools.running-planner.texts.label-every-5-miles'),
value: 5,
},
];
});
const paceInSeconds = computed(() => paceMinutes.value * 60 + paceSeconds.value);
const distanceName = computed(() => {
const currentKm = unit.value === 'km' ? distance.value : milesToKm(distance.value);
const found = racePresets.find((race) => Math.abs(race.distanceKm - currentKm) < 0.1);
return found?.label ?? t('tools.running-planner.texts.custom-distance');
});
const paceVariants = computed(() => [
{
key: 'minus60',
title: '-1:00',
seconds: Math.max(60, paceInSeconds.value - 60),
},
{
key: 'minus30',
title: '-0:30',
seconds: Math.max(60, paceInSeconds.value - 30),
},
{
key: 'target',
title: t('tools.running-planner.texts.target'),
seconds: paceInSeconds.value,
},
{
key: 'plus30',
title: '+0:30',
seconds: paceInSeconds.value + 30,
},
{
key: 'plus60',
title: '+1:00',
seconds: paceInSeconds.value + 60,
},
]);
const estimatedFinishTime = computed(() => formatDuration(distance.value * paceInSeconds.value));
const rows = computed(() => {
const data: Record<string, any>[] = [];
let current = splitInterval.value;
while (current < distance.value) {
const row: Record<string, any> = {
distance: current,
finish: false,
};
paceVariants.value.forEach((variant) => {
row[variant.key] = formatDuration(current * variant.seconds);
});
data.push(row);
current += splitInterval.value;
}
const finishRow: Record<string, any> = {
distance: distance.value,
finish: true,
};
paceVariants.value.forEach((variant) => {
finishRow[variant.key] = formatDuration(distance.value * variant.seconds);
});
data.push(finishRow);
return data;
});
const columns = computed<DataTableColumns<any>>(() => {
const result: DataTableColumns<any> = [
{
title: t('tools.running-planner.texts.distance-unit-value', [unit.value]),
key: 'distance',
width: 160,
fixed: 'left',
render(row) {
if (row.finish) {
return h(
NTag,
{
type: 'success',
},
{
default: () => `${row.distance.toFixed(2)} ${unit.value}`,
},
);
}
return `${row.distance.toFixed(1)} ${unit.value}`;
},
},
];
paceVariants.value.forEach((variant) => {
result.push({
title:
variant.title === t('tools.running-planner.texts.target-0')
? paceToLabel(variant.seconds)
: `${variant.title} (${paceToLabel(variant.seconds)})`,
key: variant.key,
});
});
return result;
});
</script>
+13
View File
@@ -0,0 +1,13 @@
import { translate as t } from '@/plugins/i18n.plugin';
import { defineTool } from '../tool';
export const tool = defineTool({
name: t('tools.ssh-key-converter.title'),
path: '/ssh-key-converter',
description: t('tools.ssh-key-converter.description'),
keywords: ['ssh', 'key', 'rfc4716', 'pkcs1', 'pem', 'pkcs8', 'converter'],
component: () => import('./ssh-key-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/ShieldChevron')),
createdAt: new Date('2026-11-29'),
category: 'Crypto',
});
@@ -0,0 +1,147 @@
import { describe, expect, it } from 'vitest';
import { detectFormat, openSSHToRFC4716, rfc4716ToOpenSSH } from './ssh-key-converter.service';
const OPENSSH_ED25519 = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMaABCDEFGHIJKLMNopqrstuvwxyz1234567890 test@example.com';
describe('detectFormat', () => {
it('detects openssh rsa key', () => {
expect(detectFormat('ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC')).toBe('ssh');
});
it('detects openssh ed25519 key', () => {
expect(detectFormat(OPENSSH_ED25519)).toBe('ssh');
});
it('detects ecdsa key', () => {
expect(detectFormat('ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTY=')).toBe('ssh');
});
it('detects rfc4716 key', () => {
expect(
detectFormat(`
---- BEGIN SSH2 PUBLIC KEY ----
AAAA
---- END SSH2 PUBLIC KEY ----
`),
).toBe('rfc4716');
});
it('detects pem public key', () => {
expect(
detectFormat(`
-----BEGIN PUBLIC KEY-----
AAAA
-----END PUBLIC KEY-----
`),
).toBe('pem');
});
it('detects rsa pem public key', () => {
expect(
detectFormat(`
-----BEGIN RSA PUBLIC KEY-----
AAAA
-----END RSA PUBLIC KEY-----
`),
).toBe('pem');
});
it('detects pkcs8 private key', () => {
expect(
detectFormat(`
-----BEGIN PRIVATE KEY-----
AAAA
-----END PRIVATE KEY-----
`),
).toBe('pkcs8');
});
it('throws for unknown format', () => {
expect(() => detectFormat('this is not a key')).toThrow('Cannot detect key format');
});
});
describe('openSSHToRFC4716', () => {
it('creates valid rfc4716 envelope', () => {
const result = openSSHToRFC4716(OPENSSH_ED25519);
expect(result).toContain('BEGIN SSH2 PUBLIC KEY');
expect(result).toContain('END SSH2 PUBLIC KEY');
expect(result).toContain('Comment: "test@example.com"');
expect(result).toContain('AAAAC3NzaC1lZDI1NTE5');
});
it('supports commentless keys', () => {
const result = openSSHToRFC4716('ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC');
expect(result).not.toContain('Comment:');
});
it('throws for malformed openssh input', () => {
expect(() => openSSHToRFC4716('not-a-key')).toThrow('Invalid OpenSSH key');
});
it('wraps long base64 content', () => {
const longBase64 = 'A'.repeat(200);
const result = openSSHToRFC4716(`ssh-rsa ${longBase64}`);
const lines = result.split('\n');
const payloadLines = lines.filter((line) => !line.startsWith('----') && !line.startsWith('Comment:'));
expect(payloadLines.some((line) => line.length <= 72)).toBe(true);
});
});
describe('rfc4716ToOpenSSH', () => {
it('converts rfc4716 to openssh', () => {
const blob = 'AAAAC3NzaC1lZDI1NTE5AAAAIMaABCDEFGHIJKLMNopqrstuvwxyz1234567890';
const rfc = `
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "user@test"
${blob}
---- END SSH2 PUBLIC KEY ----
`;
const result = rfc4716ToOpenSSH(rfc);
expect(result.startsWith('ssh-ed25519 ')).toBe(true);
expect(result.endsWith(blob)).toBe(true);
});
it('ignores comments', () => {
const blob = 'AAAAC3NzaC1lZDI1NTE5AAAAIMaABCDEFGHIJKLMNopqrstuvwxyz1234567890';
const result = rfc4716ToOpenSSH(`
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "one"
Comment: "two"
${blob}
---- END SSH2 PUBLIC KEY ----
`);
expect(result.startsWith('ssh-ed25519 ')).toBe(true);
});
});
describe('round trip conversions', () => {
it('preserves payload through openssh->rfc4716 conversion', () => {
const openssh = OPENSSH_ED25519;
const rfc = openSSHToRFC4716(openssh);
const payload = rfc
.split('\n')
.filter((line) => !line.startsWith('----') && !line.startsWith('Comment:'))
.join('');
expect(payload).toBe(openssh.split(' ')[1]);
});
});
@@ -0,0 +1,66 @@
export type KeyFormat = 'auto' | 'ssh' | 'rfc4716' | 'pem' | 'pkcs8';
export function detectFormat(key: string): KeyFormat {
const text = key.trim();
if (text.includes('BEGIN SSH2 PUBLIC KEY')) {
return 'rfc4716';
}
if (text.startsWith('ssh-rsa') || text.startsWith('ssh-ed25519') || text.startsWith('ecdsa-sha2-')) {
return 'ssh';
}
if (text.includes('BEGIN PUBLIC KEY') || text.includes('BEGIN RSA PUBLIC KEY')) {
return 'pem';
}
if (text.includes('BEGIN PRIVATE KEY')) {
return 'pkcs8';
}
throw new Error('Cannot detect key format');
}
export function rfc4716ToOpenSSH(rfc: string): string {
const lines = rfc
.split(/\r?\n/)
.map((x) => x.trim())
.filter(Boolean);
const payload = lines.filter((line) => !line.startsWith('----') && !line.startsWith('Comment:')).join('');
const blob = Buffer.from(payload, 'base64');
const typeLength = blob.readUInt32BE(0);
const type = blob.subarray(4, 4 + typeLength).toString();
return `${type} ${payload}`;
}
export function openSSHToRFC4716(openssh: string): string {
const parts = openssh.trim().split(/\s+/);
if (parts.length < 2) {
throw new Error('Invalid OpenSSH key');
}
const comment = parts.slice(2).join(' ');
const base64 = parts[1];
const output: string[] = ['---- BEGIN SSH2 PUBLIC KEY ----'];
if (comment) {
output.push(`Comment: "${comment}"`);
}
for (let i = 0; i < base64.length; i += 72) {
output.push(base64.slice(i, i + 72));
}
output.push('---- END SSH2 PUBLIC KEY ----');
return output.join('\n');
}
@@ -0,0 +1,109 @@
<template>
<div>
<n-grid :cols="2" :x-gap="12">
<n-gi>
<n-form-item :label="t('tools.ssh-key-converter.texts.label-source-format')">
<n-select v-model:value="sourceFormat" :options="sourceOptions" />
</n-form-item>
</n-gi>
<n-gi>
<n-form-item :label="t('tools.ssh-key-converter.texts.label-target-format')">
<n-select v-model:value="targetFormat" :options="targetOptions" />
</n-form-item>
</n-gi>
</n-grid>
<n-form-item :label="t('tools.ssh-key-converter.texts.label-input-key')" label-placement="top">
<n-input
v-model:value="inputKey"
type="textarea"
:rows="12"
:placeholder="t('tools.ssh-key-converter.texts.placeholder-paste-ssh-key-here')"
/>
</n-form-item>
<n-alert v-if="error" type="error">
{{ error }}
</n-alert>
<n-card v-if="outputKey" :title="t('tools.ssh-key-converter.texts.title-output-key')" type="info" size="small" mb-1>
<textarea-copyable :value="outputKey" readonly />
</n-card>
</div>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
import sshpk from 'sshpk';
import { detectFormat, openSSHToRFC4716, rfc4716ToOpenSSH, type KeyFormat } from './ssh-key-converter.service';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const inputKey = ref('');
const error = ref('');
const sourceFormat = ref<KeyFormat>('auto');
const targetFormat = useQueryParamOrStorage<KeyFormat>({
name: 'fmt',
storageName: 'ssh-key-conv:fmt',
defaultValue: 'rfc4716',
});
const sourceOptions = [
{ label: t('tools.ssh-key-converter.texts.label-auto-detect'), value: 'auto' },
{ label: t('tools.ssh-key-converter.texts.label-openssh'), value: 'ssh' },
{ label: t('tools.ssh-key-converter.texts.label-rfc4716'), value: 'rfc4716' },
{ label: t('tools.ssh-key-converter.texts.label-pem'), value: 'pem' },
{ label: t('tools.ssh-key-converter.texts.label-pkcs8'), value: 'pkcs8' },
];
const targetOptions = [
{ label: t('tools.ssh-key-converter.texts.label-openssh'), value: 'ssh' },
{ label: t('tools.ssh-key-converter.texts.label-rfc4716'), value: 'rfc4716' },
{ label: t('tools.ssh-key-converter.texts.label-pem'), value: 'pem' },
{ label: t('tools.ssh-key-converter.texts.label-pkcs8'), value: 'pkcs8' },
];
function parseKey(key: string, format: KeyFormat) {
try {
return sshpk.parseKey(key, format as any);
} catch {
return sshpk.parsePrivateKey(key, format as any);
}
}
const outputKey = computed(() => {
error.value = '';
try {
const actualFormat = sourceFormat.value === 'auto' ? detectFormat(inputKey.value) : sourceFormat.value;
let normalized = inputKey.value;
if (actualFormat === 'rfc4716') {
normalized = rfc4716ToOpenSSH(inputKey.value);
}
if (targetFormat.value === 'rfc4716') {
let openssh: string;
if (actualFormat === 'rfc4716') {
openssh = rfc4716ToOpenSSH(inputKey.value);
} else {
const key = parseKey(normalized, actualFormat);
openssh = key.toString('ssh');
}
return openSSHToRFC4716(openssh);
}
const key = parseKey(normalized, actualFormat === 'rfc4716' ? 'ssh' : actualFormat);
return key.toString(targetFormat.value as any);
} catch (e: any) {
error.value = e.toString();
}
});
</script>
@@ -4,6 +4,10 @@ import { useCopy } from '@/composable/copy';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { computedRefreshable } from '@/composable/computedRefreshable';
import { zxcvbn, zxcvbnOptions } from '@zxcvbn-ts/core';
import * as zxcvbnCommonPackage from '@zxcvbn-ts/language-common';
import * as zxcvbnEnPackage from '@zxcvbn-ts/language-en';
const count = useQueryParamOrStorage({ name: 'count', storageName: 'token-generator:count', defaultValue: 1 });
const length = useQueryParamOrStorage({ name: 'length', storageName: 'token-generator:length', defaultValue: 64 });
const withUppercase = useQueryParamOrStorage({
@@ -48,11 +52,51 @@ const [tokens, refreshTokens] = computedRefreshable(() =>
).join('\n'),
);
const options = {
dictionary: {
...zxcvbnCommonPackage.dictionary,
...zxcvbnEnPackage.dictionary,
},
graphs: zxcvbnCommonPackage.adjacencyGraphs,
translations: zxcvbnEnPackage.translations,
};
zxcvbnOptions.setOptions(options);
const tokensStrength = computed(() => {
return tokens.value.split('\n').map((token) => {
const result = zxcvbn(token);
const score = result.score;
const labels = [
t('tools.token-generator.tool.texts.very-weak'),
t('tools.token-generator.tool.texts.weak'),
t('tools.token-generator.tool.texts.fair'),
t('tools.token-generator.tool.texts.strong'),
t('tools.token-generator.tool.texts.very-strong'),
];
const statuses = ['error', 'warning', 'info', 'success', 'success'] as const;
const percent = (score / 4) * 100;
const colorMap = ['#d32f2f', '#f57c00', '#fbc02d', '#388e3c', '#2e7d32'];
return {
token,
percent,
label: labels[score],
status: statuses[score],
color: colorMap[score],
};
});
});
const { copy } = useCopy({ source: tokens, text: t('tools.token-generator.copied') });
</script>
<template>
<div>
<n-space justify="center" mb-3>
<c-link target="_blank" to="/passphrase-generator">
{{ t('tools.passphrase-generator.texts.link-to-passphase-generator') }}
</c-link>
</n-space>
<c-card>
<n-form label-placement="left" label-width="140">
<n-space justify="center">
@@ -116,6 +160,30 @@ const { copy } = useCopy({ source: tokens, text: t('tools.token-generator.copied
{{ t('tools.token-generator.button.refresh') }}
</c-button>
</div>
<n-table v-if="tokensStrength.length" mt-3>
<thead>
<tr>
<th>{{ t('tools.token-generator.texts.tag-token') }}</th>
<th>{{ t('tools.token-generator.texts.tag-strength') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in tokensStrength" :key="row.token">
<td>{{ row.token }}</td>
<td>
<n-progress
:percentage="row.percent"
:color="row.color"
:status="row.status"
indicator-placement="inside"
>
{{ row.percent }}% - {{ row.label }}
</n-progress>
</td>
</tr>
</tbody>
</n-table>
</c-card>
</div>
</template>