From 11f1f625239c1712f0f318a7f8ba858cf564ed1f Mon Sep 17 00:00:00 2001
From: Tom Sherman <the.tomsherman@gmail.com>
Date: Thu, 12 Jan 2023 18:14:34 +0000
Subject: [PATCH] feat: hide server autocomplete when you enter a valid URL
 (#1009)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: 三咲智子 Kevin Deng <sxzz@sxzz.moe>
closes https://github.com/elk-zone/elk/issues/1005
---
 components/user/UserSignIn.vue | 37 ++++++++++++++++++++++++++--------
 1 file changed, 29 insertions(+), 8 deletions(-)

diff --git a/components/user/UserSignIn.vue b/components/user/UserSignIn.vue
index 2c5d2975..904992d5 100644
--- a/components/user/UserSignIn.vue
+++ b/components/user/UserSignIn.vue
@@ -47,14 +47,6 @@ async function oauth() {
   }
 }
 
-async function handleInput() {
-  if (server.startsWith('https://'))
-    server = server.replace('https://', '')
-
-  if (server?.length)
-    displayError = false
-}
-
 let fuse = $shallowRef(new Fuse([] as string[]))
 
 const filteredServers = $computed(() => {
@@ -68,6 +60,35 @@ const filteredServers = $computed(() => {
   return results
 })
 
+function isValidUrl(str: string) {
+  try {
+    // eslint-disable-next-line no-new
+    new URL(str)
+    return true
+  }
+  catch (err) {
+    return false
+  }
+}
+
+async function handleInput() {
+  if (server.startsWith('https://'))
+    server = server.replace('https://', '')
+
+  if (server?.length)
+    displayError = false
+
+  if (
+    isValidUrl(`https://${server.trim()}`)
+    && server.trim().match(/^[a-z0-9-]+(\.[a-z0-9-]+)+(:[0-9]+)?$/i)
+    // Do not hide the autocomplete if a result has an exact substring match on the input
+    && !filteredServers.some(s => s.includes(server.trim()))
+  )
+    autocompleteShow = false
+  else
+    autocompleteShow = true
+}
+
 function toSelector(server: string) {
   return server.replace(/[^\w-]/g, '-')
 }