All files / lib i18n.js

74.28% Statements 26/35
63.26% Branches 31/49
62.5% Functions 5/8
72.72% Lines 24/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191                                                      10x     10x   10x 3x       10x                                               8x   8x   8x 5x     8x                                               8x   8x   8x 5x 5x   5x 1x       8x 1x     8x                                                 30x 30x                 5x 4x                                                                                        
/**
 * @typedef {import('$lib/database').Settings['language']} Language
 */
 
/**
 * Pluralizes a string based on a number and a list of candidate strings.
 * @see https://wuchale.dev/guides/plurals/#usage
 * @param {number} num
 * @param {string[]} candidates
 * @param {(n: number) => number} [rule]
 * @returns {string}
 */
export function plural(num, candidates, rule = (n) => (n === 1 ? 0 : 1)) {
	const index = rule(num);
	return candidates[index]?.replace('#', Intl.NumberFormat().format(num));
}
 
/**
 * Converts a number between 0 and 1 to a percentage string.
 * @param {number} value Number between 0 and 1
 * @param {number} [decimals=0] Number of decimal places to include in the output
 * @param {object} [options] Additional options
 * @param {'none'|'nbsp'|'zeros'} [options.pad=none] Whether to pad the percentage with leading non-breaking spaces
 * @param {number} [options.length] Total length of the resulting string (including % sign); if not specified, this is calculated based on decimals and the eventual padding. only relevant when pad is not 'none'.
 * @returns {`${number}%`} Percentage string
 */
export function percent(value, decimals = 0, { pad = 'none', length } = {}) {
	let result = (value * 100).toFixed(decimals);
 
	// Remove trailing zeros and decimal point if not needed
	if (decimals > 0) result = result.replace(/\.?0+$/, '');
 
	if (pad !== 'none') {
		result = result.padStart(length ?? 2 + decimals, pad === 'nbsp' ? '\u00A0' : '0');
	}
 
	// @ts-expect-error
	return result + '%';
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('percent', () => {
		expect.soft(percent(0.5)).toBe('50%');
		expect.soft(percent(0.123)).toBe('12%');
		expect.soft(percent(0.123, 1)).toBe('12.3%');
		expect.soft(percent(0.123, 2)).toBe('12.3%'); // trailing zeros removed
		expect.soft(percent(0.1234, 2)).toBe('12.34%');
		expect.soft(percent(1)).toBe('100%');
		expect.soft(percent(0)).toBe('0%');
		expect.soft(percent(0.05, 1, { pad: 'zeros' })).toBe('005%'); // 5.0 -> 5 -> 005
		expect.soft(percent(0.05, 0, { pad: 'nbsp' })).toBe('\u00A05%');
		expect.soft(percent(0.005, 2, { pad: 'nbsp' })).toBe('\u00A00.5%');
	});
}
 
/**
 * Returns a human-readable name for a content type.
 * @param {string} contentType Content type, of the form type/subtype
 */
export function humanFormatName(contentType) {
	const [supertype, subtype] = contentType.split('/', 2);
 
	let result = subtype.replace(/^x-/, '');
 
	if (['image', 'video', 'audio'].includes(supertype)) {
		result = result.toUpperCase();
	}
 
	return result;
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('humanFormatName', () => {
		expect(humanFormatName('image/jpeg')).toBe('JPEG');
		expect(humanFormatName('image/png')).toBe('PNG');
		expect(humanFormatName('video/mp4')).toBe('MP4');
		expect(humanFormatName('audio/mpeg')).toBe('MPEG');
		expect(humanFormatName('application/json')).toBe('json');
		expect(humanFormatName('text/plain')).toBe('plain');
		expect(humanFormatName('image/x-icon')).toBe('ICON');
		expect(humanFormatName('application/x-zip-compressed')).toBe('zip-compressed');
	});
}
 
/**
 *
 * @param {unknown} error
 * @param {string} [prefix]
 * @returns {string}
 */
export function errorMessage(error, prefix = '') {
	const defaultMessage = 'Erreur inattendue';
 
	let result = error?.toString() || defaultMessage;
 
	if (error instanceof Error) {
		Eif ('message' in error && error.message) {
			result = error.message || defaultMessage;
		}
		if ('cause' in error && error.cause) {
			result = errorMessage(error.cause);
		}
	}
 
	while (result.startsWith('Error: ')) {
		result = result.slice('Error: '.length);
	}
 
	return prefix ? `${prefix}: ${result}` : result;
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('errorMessage', async () => {
		expect(errorMessage(new Error('test error'))).toBe('test error');
		expect(errorMessage(new Error(/* @wc-ignore */ 'Error: test error'))).toBe('test error');
		expect(errorMessage('string error')).toBe('string error');
		expect(errorMessage(null)).toBe('Erreur inattendue');
		expect(errorMessage(undefined)).toBe('Erreur inattendue');
		expect(errorMessage(new Error('test'), 'prefix')).toBe('prefix: test');
 
		// The current implementation overwrites with toString(), so cause isn't used
		const errorWithCause = new Error('main error');
		errorWithCause.cause = new Error('cause error');
		expect(errorMessage(errorWithCause)).toBe('cause error');
	});
}
 
/**
 *
 * @returns {Language}
 */
export function localeFromNavigator() {
	const locale = navigator.language.split('-')[0];
	return locale === 'fr' ? 'fr' : 'en';
}
 
/**
 * Uppercase the first letter of a string
 * @param {string} str
 * @returns {string}
 */
export function uppercaseFirst(str) {
	if (!str) return str;
	return str.charAt(0).toUpperCase() + str.slice(1);
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
 
	test('uppercaseFirst', () => {
		expect(uppercaseFirst('hello')).toBe('Hello');
		expect(uppercaseFirst('Hello')).toBe('Hello');
		expect(uppercaseFirst('')).toBe('');
		expect(uppercaseFirst('a')).toBe('A');
		expect(uppercaseFirst('école')).toBe('École');
	});
}
 
/**
 *
 * @param {number} bytes byte count
 * @returns {string} formatted size
 */
export function formatBytesSize(bytes) {
	// SI powers (so, in terms of powers of ten and not powers of two)
	const power = bytes < 1e3 ? 0 : bytes < 1e6 ? 1 : bytes < 1e9 ? 2 : bytes < 1e12 ? 3 : 4;
 
	const formatter = new Intl.NumberFormat(undefined, {
		style: 'unit',
		unitDisplay: 'narrow',
		unit: {
			0: 'byte',
			1: 'kilobyte',
			2: 'megabyte',
			3: 'gigabyte',
			4: 'terabyte'
		}[power]
	});
 
	const value = bytes / 2 ** (10 * power);
 
	const rounding = value > 10 ? 0 : value > 1 ? 1 : 2;
 
	const rounded = Math.round(value * 10 ** rounding) / 10 ** rounding;
 
	return formatter.format(rounded);
}