field-input-limits.js 4.89 KB
/** 数字输入长度限制 — @see packageDynamicForm/docs/ARCHITECTURE.md */
import { DEFAULT_NUMBER_INPUT_MAX_LENGTH } from '../config/formFieldLimits.js'

/** 解析 numberInput 字段的有效 maxLength(schema 与默认值取较小者) */
export function resolveNumberInputMaxLength(field = {}) {
	if (field.type !== 'numberInput') {
		return undefined
	}
	const schemaMax = field.rules?.maxLength
	if (schemaMax != null && schemaMax < DEFAULT_NUMBER_INPUT_MAX_LENGTH) {
		return schemaMax
	}
	return DEFAULT_NUMBER_INPUT_MAX_LENGTH
}

/** 将字符串截断至 maxLength */
export function truncateToMaxLength(value, maxLength) {
	if (value == null || maxLength == null) {
		return value ?? ''
	}
	const str = String(value)
	if (str.length <= maxLength) {
		return str
	}
	return str.slice(0, maxLength)
}

function normalizeNumberInputField(fieldOrRules = {}) {
	if (fieldOrRules.type) {
		return fieldOrRules
	}
	return { type: 'numberInput', rules: fieldOrRules }
}

/** rules.decimal === true 时走小数输入(金额等);min<0 时不启用 */
export function isNumberInputDecimalMode(fieldOrRules = {}) {
	const field = normalizeNumberInputField(fieldOrRules)
	if (field.type !== 'numberInput') {
		return false
	}
	const rules = field.rules || {}
	if (rules.min !== undefined && rules.min < 0) {
		return false
	}
	return !!rules.decimal
}

/** numberInput 默认非负整数;decimal 或 min<0 时除外 */
export function isNonNegativeIntegerInput(fieldOrRules = {}) {
	const field = normalizeNumberInputField(fieldOrRules)
	if (field.type !== 'numberInput') {
		return false
	}
	if (isNumberInputDecimalMode(field)) {
		return false
	}
	const min = field.rules?.min
	if (min !== undefined && min < 0) {
		return false
	}
	return true
}

/** 输入过程中过滤为仅数字 0-9,并截断 maxLength */
export function sanitizeNonNegativeIntegerInput(raw, field = {}) {
	const digitsOnly = String(raw ?? '').replace(/\D/g, '')
	const maxLength = resolveNumberInputMaxLength(field)
	return truncateToMaxLength(digitsOnly, maxLength)
}

/** 失焦时将展示串规范为无多余前导零("" 保持空) */
export function normalizeNonNegativeIntegerDisplay(displayStr = '') {
	if (displayStr === '') {
		return ''
	}
	const num = Number(displayStr)
	if (Number.isNaN(num)) {
		return ''
	}
	return String(num)
}

/** 非负整数展示串 → 写入 engine 的 value(空串或 number) */
export function coerceNonNegativeIntegerInputValue(displayStr = '') {
	if (displayStr === '') {
		return ''
	}
	const num = Number(displayStr)
	return Number.isNaN(num) ? '' : num
}

const MAX_DECIMAL_FRACTION_DIGITS = 2

/** rules.decimal === true 时走小数输入(与整数分支互斥) */
export function isDecimalInput(fieldOrRules = {}) {
	return isNumberInputDecimalMode(fieldOrRules)
}

/**
 * decimal 输入串规范化(对齐精品创建 createOrder + utils_format 前导零/孤立小数点逻辑)
 * @param {string} str
 * @param {{ trailingDot?: 'keep' | 'strip' }} options
 */
function normalizeDecimalInputString(str, { trailingDot = 'keep' } = {}) {
	if (str === '') {
		return ''
	}

	let s = str.replace(/[^\d.]/g, '')
	if (s === '') {
		return ''
	}

	const dotIndex = s.indexOf('.')
	if (dotIndex !== -1) {
		const intPart = s.slice(0, dotIndex).replace(/\./g, '')
		const fracPart = s.slice(dotIndex + 1).replace(/\./g, '')
		s = `${intPart}.${fracPart}`
	}

	// createOrder changePrice:去掉整数部分多余前导零
	if (s.length > 1 && s.startsWith('0') && s[1] !== '.') {
		s = s.replace(/^0+/, '')
		if (s === '') {
			s = '0'
		} else if (s.startsWith('.')) {
			s = `0${s}`
		}
	}

	// removeLeadingZerosAndEnsureNonNegative:00.5 → .5、0.5 前导零
	s = s.replace(/^0+(?=\d)|^0+(?=\.)/, '')

	if (s === '.') {
		s = '0.'
	} else if (s.startsWith('.')) {
		s = `0${s}`
	}

	const fracDot = s.indexOf('.')
	if (fracDot !== -1) {
		const intPart = s.slice(0, fracDot)
		const fracPart = s.slice(fracDot + 1).slice(0, MAX_DECIMAL_FRACTION_DIGITS)
		s = `${intPart}.${fracPart}`
	}

	if (trailingDot === 'strip' && s.endsWith('.')) {
		s = s.slice(0, -1)
	}

	return s
}

/** 输入过滤:仅数字与至多一个小数点,小数最多 2 位(对齐 validator) */
export function sanitizeDecimalInput(raw, field = {}) {
	const s = normalizeDecimalInputString(String(raw ?? ''), { trailingDot: 'keep' })
	return truncateToMaxLength(s, resolveNumberInputMaxLength(field))
}

/** 失焦:规范化展示串并去掉末尾孤立小数点("12." → "12","0." → "0") */
export function normalizeDecimalDisplay(displayStr = '') {
	if (displayStr === '') {
		return ''
	}
	return normalizeDecimalInputString(displayStr, { trailingDot: 'strip' })
}

/** 小数展示串 → 写入 engine 的 value(空串或 number) */
export function coerceDecimalInputValue(displayStr = '') {
	if (displayStr === '') {
		return ''
	}
	const num = Number(displayStr)
	return Number.isNaN(num) ? '' : num
}

export { DEFAULT_NUMBER_INPUT_MAX_LENGTH }