Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CB-3753-1809-fr-add-field-hints-in-the-filter-field #3151

Open
wants to merge 11 commits into
base: devel
Choose a base branch
from
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* CloudBeaver - Cloud Database Manager
* Copyright (C) 2020-2024 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0.
* you may not use this file except in compliance with the License.
*/

.menu {
&::before {
opacity: 0 !important;
}
}

.menuItem {
composes: theme-ripple from global;
background: transparent;
display: flex;
flex-direction: row;
align-items: center;
max-width: 200px;
padding: 4px 8px;
text-align: left;
outline: none;
color: inherit;
cursor: pointer;
gap: 8px;

& .itemTitle {
position: relative;
}

& .iconOrImage {
width: 16px;
height: 16px;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* CloudBeaver - Cloud Database Manager
* Copyright (C) 2020-2024 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0.
* you may not use this file except in compliance with the License.
*/
import { observer } from 'mobx-react-lite';
import { useEffect, useRef } from 'react';
import { MenuItem } from 'reakit';

import { IconOrImage } from '../IconOrImage.js';
import { Menu } from '../Menu/Menu.js';
import type { IMenuState } from '../Menu/MenuStateContext.js';
import { s } from '../s.js';
import { Text } from '../Text.js';
import { useS } from '../useS.js';
import style from './InputAutocompletionMenu.module.css';
import { type InputAutocompleteProposal, type InputAutocompleteStrategy, useInputAutocomplete } from './useInputAutocomplete.js';

interface AutocompletionProps {
sourceHints: InputAutocompleteProposal[];
inputRef: React.RefObject<HTMLInputElement | HTMLTextAreaElement>;
matchStrategy?: InputAutocompleteStrategy;
className?: string;
onSelect?: (proposal: InputAutocompleteProposal) => void;
}

export const InputAutocompletionMenu = observer(function InputAutocompletionMenu({
sourceHints,
className,
matchStrategy,
inputRef,
onSelect,
}: AutocompletionProps) {
const styles = useS(style);
const menuRef = useRef<IMenuState>();
const autocompleteState = useInputAutocomplete(inputRef, {
sourceHints,
matchStrategy,
});

function handleSelect(proposal: InputAutocompleteProposal) {
hideMenu();
autocompleteState.replaceCurrentWord(proposal.replacementString);
onSelect?.(proposal);
}

function hideMenu() {
menuRef.current?.hide();
}

function handleKeyDown(event: any) {
if (!autocompleteState.filteredSuggestions.length) {
return;
}

switch (event.key) {
case 'Escape':
hideMenu();
break;
default:
break;
}
}

useEffect(() => {
inputRef.current?.addEventListener('keydown', handleKeyDown);
return () => {
inputRef.current?.removeEventListener('keydown', handleKeyDown);
};
}, [inputRef.current, menuRef.current]);

useEffect(() => {
if (menuRef.current?.visible && (autocompleteState.filteredSuggestions === null || autocompleteState.filteredSuggestions.length === 0)) {
menuRef.current?.hide();
}
if (!menuRef.current?.visible && autocompleteState.filteredSuggestions !== null && autocompleteState.filteredSuggestions.length !== 0) {
menuRef.current?.show();
}
}, [sourceHints, menuRef, autocompleteState.filteredSuggestions]);

return (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably use combobox component as its based on the input and supports search

<Menu
className={s(styles, { menu: true }, className)}
menuRef={menuRef}
label="Autocompletion"
items={autocompleteState.filteredSuggestions.map(item => (
<MenuItem
key={item.displayString}
id={item.displayString}
type="button"
title={item.title}
className={styles['menuItem']}
onClick={event => handleSelect(item)}
>
{item.icon && <IconOrImage icon={item.icon} className={styles['iconOrImage']} />}
<Text truncate>{item.displayString}</Text>
</MenuItem>
))}
modal
/>
);
});
154 changes: 154 additions & 0 deletions webapp/packages/core-blocks/src/FormControls/useInputAutocomplete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* CloudBeaver - Cloud Database Manager
* Copyright (C) 2020-2024 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0.
* you may not use this file except in compliance with the License.
*/
import { action, computed, observable } from 'mobx';
import { type RefObject, useEffect } from 'react';

import { debounce, isFuzzySearchable, isNotNullDefined } from '@cloudbeaver/core-utils';

import { useObservableRef } from '../useObservableRef.js';

export type InputAutocompleteStrategy = 'startsWith' | 'contains' | 'fuzzy';

interface InputAutocompleteOptions {
sourceHints: InputAutocompleteProposal[];
matchStrategy?: InputAutocompleteStrategy;
filter?: (suggestion: InputAutocompleteProposal, lastWord?: string) => boolean;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe predicate is more descriptive word for that prop, then filter.

}

export interface InputAutocompleteProposal {
displayString: string;
replacementString: string;
icon?: string;
title?: string;
score?: number;
}

const INPUT_DELAY = 300;

export const useInputAutocomplete = (
inputRef: RefObject<HTMLInputElement | HTMLTextAreaElement>,
{ sourceHints, matchStrategy = 'startsWith', filter }: InputAutocompleteOptions,
) => {
const state = useObservableRef(
() => ({
input: inputRef.current?.value as string | undefined,
selectionStart: inputRef.current?.selectionStart ?? null,
selectionEnd: inputRef.current?.value?.length ?? null,
replaceCurrentWord(replacement: string) {
const input = this.inputRef.current;

if (!input) {
return;
}

const cursorPosition = this.selectionStart;
const words = this.input?.split(' ');

if (!isNotNullDefined(words) || !isNotNullDefined(cursorPosition) || !isNotNullDefined(this.currentWord)) {
Comment on lines +50 to +52
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to check words and cursor here if currentWord getter should return falsy value if there is no words or cursorPosition?

return;
}

const start = cursorPosition - this.currentWord.length;
const end = cursorPosition;

this.input = this.input?.slice(0, start) + replacement + this.input?.slice(end);
this.selectionStart = start + replacement.length;
this.selectionEnd = start + replacement.length;

input.value = this.input;
input.focus();
},
get currentWord() {
const cursorPosition = this.selectionStart;

if (!cursorPosition) {
return '';
}

const substring = this.input?.slice(0, cursorPosition);

if (!substring) {
return '';
}

return (
substring
.split(' ')
.at(-1)
?.replace(/[^\w\s]|_/g, '') ?? ''
);
},
get filteredSuggestions() {
if (!this.currentWord) {
return [];
}

return this.sourceHints
.filter(suggestion => {
const values = [suggestion.displayString.toLocaleLowerCase(), suggestion.replacementString.toLocaleLowerCase()];
const isEqual = values.some(value => value === this.currentWord?.toLocaleLowerCase());

if (!this.currentWord || isEqual) {
return false;
}

return (
(this.matchStrategy === 'startsWith' &&
values.some(value => isNotNullDefined(this.currentWord) && value.startsWith(this.currentWord))) ||
(this.matchStrategy === 'contains' && values.some(value => isNotNullDefined(this.currentWord) && value.includes(this.currentWord))) ||
(this.matchStrategy === 'fuzzy' &&
values.some(value => isNotNullDefined(this.currentWord) && isFuzzySearchable(this.currentWord, value)))
);
})
Comment on lines +101 to +107
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
(this.matchStrategy === 'startsWith' &&
values.some(value => isNotNullDefined(this.currentWord) && value.startsWith(this.currentWord))) ||
(this.matchStrategy === 'contains' && values.some(value => isNotNullDefined(this.currentWord) && value.includes(this.currentWord))) ||
(this.matchStrategy === 'fuzzy' &&
values.some(value => isNotNullDefined(this.currentWord) && isFuzzySearchable(this.currentWord, value)))
);
})
const isMatch = () => {
const { matchStrategy, currentWord } = this;
if (!isNotNullDefined(currentWord)) {
return false;
}
const matchFunctions: { [key: InputAutocompleteStrategy]: (value: string) => boolean } = {
startsWith: value => value.startsWith(currentWord),
contains: value => value.includes(currentWord),
fuzzy: value => isFuzzySearchable(currentWord, value),
};
return values.some(matchFunctions[matchStrategy]);
};

Maybe like that? And we checked thus.currentWord just above, so maybe we can skip this check:

 if (!isNotNullDefined(currentWord)) {
    return false;
  }

.filter(suggestion => (filter ? filter(suggestion, this.currentWord) : true))
.sort((a, b) => {
if (isNotNullDefined(a.score) && isNotNullDefined(b.score)) {
return b.score - a.score;
}

return 0;
});
},
}),
{
input: observable.ref,
selectionStart: observable.ref,
selectionEnd: observable.ref,
sourceHints: observable.ref,
matchStrategy: observable.ref,
inputRef: observable.ref,
currentWord: computed,
filteredSuggestions: computed,
replaceCurrentWord: action.bound,
},
{ sourceHints, matchStrategy, inputRef },
);

