You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by GitBox <gi...@apache.org> on 2022/03/04 14:21:37 UTC

[GitHub] [superset] michael-s-molina commented on a change in pull request #18856: feat(select): sort exact and startsWith match to first

michael-s-molina commented on a change in pull request #18856:
URL: https://github.com/apache/superset/pull/18856#discussion_r819590759



##########
File path: superset-frontend/src/components/Select/Select.tsx
##########
@@ -315,81 +324,44 @@ const Select = ({
     : allowNewOptions
     ? 'tags'
     : 'multiple';
-  const allowFetch = !fetchOnlyOnSearch || searchedValue;
-
-  // TODO: Don't assume that isAsync is always labelInValue
-  const handleTopOptions = useCallback(
-    (selectedValue: AntdSelectValue | undefined) => {
-      // bringing selected options to the top of the list
-      if (selectedValue !== undefined && selectedValue !== null) {
-        const isLabeledValue = isAsync || labelInValue;
-        const topOptions: OptionsType = [];
-        const otherOptions: OptionsType = [];
-
-        selectOptions.forEach(opt => {
-          let found = false;
-          if (Array.isArray(selectedValue)) {
-            if (isLabeledValue) {
-              found =
-                (selectedValue as AntdLabeledValue[]).find(
-                  element => element.value === opt.value,
-                ) !== undefined;
-            } else {
-              found = selectedValue.includes(opt.value);
-            }
-          } else {
-            found = isLabeledValue
-              ? (selectedValue as AntdLabeledValue).value === opt.value
-              : selectedValue === opt.value;
-          }
-
-          if (found) {
-            topOptions.push(opt);
-          } else {
-            otherOptions.push(opt);
-          }
-        });
-
-        // fallback for custom options in tags mode as they
-        // do not appear in the selectOptions state
-        if (!isSingleMode && Array.isArray(selectedValue)) {
-          selectedValue.forEach((val: string | number | AntdLabeledValue) => {
-            if (
-              !topOptions.find(
-                tOpt =>
-                  tOpt.value ===
-                  (isLabeledValue ? (val as AntdLabeledValue)?.value : val),
-              )
-            ) {
-              if (isLabeledValue) {
-                const labelValue = val as AntdLabeledValue;
-                topOptions.push({
-                  label: labelValue.label,
-                  value: labelValue.value,
-                });
-              } else {
-                const value = val as string | number;
-                topOptions.push({ label: String(value), value });
-              }
-            }
-          });
-        }
-        const sortedOptions = [
-          ...topOptions.sort(sortComparator),
-          ...otherOptions.sort(sortComparator),
-        ];
-        if (!isEqual(sortedOptions, selectOptions)) {
-          setSelectOptions(sortedOptions);
-        }
-      } else {
-        const sortedOptions = [...selectOptions].sort(sortComparator);
-        if (!isEqual(sortedOptions, selectOptions)) {
-          setSelectOptions(sortedOptions);
-        }
-      }
-    },
-    [isAsync, isSingleMode, labelInValue, selectOptions, sortComparator],
+  const allowFetch = !fetchOnlyOnSearch || inputValue;
+
+  const sortSelectedFirst = useCallback(
+    (a: AntdLabeledValue, b: AntdLabeledValue) =>
+      selectValue && a.value !== undefined && b.value !== undefined
+        ? Number(hasOption(b.value, selectValue)) -
+          Number(hasOption(a.value, selectValue))
+        : 0,
+    [selectValue],
+  );
+  const sortComparatorWithSearch = useCallback(
+    (a: AntdLabeledValue, b: AntdLabeledValue) =>
+      sortSelectedFirst(a, b) || sortComparator(a, b, inputValue),
+    [inputValue, sortComparator, sortSelectedFirst],
   );
+  const sortComparatorWithoutSearch = useCallback(
+    (a: AntdLabeledValue, b: AntdLabeledValue) =>
+      sortSelectedFirst(a, b) || sortComparator(a, b, ''),
+    [sortComparator, sortSelectedFirst],
+  );
+  const [selectOptions_, setSelectOptions] =

Review comment:
       Can we improve the logic here? Having a state called `selectOption_` which is updated by `setSelectOption` and then a memo called `selectOption`  is really confusing. Can't we just update the state when the `selectValue` changes and this value is not present in the options?

##########
File path: superset-frontend/src/utils/rankedSearchCompare.ts
##########
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Sort comparator with basic rankings.
+ */
+export function rankedSearchCompare(a: string, b: string, search: string) {
+  const aLower = a.toLowerCase() || '';
+  const bLower = b.toLowerCase() || '';
+  const searchLower = search.toLowerCase() || '';
+  if (!search) return a.localeCompare(b);
+  return (
+    Number(b === search) - Number(a === search) ||
+    Number(b.startsWith(search)) - Number(a.startsWith(search)) ||

Review comment:
       I think https://github.com/apache/superset/pull/18837 is trying to resolve a different use case. If you check the original issue https://github.com/apache/superset/issues/17716 you will see that the X-Axis time format is a select that allows new options, which means the user is trying to insert a new lower case value but can't because it's matched with an upper case version. Here's an example where the initial `h` is lower case:
   
   <img width="304" alt="Screen Shot 2022-03-04 at 10 18 22 AM" src="https://user-images.githubusercontent.com/70410625/156770545-c01ca798-5527-4ffc-b56b-eb6eefd21a6c.png">
   

##########
File path: superset-frontend/src/components/Select/Select.stories.tsx
##########
@@ -80,6 +80,12 @@ const ARG_TYPES = {
       The options can also be async, a promise that returns an array of options.
     `,
   },
+  optionsCount: {

Review comment:
       Since this is only being used by `InteractiveSelect`, can we move it to `InteractiveSelect.argTypes`? Currently, it's appearing for `AsyncSelect` but does not have any effect.

##########
File path: superset-frontend/src/components/Select/Select.tsx
##########
@@ -577,7 +538,6 @@ const Select = ({
 
     if (filterOption) {
       const searchValue = search.trim().toLowerCase();

Review comment:
       That's an interesting point. We also need to consider frequent use cases. If I search for "michael", I expect to get "Michael". We can tackle this in more depth when adding support to sophisticated backend search engines.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org