1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-20 02:48:51 +00:00

Merge pull request #5783 from haiwen/feat/question-answering-search-new

Feat/question answering search new
This commit is contained in:
Michael An
2023-11-23 10:33:33 +08:00
committed by GitHub
22 changed files with 659 additions and 82 deletions

View File

@@ -0,0 +1,79 @@
.search-container.show.ai-search-ask {
width: 800px;
}
.ai-search-ask .ai-search-ask-header {
display: flex;
align-items: center;
padding: 1rem;
border-bottom: 1px solid rgba(0, 40, 100, 0.12);
}
.ai-search-ask .ai-search-ask-header .ai-search-ask-return {
padding: 0 4px;
transform: rotate(180deg);
line-height: 10px;
cursor: pointer;
}
.ai-search-ask .ai-search-ask-header .ai-search-ask-return .seafile-multicolor-icon-arrow {
opacity: 0.6;
}
.ai-search-ask .ai-search-ask-header .ai-search-ask-return:hover .seafile-multicolor-icon-arrow {
opacity: 0.8;
}
.ai-search-ask .ai-search-ask-body {
display: flex;
max-height: 400px;
overflow-y: auto;
}
.ai-search-ask .ai-search-ask-body .ai-search-ask-body-left {
flex-shrink: 0;
margin-right: 1rem;
}
.ai-search-ask .ai-search-ask-body .ai-search-ask-body-right {
line-height: 1.8;
font-size: 14px;
width: 100%;
}
.ai-search-ask .ai-search-ask-footer {
border-top: 1px solid rgba(0, 40, 100, 0.12);
margin: 0 1rem;
padding: 1rem 0;
}
.ai-search-ask .ai-search-ask-footer .ai-search-ask-footer-btn {
width: 16px;
height: 16px;
position: absolute;
right: 8px;
top: 8px;
background-color: #fff;
cursor: pointer;
}
.ai-search-ask .ai-search-ask-footer .ai-search-ask-footer-btn .seafile-multicolor-icon-send {
color: #ff8000;
}
.ai-search-ask .ai-search-ask-footer .ai-search-ask-footer-btn:hover .seafile-multicolor-icon-send {
color: #d96d00;
}
@media (max-width: 768px) {
.search-container.show.ai-search-ask {
width: 100%;
}
.ai-search-ask .search-input {
box-shadow: none;
width: 100% !important;
}
}

View File