const handleInput = debounce((event: Event) => {
const target = event.target as HTMLInputElement;

state.selectionStart = target.selectionStart;
state.selectionEnd = target.selectionEnd;
state.input = target?.value;
}, INPUT_DELAY);

useEffect(() => {
const input = state.inputRef.current;

if (!input) {
return;
}

input.addEventListener('input', handleInput);
return () => {
input.removeEventListener('input', handleInput);
};
}, [state.inputRef.current]);

Check warning on line 151 in webapp/packages/core-blocks/src/FormControls/useInputAutocomplete.ts

View check run for this annotation

Jenkins-CI-integration / CheckStyle TypeScript Report

webapp/packages/core-blocks/src/FormControls/useInputAutocomplete.ts#L151

React Hook useEffect has missing dependencies: handleInput and state.inputRef. Either include them or remove the dependency array. Mutable values like state.inputRef.current arent valid dependencies because mutating them doesnt re-render the component. (react-hooks/exhaustive-deps)

return state;
};
2 changes: 2 additions & 0 deletions webapp/packages/core-blocks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,5 @@ export * from './importLazyComponent.js';
export * from './ClickableLoader.js';
export * from './FormControls/TagsComboboxLoader.js';
export * from './Flex/Flex.js';
export * from './FormControls/useInputAutocomplete.js';
export * from './FormControls/InputAutocompletionMenu.js';
Loading
Loading