UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

114 lines 3.16 kB
export function getDisplayValue({ value, placeholder, length }) { const fallback = (placeholder || '').padEnd(length, placeholder[0] || ' '); const visiblePlaceholder = fallback.slice(0, length); if (!value) { return visiblePlaceholder; } return `${value}${visiblePlaceholder.slice(value.length)}`.slice(0, length); } export function insertChar(value, char, position, { overwriteMode, maxLength }) { const chars = Array.from(value); if (overwriteMode === 'shift') { chars.splice(position, 0, char); } else { chars[position] = char; } return chars.join('').slice(0, maxLength); } export function removeChar(value, position) { if (position < 0 || position >= value.length) { return value; } const chars = Array.from(value); chars.splice(position, 1); return chars.join(''); } export function extractValidChars(value, mask) { const chars = Array.from(value); const output = []; for (let index = 0; index < chars.length && output.length < mask.length; index++) { const char = chars[index]; const maskRule = mask[output.length]; if (maskRule?.test(char)) { output.push(char); } } return output.join(''); } export function joinValues(values, delimiter) { const parts = Object.values(values).filter(Boolean); if (parts.length === 0) { return ''; } return parts.join(delimiter !== null && delimiter !== void 0 ? delimiter : ''); } export function distributeValueFromStart({ value, inputs, existingValues }) { const nextValues = { ...existingValues }; let remaining = value; inputs.forEach(({ id, mask }, index) => { if (index > 0) { remaining = remaining.replace(/^[./\-\s]+/, ''); } if (!remaining) { return; } const nextValue = extractValidChars(remaining, mask); nextValues[id] = nextValue; remaining = remaining.slice(Math.max(1, nextValue.length)); }); return nextValues; } export function insertCharIntoSection({ char, inputId, overwriteMode, valuesRef, inputs, caretPositionsRef, sectionSelectionModeRef, onChange, focusSection, setSectionCaret }) { var _valuesRef$current$in, _caretPositionsRef$cu; const mask = inputs.find(({ id }) => id === inputId)?.mask; if (!mask) { return false; } const currentValue = (_valuesRef$current$in = valuesRef.current[inputId]) !== null && _valuesRef$current$in !== void 0 ? _valuesRef$current$in : ''; const isAllSelected = sectionSelectionModeRef.current[inputId] === 'all'; const currentPosition = isAllSelected ? 0 : (_caretPositionsRef$cu = caretPositionsRef.current[inputId]) !== null && _caretPositionsRef$cu !== void 0 ? _caretPositionsRef$cu : 0; if (!mask[Math.min(currentPosition, mask.length - 1)]?.test(char)) { return false; } const nextValue = insertChar(isAllSelected ? '' : currentValue, char, currentPosition, { overwriteMode, maxLength: mask.length }); onChange(inputId, nextValue); if (nextValue.length >= mask.length) { focusSection(inputId, 'end'); } else { setSectionCaret(inputId, nextValue.length); } return true; } //# sourceMappingURL=utils.js.map