From 6dd56697a64817641f8de863805958c3a7a87eb1 Mon Sep 17 00:00:00 2001 From: hz Date: Thu, 9 Jul 2026 21:42:31 -0500 Subject: [PATCH] Highlight exact selected text ranges --- scripts/ui/question_player.gd | 43 ++++++++++++----------------------- 1 file changed, 15 insertions(+), 28 deletions(-) diff --git a/scripts/ui/question_player.gd b/scripts/ui/question_player.gd index 9cf866c..5fe9874 100644 --- a/scripts/ui/question_player.gd +++ b/scripts/ui/question_player.gd @@ -310,25 +310,30 @@ func _commit_current_text_selection() -> void: var selected_text := stem_label.get_selected_text().strip_edges() if selected_text == "": return - _highlight_text(selected_text) - -func _highlight_text(selected_text: String) -> void: - if selected_text == "": + var selection_start := stem_label.get_selection_from() + var selection_end := stem_label.get_selection_to() + if selection_start == selection_end: return + if selection_start > selection_end: + var previous_start := selection_start + selection_start = selection_end + selection_end = previous_start + _highlight_range(selection_start, selection_end) + + +func _highlight_range(start: int, end: int) -> void: var question_id := str(BlockSessionService.get_current_question().get("id", "")) if not question_highlights.has(question_id): question_highlights[question_id] = [] var highlights: Array = question_highlights[question_id] - var start := _find_available_highlight_start(selected_text, highlights) - if start == -1: - start = stem_plain_text.find(selected_text) - if start == -1: - return + start = clamp(start, 0, stem_plain_text.length()) + end = clamp(end, start, stem_plain_text.length()) + if start == end: + return - var end := start + selected_text.length() if _remove_overlapping_highlights(highlights, start, end): _render_stem() if stem_label.has_method("deselect"): @@ -370,24 +375,6 @@ func _escape_bbcode(value: String) -> String: return value.replace("[", "[lb]").replace("]", "[rb]") -func _find_available_highlight_start(selected_text: String, highlights: Array) -> int: - var search_from := 0 - while search_from < stem_plain_text.length(): - var start := stem_plain_text.find(selected_text, search_from) - if start == -1: - return -1 - var end := start + selected_text.length() - var overlaps := false - for highlight_range in highlights: - if start < int(highlight_range.get("end", 0)) and end > int(highlight_range.get("start", 0)): - overlaps = true - break - if not overlaps: - return start - search_from = start + 1 - return -1 - - func _remove_overlapping_highlights(highlights: Array, start: int, end: int) -> bool: var removed := false for index in range(highlights.size() - 1, -1, -1):