okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e5476b0e1
main
1/** 2* A number typed into a settings field (QA report F05: "Max output tokens" took -1 below its minimum of 0 and saved it). 3* The field keeps what the person typed, says in plain words what is wrong, and the save stays off until it is right. 4*/ 5export type NumberCheck = { ok :true ; value :number } | { ok :false ; problem :'empty' | 'range' }; 6 7/** A whole number between `min` and `max` (both included). Spaces around it are ignored; "1e3", "0.5" and "-" are not whole numbers. */ 8export function checkWholeNumber ( raw :string , min :number , max :number ) :NumberCheck { 9const text = String ( raw ?? '' ). trim (); 10if ( ! text ) return { ok :false , problem :'empty' }; 11if ( ! /^[+-]?\d+$ / . test ( text )) return { ok :false , problem :'range' }; 12const value = Number ( text ); 13if ( ! Number . isSafeInteger ( value ) || value < min || value > max ) return { ok :false , problem :'range' }; 14return { ok :true , value}; 15} 16 17/** The sentence under a field that does not hold a good number. `format` writes a number the way the person's language does. */ 18export function numberProblem ( check :NumberCheck , min :number , max :number , format :( n :number ) => string ) :{ text :string ; args :string [] } | null { 19if ( check . ok ) return null ; 20return check . problem === 'empty' ?{ text :'Enter a number.' , args :[] } :{ text :'Enter a whole number from {0} to {1}.' , args :[ format ( min ), format ( max )] }; 21}