Skip to content

Commit

Permalink
Major refactor for ExtensionsInput.FilterRange(...) #77
Browse files Browse the repository at this point in the history
  • Loading branch information
valkyrienyanko committed Oct 1, 2022
1 parent 055acf2 commit e2c0a01
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
2 changes: 1 addition & 1 deletion Scripts/UI/UIMapMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ private void _on_Host_pressed()
}

private void _on_Port_text_changed(string text) =>
HostPort = (ushort)LineEditHostPort.FilterRange(ushort.MaxValue, 3000);
HostPort = (ushort)LineEditHostPort.FilterRange(ushort.MaxValue);

private void _on_Password_text_changed(string text) => HostPassword = text;

Expand Down
36 changes: 24 additions & 12 deletions Scripts/Utils/Extensions/ExtensionsInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,29 +53,45 @@ public static string Filter(this TextEdit textEdit, Func<string, bool> filter)
return text;
}

public static int FilterRange(this LineEdit lineEdit, int maxRange, int minRange = 0)
public static int FilterRange(this LineEdit lineEdit, int maxRange)
{
var text = lineEdit.Text;
var id = lineEdit.GetInstanceId();

// Ignore blank spaces
if (string.IsNullOrWhiteSpace(text))
return minRange - 1;

if (text == "-")
return minRange - 1;
{
lineEdit.ChangeLineEditText("");
return 0;
}

// Text is not a number
if (!int.TryParse(text.Trim(), out int num))
{
// No keys are in the dictionary for the first case, so handle this by returning 0
if (!PrevNums.ContainsKey(id))
{
lineEdit.ChangeLineEditText("");
return minRange - 1;
return 0;
}

// Scenario #1: Text is 'a' -> returns ""
// Scenario #2: Text is '1a' -> returns ""
if (text.Length == 1 || text.Length == 2)
{
if (!int.TryParse(text, out int number))
{
lineEdit.ChangeLineEditText("");
return 0;
}
}

// Text is '123', user types a letter -> returns "123"
lineEdit.ChangeLineEditText($"{PrevNums[id]}");
return PrevNums[id];
}

// Not sure why this is here but I'm sure it's here for a good reason
if (text.Length > maxRange.ToString().Length && num <= maxRange)
{
var spliced = text.Remove(text.Length - 1);
Expand All @@ -86,18 +102,14 @@ public static int FilterRange(this LineEdit lineEdit, int maxRange, int minRange
return PrevNums[id];
}

// Text is at max range, return max range text if greater than max range
if (num > maxRange)
{
num = maxRange;
lineEdit.ChangeLineEditText($"{maxRange}");
}

if (num < minRange)
{
num = minRange;
lineEdit.ChangeLineEditText($"{minRange}");
}

// Keep track of the previous number
PrevNums[id] = num;
return num;
}
Expand Down

0 comments on commit e2c0a01

Please sign in to comment.