@@ -0,0 +1,209 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import isHotkey from 'is-hotkey';
import { seafileAPI } from '../../utils/seafile-api';
import { gettext } from '../../utils/constants';
import toaster from '../toast';
import Loading from '../loading';
import Icon from '../icon';
import { Utils } from '../../utils/utils';
import { SEARCH_DELAY_TIME, getValueLength } from './constant';
import AISearchRefrences from './ai-search-widgets/ai-search-refrences';
import AISearchHelp from './ai-search-widgets/ai-search-help';
import AISearchRobot from './ai-search-widgets/ai-search-robot';
import './ai-search-ask.css';
const INDEX_STATE = {
RUNNING: 'running',
UNCREATED: 'uncreated',
FINISHED: 'finished'
};
export default class AISearchAsk extends Component {
static propTypes = {
value: PropTypes.string,
token: PropTypes.string,
repoID: PropTypes.string,
repoName: PropTypes.string,
indexState: PropTypes.string,
onItemClickHandler: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
value: props.value,
isLoading: false,
answeringResult: '',
hitFiles: [],
};
this.timer = null;
this.isChineseInput = false;
}
componentDidMount() {
document.addEventListener('compositionstart', this.onCompositionStart);
document.addEventListener('compositionend', this.onCompositionEnd);
this.onSearch();
}
componentWillUnmount() {
document.removeEventListener('compositionstart', this.onCompositionStart);
document.removeEventListener('compositionend', this.onCompositionEnd);
this.isChineseInput = false;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
onCompositionStart = () => {
this.isChineseInput = true;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
};
onCompositionEnd = () => {
this.isChineseInput = false;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.onSearch();
}, SEARCH_DELAY_TIME);
};
onChange = (event) => {
const newValue = event.target.value;
this.setState({ value: newValue }, () => {
if (!this.isChineseInput) {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.onSearch();
}, SEARCH_DELAY_TIME);
}
});
};
onKeydown = (event) => {
if (isHotkey('enter', event)) {
this.onSearch();
}
};
formatQuestionAnsweringItems(data) {
let items = [];
for (let i = 0; i < data.length; i++) {
items[i] = {};
items[i]['index'] = [i];
items[i]['name'] = data[i].substring(data[i].lastIndexOf('/')+1);
items[i]['path'] = data[i];
items[i]['repo_id'] = this.props.repoID;
items[i]['is_dir'] = false;
items[i]['link_content'] = decodeURI(data[i]).substring(1);
items[i]['content'] = data[i].sentence;
items[i]['thumbnail_url'] = '';
}
return items;
}
onSearch = () => {
const { indexState, repoID, token } = this.props;
if (indexState === INDEX_STATE.UNCREATED) {
toaster.warning(gettext('Please create index first.'));
return;
}
if (indexState === INDEX_STATE.RUNNING) {
toaster.warning(gettext('Indexing, please try again later.'));
return;
}
if (this.state.isLoading || getValueLength(this.state.value.trim()) < 3) {
return;
}
this.setState({ isLoading: true });
const searchParams = {
q: this.state.value.trim(),
search_repo: repoID || 'all',
};
seafileAPI.questionAnsweringFiles(searchParams, token).then(res => {
const { answering_result } = res.data || {};
const hit_files = answering_result !== 'false' ? res.data.hit_files : [];
this.setState({
isLoading: false,
answeringResult: answering_result === 'false' ? 'No result' : answering_result,
hitFiles: this.formatQuestionAnsweringItems(hit_files),
});
}).catch(error => {
/* eslint-disable */
console.log(error);
this.setState({ isLoading: false });
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
});
};
render() {
return (
<div className="search">
<div className="search-mask show" onClick={this.props.closeAsk}></div>
<div className="ai-search-ask search-container show p-0">
<div className="ai-search-ask-header">
<span className="ai-search-ask-return" onClick={this.props.closeAsk}>
<Icon symbol='arrow' />
</span>
{gettext('Return')}
</div>
{this.state.isLoading ?
<div className="d-flex align-items-center my-8">
<Loading />
</div>
:
<div className="ai-search-ask-body p-6 pb-4">
<div className="ai-search-ask-body-left">
<AISearchRobot/>
</div>
<div className="ai-search-ask-body-right">
<div>{this.state.answeringResult}</div>
<AISearchHelp />
{this.state.hitFiles.length > 0 &&
<AISearchRefrences
hitFiles={this.state.hitFiles}
onItemClickHandler={this.props.onItemClickHandler}
/>
}
</div>
</div>
}
<div className="ai-search-ask-footer">
<div className={`input-icon mb-1`}>
<input
type="text"
className="form-control search-input w-100"
name="query"
value={this.state.value}
onChange={this.onChange}
autoComplete="off"
onKeyDown={this.onKeydown}
placeholder={gettext('Ask a question') + '...'}
/>
<span className="ai-search-ask-footer-btn" onClick={this.onSearch}>
<Icon symbol='send' />
</span>
</div>
</div>
</div>
</div>
)
}
}

View File

@@ -0,0 +1,25 @@
.ai-search-help {
padding: 20px 0 20px 0;
border-bottom: 1px solid rgba(0, 40, 100, 0.12);
}
.ai-search-help .ai-search-help-title {
margin-bottom: 10px;
}
.ai-search-help .ai-search-help-container {
display: flex;
}
.ai-search-help .ai-search-help-container .ai-search-help-detail {
border: 1px solid #ccc;
max-width: 200px;
margin-right: 8px;
padding: 4px 8px;
border-radius: 3px;
}
.ai-search-help .ai-search-help-detail:hover {
cursor: pointer;
background-color: rgb(245, 245, 245);
}

View File

