Skip to content

Commit

Permalink
Dev (#231)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lungsangg authored Aug 6, 2024
2 parents dd597e3 + 026d48b commit af81532
Show file tree
Hide file tree
Showing 14 changed files with 270 additions and 75 deletions.
75 changes: 75 additions & 0 deletions reader/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4418,6 +4418,81 @@ def dummy_search_api(request):
resp['Content-Type'] = "application/json; charset=utf-8"
return resp

@csrf_exempt
def mongo_search_api(request):

print(">>>>>>>>>>>>>>>>>>>>>request>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",request.method)
if(request.method == "GET"):
try:
chapter_query = urllib.parse.unquote(request.GET.get('chapterQuery', ''))
title_query = urllib.parse.unquote(request.GET.get('titleQuery', ''))

if chapter_query:
# data = json.loads(request.body)
# query = data.get('query', '')
print("query: ", chapter_query, "title", title_query)
query = [
{
"$unwind": {
"path": "$chapter",
"includeArrayIndex": "outerIndex"
}
},
{
"$unwind": {
"path": "$chapter",
"includeArrayIndex": "innerIndex"
}
},
{
"$addFields": {
"outerIndex": { "$add": ["$outerIndex", 1] },
"innerIndex": { "$add": ["$innerIndex", 1] }
}
},
{
"$match": {
"$and": [
{ "title": { "$regex": title_query, "$options": "i" } },
{ "chapter": { "$regex": chapter_query, "$options": "i" } }
]
}
},
{
"$group": {
"_id": "$_id",
"language": { "$first": "$language" },
"title": { "$first": "$title" },
"versionSource": { "$first": "$versionSource" },
"versionTitle": { "$first": "$versionTitle" },
"iscompleted": { "$first": "$iscompleted" },
"actualLanguage": { "$first": "$actualLanguage" },
"languageFamilyName": { "$first": "$languageFamilyName" },
"direction": { "$first": "$direction" },
"matchingChapters": {
"$push": {
"chapter": "$chapter",
"index": {
"$concat": [
{ "$toString": "$outerIndex" },
".",
{ "$toString": "$innerIndex" }
]
}
}
}
}
}
]

result = list(db.texts.aggregate(query))
for item in result:
item.pop('_id', None)
return jsonResponse({'status': 'success', 'result': result})
except Exception as e:
print({'status': 'error', 'message': str(e)})
return jsonResponse({'status': 'error', 'message': str(e)}, status=500)


@csrf_exempt
def search_wrapper_api(request, es6_compat=False):
Expand Down
1 change: 1 addition & 0 deletions sefaria/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@
url(r'^api/search-wrapper/es8$', reader_views.search_wrapper_api),
url(r'^api/search-wrapper$', reader_views.search_wrapper_api, {'es6_compat': True}),
url(r'^api/search-path-filter/(?P<book_title>.+)$', reader_views.search_path_filter),
url(r'^api/mongo-search/', reader_views.mongo_search_api),
]

