leetcode_tui_core/content/question.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
pub(super) mod sol_dir;
mod stats;
use crate::SendError;
use crate::{emit, utils::Paginate};
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use leetcode_core::graphql::query::{daily_coding_challenge, RunOrSubmitCodeCheckResult};
use leetcode_core::types::run_submit_response::display::CustomDisplay;
use leetcode_core::types::run_submit_response::ParsedResponse;
use leetcode_core::{
GQLLeetcodeRequest, QuestionContentRequest, RunCodeRequest, SubmitCodeRequest,
};
use leetcode_tui_config::log;
use leetcode_tui_db::{DbQuestion, DbTopic};
use leetcode_tui_shared::layout::Window;
pub(crate) use sol_dir::init;
use sol_dir::SOLUTION_FILE_MANAGER;
use stats::Stats;
use std::rc::Rc;
pub struct Questions {
paginate: Paginate<Rc<DbQuestion>>,
ques_haystack: Vec<Rc<DbQuestion>>,
needle: Option<String>,
matcher: SkimMatcherV2,
show_stats: bool,
adhoc_question: Option<Rc<DbQuestion>>,
}
impl Default for Questions {
fn default() -> Self {
Self {
paginate: Paginate::new(vec![]),
needle: Default::default(),
ques_haystack: vec![],
matcher: Default::default(),
show_stats: Default::default(),
adhoc_question: Default::default(),
}
}
}
impl Questions {
pub fn prev_ques(&mut self) -> bool {
self.paginate.prev_elem(self.widget_height())
}
pub fn next_ques(&mut self) -> bool {
self.paginate.next_elem(self.widget_height())
}
pub fn rand_ques(&mut self) -> bool {
self.paginate.rand_elem(self.widget_height())
}
pub fn window(&self) -> &[Rc<DbQuestion>] {
self.paginate.window(self.widget_height())
}
pub fn hovered(&self) -> Option<&Rc<DbQuestion>> {
if self.adhoc_question.is_some() {
return self.adhoc_question.as_ref();
}
self.paginate.hovered()
}
pub fn unset_adhoc(&mut self) -> bool {
self.adhoc_question.take();
true
}
pub fn set_adhoc(&mut self, question: DbQuestion) {
self.adhoc_question = Some(Rc::new(question));
}
fn widget_height(&self) -> usize {
let window = Window::default();
let height = window.root.center_layout.question.inner.height;
height as usize
}
}
impl Questions {
pub fn get_questions_by_topic(&mut self, topic: DbTopic) {
tokio::spawn(async move {
let questions = topic.fetch_questions();
if let Ok(_questions) = questions.emit_if_error() {
emit!(Questions(_questions));
}
});
}
pub fn show_question_content(&self) -> bool {
if let Some(_hovered) = self.hovered() {
let slug = _hovered.title_slug.clone();
let title = _hovered.title.clone();
tokio::spawn(async move {
let qc = QuestionContentRequest::new(slug);
if let Ok(content) = qc.send().await.emit_if_error() {
let lines = content
.data
.question
.html_to_text()
.lines()
.map(|l| l.to_string())
.collect::<Vec<String>>();
emit!(Popup(title, lines));
}
});
} else {
log::debug!("hovered question is none");
}
true
}
pub fn run_solution(&self) -> bool {
self._run_solution(false)
}
pub fn submit_solution(&self) -> bool {
self._run_solution(true)
}
fn _run_solution(&self, is_submit: bool) -> bool {
if let Some(_hovered) = self.hovered() {
let mut cloned_quest = _hovered.as_ref().clone();
let id = _hovered.id.to_string();
if let Ok(lang_refs) = SOLUTION_FILE_MANAGER
.get()
.unwrap()
.read()
.unwrap()
.get_available_languages(id.as_str())
.emit_if_error()
{
let cloned_langs = lang_refs.iter().map(|v| v.to_string()).collect();
tokio::spawn(async move {
if let Some(selected_lang) =
emit!(SelectPopup("Available solutions in", cloned_langs)).await
{
let selected_sol_file = SOLUTION_FILE_MANAGER
.get()
.unwrap()
.read()
.unwrap()
.get_solution_file(id.as_str(), selected_lang)
.cloned();
if let Ok(f) = selected_sol_file.emit_if_error() {
if let Ok(contents) = f.read_contents().await.emit_if_error() {
let lang = f.language;
let request = if is_submit {
SubmitCodeRequest::new(
lang,
f.question_id,
contents,
f.title_slug,
)
.poll_check_response()
.await
} else {
let mut run_code_req = RunCodeRequest::new(
lang,
None,
f.question_id,
contents,
f.title_slug,
);
if let Err(e) = run_code_req
.set_sample_test_cases_if_none()
.await
.emit_if_error()
{
log::info!(
"error while setting the sample testcase list {}",
e
);
return;
} else {
run_code_req.poll_check_response().await
}
};
if let Ok(response) = request.emit_if_error() {
if let Ok(update_result) =
cloned_quest.mark_attempted().emit_if_error()
{
// when solution is just run against sample cases
if update_result.is_some() {
// fetches latest result from db
emit!(QuestionUpdate);
}
}
if is_submit {
let is_submission_accepted =
matches!(response, ParsedResponse::SubmitAccepted(..));
if is_submission_accepted {
if let Ok(update_result) =
cloned_quest.mark_accepted().emit_if_error()
{
// when solution is accepted
if update_result.is_some() {
// fetches latest result from db
emit!(QuestionUpdate);
}
};
}
}
emit!(Popup(response.get_display_lines()));
}
}
}
}
});
}
}
false
}
pub fn solve_for_language(&self) -> bool {
if let Some(_hovered) = self.hovered() {
let slug = _hovered.title_slug.clone();
tokio::spawn(async move {
if let Ok(editor_data) = leetcode_core::EditorDataRequest::new(slug)
.send()
.await
.emit_if_error()
{
if let Some(selected) = emit!(SelectPopup(
"Select Language",
editor_data
.get_languages()
.iter()
.map(|l| l.to_string())
.collect()
))
.await
{
let selected_lang = editor_data.get_languages()[selected];
let editor_content = editor_data.get_editor_data_by_language(selected_lang);
if let Ok(file_name) =
editor_data.get_filename(selected_lang).emit_if_error()
{
if let Some(e_data) = editor_content {
if let Ok(written_path) = SOLUTION_FILE_MANAGER
.get()
.unwrap()
.write()
.unwrap()
.create_solution_file(file_name.as_str(), e_data)
.emit_if_error()
{
emit!(Open(written_path));
}
};
};
} else {
log::info!("quitting popup unselected");
}
}
});
}
false
}
pub fn set_questions(&mut self, questions: Vec<DbQuestion>) {
self.ques_haystack = questions.into_iter().map(Rc::new).collect();
self.filter_questions();
}
pub fn add_question(&mut self, question: DbQuestion) {
self.ques_haystack.push(Rc::new(question));
}
pub fn toggle_daily_question(&self) -> bool {
tokio::spawn(async move {
let daily_challenge_question = daily_coding_challenge::Query::new()
.send()
.await
.emit_if_error()
.unwrap();
let mut db_question: DbQuestion = daily_challenge_question
.data
.active_daily_coding_challenge_question
.question
.try_into()
.emit_if_error()
.unwrap();
db_question.save_to_db().unwrap();
emit!(AdhocQuestion(db_question));
// emit!(AddQuestions(vec![db_question.clone()]));
});
false
}
}
impl Questions {
pub fn toggle_search(&mut self) -> bool {
let existing_needle = self.needle.clone();
tokio::spawn(async move {
let mut rx = emit!(Input(existing_needle));
while let Some(maybe_needle) = rx.recv().await {
if let Some(needle) = maybe_needle {
emit!(QuestionFilter(Some(needle)));
} else {
break;
}
}
});
false
}
pub fn filter_by(&mut self, string: Option<String>) {
if self.needle != string {
self.needle = string;
self.filter_questions();
}
}
fn filter_questions(&mut self) {
let fil_quests = if let Some(needle) = self.needle.as_ref() {
let quests: Vec<Rc<DbQuestion>> = self
.ques_haystack
.iter()
.filter(|q| {
let search_string = format!(
"{} {} {}", // id, topics, title
q.id,
q.topics
.iter()
.map(|t| t.slug.as_str())
.collect::<Vec<&str>>()
.join(", "),
q.title
);
self.matcher
.fuzzy_match(search_string.as_str(), &needle)
.is_some()
})
.cloned()
.collect();
quests
} else {
self.ques_haystack.clone()
};
self.paginate.update_list(fil_quests);
}
}
impl Questions {
pub fn get_stats(&self) -> Stats<'_> {
Stats::new(&self.ques_haystack)
}
pub fn toggle_stats(&mut self) -> bool {
self.show_stats = !self.show_stats;
true
}
pub fn is_stats_visible(&self) -> bool {
self.show_stats
}
}