@@ -0,0 +1,23 @@
import React from 'react';
import Icon from '../../icon';
import { gettext } from '../../../utils/constants';
import './ai-search-help.css';
export default function AISearchHelp() {
return (
<div className="ai-search-help">
<div className="ai-search-help-title">{gettext('Is this answer helpful to you')}{':'}</div>
<div className='ai-search-help-container'>
<div className="ai-search-help-detail" key={1}>
<Icon symbol='helpful' />
<span className="pl-1">{gettext('Yes')}</span>
</div>
<div className="ai-search-help-detail" key={2}>
<Icon symbol='helpless' />
<span className="pl-1">{gettext('No')}</span>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,24 @@
.ai-search-refrences {
margin-top: 10px;
}
.ai-search-refrences .ai-search-refrences-title {
margin-bottom: 6px;
}
.ai-search-refrences .ai-search-refrences-container {
display: flex;
}
.ai-search-refrences .ai-search-refrences-container .ai-search-refrences-detail {
border: 1px solid #ccc;
max-width: 200px;
margin-right: 8px;
padding: 4px 8px;
border-radius: 3px;
}
.ai-search-refrences .ai-search-refrences-detail:hover {
cursor: pointer;
background-color: rgb(245, 245, 245);
}

View File

@@ -0,0 +1,33 @@
import React from 'react';
import PropTypes from 'prop-types';
import { gettext } from '../../../utils/constants';
import './ai-search-refrences.css';
function AISearchRefrences({hitFiles, onItemClickHandler}) {
return (
<div className="ai-search-refrences">
<div className="ai-search-refrences-title">{gettext('Reference documents')}{':'}</div>
<div className='ai-search-refrences-container'>
{hitFiles.map((hitFile, index) => {
return (
<div
className="ai-search-refrences-detail text-truncate"
onClick={() => onItemClickHandler(hitFile)}
key={index}
>
{`${index + 1}. ${hitFile.name}`}
</div>
);
})}
</div>
</div>
);
}
AISearchRefrences.propTypes = {
hitFiles: PropTypes.array.isRequired,
onItemClickHandler: PropTypes.func.isRequired,
};
export default AISearchRefrences;

View File

@@ -0,0 +1,17 @@
import React from 'react';
import PropTypes from 'prop-types';
import { mediaUrl } from '../../../utils/constants';
function AISearchRobot({style}) {
return (
<div style={style}>
<img src={`${mediaUrl}img/ask-ai.png`} alt="" width="32" height="32" />
</div>
);
}
AISearchRobot.propTypes = {
style: PropTypes.object,
};
export default AISearchRobot;

View File

@@ -1,6 +1,7 @@
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import isHotkey from 'is-hotkey';
import classnames from 'classnames';
import MediaQuery from 'react-responsive';
import { seafileAPI } from '../../utils/seafile-api';
import { gettext, siteRoot } from '../../utils/constants';
@@ -9,7 +10,9 @@ import { Utils } from '../../utils/utils';
import { isMac } from '../../utils/extra-attributes';
import toaster from '../toast';
import Switch from '../common/switch';
import { SEARCH_DELAY_TIME } from './constant';
import { SEARCH_DELAY_TIME, getValueLength } from './constant';
import AISearchAsk from './ai-search-ask';
import AISearchRobot from './ai-search-widgets/ai-search-robot';
const INDEX_STATE = {
RUNNING: 'running',
@@ -17,6 +20,11 @@ const INDEX_STATE = {
FINISHED: 'finished'
};
const SEARCH_MODE = {
QA: 'question-answering',
COMBINED: 'combined-search',
};
const PER_PAGE = 10;
const controlKey = isMac() ? '⌘' : 'Ctrl';
@@ -47,6 +55,7 @@ export default class AISearch extends Component {
isSearchInputShow: false, // for mobile
searchPageUrl: this.baseSearchPageURL,
indexState: '',
searchMode: SEARCH_MODE.COMBINED,
};
this.inputValue = '';
this.highlightRef = null;
@@ -84,33 +93,31 @@ export default class AISearch extends Component {
document.removeEventListener('compositionstart', this.onCompositionStart);
document.removeEventListener('compositionend', this.onCompositionEnd);
this.isChineseInput = false;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.clearTimer();
if (this.indexStateTimer) {
clearInterval(this.indexStateTimer);
this.indexStateTimer = null;
}
}
onCompositionStart = () => {
this.isChineseInput = true;
clearTimer = () => {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
};
onCompositionStart = () => {
this.isChineseInput = true;
this.clearTimer();
};
onCompositionEnd = () => {
this.isChineseInput = false;
// chromecompositionstart -> onChange -> compositionend
// not chromecompositionstart -> compositionend -> onChange
// The onChange event will setState and change input value, then setTimeout to initiate the search
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.clearTimer();
this.timer = setTimeout(() => {
this.onSearch();
}, SEARCH_DELAY_TIME);
@@ -199,10 +206,7 @@ export default class AISearch extends Component {
if (this.inputValue === newValue.trim()) return;
this.inputValue = newValue.trim();
if (!this.isChineseInput) {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.clearTimer();
this.timer = setTimeout(() => {
this.onSearch();
}, SEARCH_DELAY_TIME);
@@ -219,7 +223,7 @@ export default class AISearch extends Component {
onSearch = () => {
const { value } = this.state;
const { repoID } = this.props;
if (this.inputValue === '' || this.getValueLength(this.inputValue) < 3) {
if (this.inputValue === '' || getValueLength(this.inputValue) < 3) {
this.setState({
highlightIndex: 0,
resultItems: [],
@@ -329,6 +333,9 @@ export default class AISearch extends Component {
hasMore: false,
});
}).catch(error => {
if (error && error.message === "prev request is cancelled") {
return;
}
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
this.setState({ isLoading: false });
@@ -362,23 +369,6 @@ export default class AISearch extends Component {
this.setState({searchPageUrl: `${this.baseSearchPageURL}?${params.substring(0, params.length - 1)}`});
}
getValueLength(str) {
var i = 0, code, len = 0;
for (; i < str.length; i++) {
code = str.charCodeAt(i);
if (code == 10) { //solve enter problem
len += 2;
} else if (code < 0x007f) {
len += 1;
} else if (code >= 0x0080 && code <= 0x07ff) {
len += 2;
} else if (code >= 0x0800 && code <= 0xffff) {
len += 3;
}
}
return len;
}
formatResultItems(data) {
let items = [];
for (let i = 0; i < data.length; i++) {
@@ -429,26 +419,55 @@ export default class AISearch extends Component {
});
}
openAsk = () => {
this.clearTimer();
this.setState({ searchMode: SEARCH_MODE.QA });
}
closeAsk = () => {
this.clearTimer();
this.setState({ searchMode: SEARCH_MODE.COMBINED });
}
renderSearchResult() {
const { resultItems, highlightIndex, width } = this.state;
const { resultItems, highlightIndex, width, searchMode, answeringResult } = this.state;
if (!width || width === 'default') return null;
if (!this.state.isResultShow) return null;
if (!this.state.isResultGetted || this.getValueLength(this.inputValue) < 3) {
if (!this.state.isResultGetted || getValueLength(this.inputValue) < 3) {
return (
<span className="loading-icon loading-tip"></span>
);
}
if (!resultItems.length) {
return (
<div className="search-result-none">{gettext('No results matching.')}</div>
<>
<li className='search-result-item align-items-center' onClick={this.openAsk}>
<AISearchRobot />
<div className="item-content">
<div className="item-name ellipsis">{gettext('Ask AI')}{': '}{this.state.value.trim()}</div>
</div>
</li>
<div className="search-result-none">{gettext('No results matching.')}</div>
</>
);
}
const results = (
<ul className="search-result-list" ref={this.searchResultListRef}>
<li
className={classnames('search-result-item align-items-center py-3', {'search-result-item-highlight': highlightIndex === 0 })}
onClick={this.openAsk}
>
<AISearchRobot style={{width: 36}}/>
<div className="item-content">
<div className="item-name ellipsis">
{gettext('Ask AI')}{': '}{this.state.value.trim()}
</div>
</div>
</li>
{resultItems.map((item, index) => {
const isHighlight = index === highlightIndex;
const isHighlight = (index + 1) === highlightIndex;
return (
<SearchResultItem
key={index}
@@ -545,8 +564,22 @@ export default class AISearch extends Component {
render() {
let width = this.state.width !== 'default' ? this.state.width : '';
let style = {'width': width};
const { isMaskShow, isCloseShow } = this.state;
const { isMaskShow, isCloseShow, searchMode, answeringResult, resultItems } = this.state;
const placeholder = `${this.props.placeholder}${isMaskShow ? '' : ` (${controlKey} + f )`}`;
if (searchMode === SEARCH_MODE.QA) {
return (
<AISearchAsk
token={this.source ? this.source.token : null}
indexState={this.state.indexState}
repoID={this.props.repoID}
value={this.state.value.trim()}
closeAsk={this.closeAsk}
onItemClickHandler={this.onItemClickHandler}
/>
);
}
return (
<Fragment>
<MediaQuery query="(min-width: 768px)">

View File

@@ -1,3 +1,21 @@
const SEARCH_DELAY_TIME = 1000;
export { SEARCH_DELAY_TIME };
const getValueLength = (str) => {
let code;
let len = 0;
for (let i = 0; i < str.length; i++) {
code = str.charCodeAt(i);
if (code == 10) { //solve enter problem
len += 2;
} else if (code < 0x007f) {
len += 1;
} else if (code >= 0x0080 && code <= 0x07ff) {
len += 2;
} else if (code >= 0x0800 && code <= 0xffff) {
len += 3;
}
}
return len;
};
export { SEARCH_DELAY_TIME, getValueLength };

View File

@@ -8,7 +8,7 @@ import SearchResultItem from './search-result-item';
import { Utils } from '../../utils/utils';
import { isMac } from '../../utils/extra-attributes';
import toaster from '../toast';
import { SEARCH_DELAY_TIME } from './constant';
import { SEARCH_DELAY_TIME, getValueLength } from './constant';
const propTypes = {
repoID: PropTypes.string,
@@ -305,23 +305,6 @@ class Search extends Component {
this.setState({searchPageUrl: `${this.baseSearchPageURL}?${params.substring(0, params.length - 1)}`});
}
getValueLength(str) {
var i = 0, code, len = 0;
for (; i < str.length; i++) {
code = str.charCodeAt(i);
if (code == 10) { //solve enter problem
len += 2;
} else if (code < 0x007f) {
len += 1;
} else if (code >= 0x0080 && code <= 0x07ff) {
len += 2;
} else if (code >= 0x0800 && code <= 0xffff) {
len += 3;
}
}
return len;
}
formatResultItems(data) {
let items = [];
for (let i = 0; i < data.length; i++) {
@@ -359,7 +342,7 @@ class Search extends Component {
if (!width || width === 'default') return null;
if (!this.state.isResultShow) return null;
if (!this.state.isResultGetted || this.getValueLength(this.inputValue) < 3) {
if (!this.state.isResultGetted || getValueLength(this.inputValue) < 3) {
return (
<span className="loading-icon loading-tip"></span>
);

View File

@@ -7,6 +7,7 @@ import SearchResultItem from './search-result-item';
import More from '../more';
import { Utils } from '../../utils/utils';
import toaster from '../toast';
import { getValueLength } from './constant';
const propTypes = {
repoID: PropTypes.string,
@@ -134,23 +135,6 @@ class Search extends Component {
this.source.cancel('prev request is cancelled');
}
getValueLength(str) {
var i = 0, code, len = 0;
for (; i < str.length; i++) {
code = str.charCodeAt(i);
if (code == 10) { //solve enter problem
len += 2;
} else if (code < 0x007f) {
len += 1;
} else if (code >= 0x0080 && code <= 0x07ff) {
len += 2;
} else if (code >= 0x0800 && code <= 0xffff) {
len += 3;
}
}
return len;
}
formatResultItems(data) {
let items = [];
let length = data.length > 5 ? 5 : data.length;
@@ -199,7 +183,7 @@ class Search extends Component {
if (!this.state.isResultShow) {
return;
}
if (!this.state.isResultGetted || this.getValueLength(this.inputValue) < 3) {
if (!this.state.isResultGetted || getValueLength(this.inputValue) < 3) {
return (
<span className="loading-icon loading-tip"></span>
);