# Following API
Expand Down
1 change: 1 addition & 0 deletions static/js/ConnectionFilters.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class CategoryFilter extends Component {
}
}
render() {

const filterSuffix = this.props.category === "Quoting Commentary" ? "Quoting" : null;
const textMissingDescription = null; //"missing description"
const textFilters = this.props.showBooks ? this.props.books.map(function(book, i) {
Expand Down
1 change: 1 addition & 0 deletions static/js/ConnectionsPanel.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,7 @@ class ConnectionsPanel extends Component {
divineNameReplacement={this.props.divineNameReplacement}
/>
} else if (this.props.mode === "SidebarSearch") {
console.log("sidebarsearch: ", this.props.title, this.props.sidebarSearchQuery)
content = <SidebarSearch
title={this.props.title}
navigatePanel={this.props.navigatePanel}
Expand Down
11 changes: 10 additions & 1 deletion static/js/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -353,12 +353,21 @@ class SearchBar extends Component {
this.submitSearch(query);
}
handleSearchButtonClick(event) {

const query = $(ReactDOM.findDOMNode(this)).find(".search").val();
if (query) {
this.submitSearch(query);
} else {
$(ReactDOM.findDOMNode(this)).find(".search").focus();
}
// }
}
// handleMongoSearchBtn(e) {
// if (e.key === 'Enter') {
// e.preventDefault()
// const query = $(e.target).val();
// Sefaria.mongoSearch(query)
// }

}
render() {
const inputClasses = classNames({
Expand Down
14 changes: 12 additions & 2 deletions static/js/ReaderApp.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class ReaderApp extends Component {
// Currently these get generated in reader/views.py then regenerated again in ReaderApp.
this.MIN_PANEL_WIDTH = 360.0;
let panels = [];

if (props.initialMenu) {
// If a menu is specified in `initialMenu`, make a panel for it
panels[0] = {
Expand Down Expand Up @@ -120,6 +120,7 @@ class ReaderApp extends Component {
initialAnalyticsTracked: false,
showSignUpModal: false,
translationLanguagePreference: props.translationLanguagePreference,
mongoSearchText: null
};
}
makePanelState(state) {
Expand Down Expand Up @@ -922,6 +923,7 @@ toggleSignUpModal(modalContentKind = SignUpModalKind.Default) {
}

handleNavigationClick(ref, currVersions, options) {
console.log("reeee ref ", ref, currVersions, options)
this.openPanel(ref, currVersions, options);
}
handleSegmentClick(n, ref, sheetNode) {
Expand Down Expand Up @@ -1659,13 +1661,20 @@ toggleSignUpModal(modalContentKind = SignUpModalKind.Default) {
}
this.setSinglePanelState(state);
}
showSearch(searchQuery) {
async searchmongoText(chapterQuery, titleQuery="" ) {
this.setState({
mongoSearchText: await Sefaria.mongoSearch(chapterQuery, titleQuery)
})

}
async showSearch(searchQuery) {
let panel;
const textSearchState = (!!this.state.panels && this.state.panels.length && !!this.state.panels[0].textSearchState) ? this.state.panels[0].textSearchState.update({ filtersValid: false }) : new SearchState({ type: 'text' });
const sheetSearchState = (!!this.state.panels && this.state.panels.length && !!this.state.panels[0].sheetSearchState) ? this.state.panels[0].sheetSearchState.update({ filtersValid: false }) : new SearchState({ type: 'sheet' });

const searchTab = !!this.state.panels && this.state.panels.length ? this.state.panels[0].searchTab : "text";
this.setSinglePanelState({mode: "Menu", menuOpen: "search", searchQuery, searchTab, textSearchState, sheetSearchState });
await this.searchmongoText(searchQuery)
}
searchInCollection(searchQuery, collection) {
let panel;
Expand Down Expand Up @@ -2107,6 +2116,7 @@ toggleSignUpModal(modalContentKind = SignUpModalKind.Default) {
var classes = classNames({readerPanelBox: 1, sidebar: panel.mode == "Connections"});
panels.push(<div className={classes} style={style} key={key}>
<ReaderPanel
mongoSearchText={this.state.mongoSearchText}
panelPosition={i}
initialState={panel}
interfaceLang={this.props.interfaceLang}
Expand Down
6 changes: 5 additions & 1 deletion static/js/ReaderPanel.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ import {ContentText} from "./ContentText";
class ReaderPanel extends Component {
constructor(props) {
super(props);

let state = this.clonePanel(props.initialState);
state["initialAnalyticsTracked"] = false;
state.width = this.props.multiPanel ? 1000 : 500; // Assume we're in a small panel not using multipanel
Expand All @@ -56,6 +55,9 @@ class ReaderPanel extends Component {
this.readerContentRef = React.createRef();
}
componentDidMount() {
// this.props.mongoSearchText.then(data => {
// console.log("datat: ", data)
// })
window.addEventListener("resize", this.setWidth);
this.setWidth();
if (this.props.panelPosition) { //Focus on the first focusable element of the newly loaded panel. Mostly for a11y
Expand Down Expand Up @@ -893,6 +895,7 @@ class ReaderPanel extends Component {

} else if (this.state.menuOpen === "search" && this.state.searchQuery) {
menu = (<SearchPage
mongoSearchText= {this.props.mongoSearchText}
key={"searchPage"}
interfaceLang={this.props.interfaceLang}
query={this.state.searchQuery}
Expand Down Expand Up @@ -1164,6 +1167,7 @@ class ReaderPanel extends Component {
}
}
ReaderPanel.propTypes = {
mongoSearchText: PropTypes.object,
initialState: PropTypes.object,
interfaceLang: PropTypes.string,
setCentralState: PropTypes.func,
Expand Down
1 change: 1 addition & 0 deletions static/js/SearchPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class SearchPage extends Component {
query={this.props.query}
tab={this.props.tab}
compare={this.props.compare}
mongoSearchText={this.props.mongoSearchText}
textSearchState={this.props.textSearchState}
sheetSearchState={this.props.sheetSearchState}
onResultClick={this.props.onResultClick}
Expand Down
76 changes: 56 additions & 20 deletions static/js/SearchResultList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ class SearchResultList extends Component {
pagesLoaded: this._typeObjDefault(0),
hits: this._typeObjDefault([]),
error: false,
topics: []
topics: [],
}

// Load search results from cache so they are available for immediate render
Expand Down Expand Up @@ -171,6 +171,7 @@ class SearchResultList extends Component {
});
}
}

async addRefTopic(topic) {
const book = await Sefaria.getIndexDetails(topic.key);
return {
Expand Down Expand Up @@ -398,7 +399,7 @@ class SearchResultList extends Component {
const request_applied = filtersValid && appliedFilters;
const { aggregation_field_array, aggregation_field_lang_suffix_array } = SearchState.metadataByType[type];
const aggregationsToUpdate = this._getAggsToUpdate(filtersValid, aggregation_field_array, aggregation_field_lang_suffix_array, appliedFilterAggTypes, type);

return {
query: props.query,
type,
Expand Down Expand Up @@ -455,29 +456,62 @@ class SearchResultList extends Component {
const { tab } = this.props;
const searchState = this._getSearchState(tab);
let results = [];
let textResults = []

if (tab === "text") {
results = Sefaria.search.mergeTextResultsVersions(this.state.hits.text);
results = results.filter(result => !!result._source.version).map(result =>
<SearchTextResult
data={result}
query={this.props.query}
key={result._id}
searchInBook={this.props.searchInBook}
onResultClick={this.props.onResultClick} />
);
// results = Sefaria.search.mergeTextResultsVersions(this.state.hits.text);
if(this.props.mongoSearchText && this.props.mongoSearchText.status == "success"){
results = this.props.mongoSearchText.result.map(result =>
result.matchingChapters.map((chapter, i) => {

const data = {
title: result.title,
ref: `${result.title}.${chapter.index}`,
heRef: `${result.versionTitle}.${chapter.index}`,
lang: result.language,
chapter: chapter.chapter,
version: result.versionTitle,

}
return (
<SearchTextResult
key={i}
data={data}
query={this.props.query}
searchInBook={this.props.searchInBook}
onResultClick={this.props.onResultClick}
/>
)
})
);
}

// results = results.filter(result => !!result._source.version).map(result =>
// <SearchTextResult
// data={mongoSearchedText}
// query={this.props.query}
// searchInBook={this.props.searchInBook}
// onResultClick={this.props.onResultClick} />
// );
// mongoSearchedText.result.map(text => {
// <SearchTextResult
// data={text}
// query={this.props.query}
// searchInBook={this.props.searchInBook}
// onResultClick={this.props.onResultClick} />
// } )
if (this.state.topics.length > 0) {
let topics = this.state.topics.map(t => {
Sefaria.track.event("Search", "topic in search display", t.analyticCat+"|"+t.title);
return <SearchTopic topic={t}/>
});
if (results.length > 0) {
topics = <div id="searchTopics">{topics}</div>
results.splice(2, 0, topics);
}
else {
results = topics;
}
// if (results.length > 0) {
// topics = <div id="searchTopics">{topics}</div>
// results.splice(2, 0, topics);
// }
// else {
// results = topics;
// }
}


Expand Down Expand Up @@ -520,8 +554,10 @@ class SearchResultList extends Component {
nFilters={searchState.appliedFilters.length} />}
</div>
<div className="searchResultList">
{ queryFullyLoaded || haveResults ? results : null }
{ this.state.isQueryRunning[tab] ? loadingMessage : null }
{/* { queryFullyLoaded || haveResults ? results : null } */}
{ results.length > 0 ? results : null }
{/* { this.state.isQueryRunning[tab] ? loadingMessage : null } */}
{ results.length == 0 ? loadingMessage : null }
</div>
</div>
);
Expand Down
Loading

0 comments on commit af81532

Please sign in to comment.