Scoop API

scoop:scoop.ui.component:0.1.0

src/otp/policy.scoop

Selected production source · src/otp/policy.scoop

1package scoop.ui.component
3import scoop.ui.text.*
4import scoop.window.Utf8Range
6internal fun otpPolicy(pattern: InputOtpPattern, length: Long): TextEditPolicy {
7 return when (pattern) {
8 case Custom(val policy) -> policy.copy {
9 this.singleLine = true
10 val limit = this.maxLength ?: length
11 this.maxLength =
12 Some(
13 if (limit < length)
14 limit
15 else
16 length
17 )
18 }
19 else -> textEditPolicy {
20 this.singleLine = true
21 this.maxLength = Some(length)
22 paste { candidate -> otpPaste(candidate) }
23 acceptsInsertedText { text -> otpAccepts(text, pattern) }
24 }
25 }
28private fun otpAccepts(text: String, pattern: InputOtpPattern): Boolean {
29 val letters =
30 when (pattern) {
31 case Alphanumeric -> true;
32 else -> false
33 }
34 for (character in text) {
35 val code = character.code
36 if (
37 !(code >= 48 && code <= 57) &&
38 !(letters && ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)))
39 )
40 return false
41 }
42 return true
45private fun otpPaste(candidate: TextEditCandidate): TextEditDecision {
46 val changes = ArrayList<TextEditReplacement>()
47 var offset = 0L
48 for (character in candidate.after.text) {
49 val code = character.code
50 if (code == 45 || code == 32 || (code >= 9 && code <= 13)) {
51 for (range in candidate.insertedRanges)
52 if (offset >= range.start && offset < range.end) {
53 changes.add(TextEditReplacement(Utf8Range(offset, offset + 1L), ""))
54 break
55 }
56 }
57 offset += character.toString().byteLength
58 }
59 return TextEditDecision.Transform(changes.toArray())