Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions lib/search/utils/search_result_copy.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:flutter/services.dart';
import 'package:otzaria/core/ui_snack.dart';
import 'package:otzaria/search/utils/snippet_builder.dart';
import 'package:otzaria/settings/settings_exports.dart';
import 'package:otzaria/utils/text/copy_utils.dart';
import 'package:otzaria/utils/text/text_manipulation.dart' as utils;
Expand All @@ -13,14 +14,11 @@ void copySearchResultText({
required String titleText,
required SettingsState settingsState,
}) {
final plainText = utils.stripHtmlPreservingBreaks(
rawHtml,
);
final plainText =
SnippetBuilder.annotatedPlainText(rawHtml) ??
utils.stripHtmlPreservingBreaks(rawHtml);
final bookName = settingsState.replaceHolyNames
? utils.replaceHolyNames(
result.title,
style: settingsState.holyNameStyle,
)
? utils.replaceHolyNames(result.title, style: settingsState.holyNameStyle)
: result.title;
final textToCopy = CopyUtils.formatTextWithHeaders(
originalText: plainText,
Expand All @@ -32,8 +30,6 @@ void copySearchResultText({
reference: titleText,
),
);
Clipboard.setData(
ClipboardData(text: textToCopy),
);
Clipboard.setData(ClipboardData(text: textToCopy));
UiSnack.show(UiSnack.textCopied);
}
194 changes: 183 additions & 11 deletions lib/search/utils/snippet_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ class SnippetBuilder {
_appendHtmlSpans(
body,
style: defaultStyle,
defaultStyle: defaultStyle,
spans: spans,
highlightStyle: highlightStyle,
markStyle: markStyle ?? highlightStyle,
Expand All @@ -85,35 +86,74 @@ class SnippetBuilder {
static void _appendHtmlSpans(
dom.Node node, {
required TextStyle style,
required TextStyle defaultStyle,
required List<InlineSpan> spans,
required TextStyle highlightStyle,
required TextStyle markStyle,
bool highlighted = false,
bool inNote = false,
bool inMarker = false,
}) {
for (final child in node.nodes) {
if (child is dom.Text) {
final text = _collapseWhitespace(child.text);
if (text.isEmpty) continue;
spans.add(TextSpan(text: text, style: style));
spans.add(
TextSpan(
text: text,
style: _annotationStyle(
style,
defaultStyle,
note: inNote,
marker: inMarker,
),
),
);
} else if (child is dom.Element) {
final tag = child.localName;
final opens = !highlighted && _highlightTags.contains(tag);
final opensNote =
tag == 'otzaria-note' &&
!inNote &&
_collapseWhitespace(child.text).trim().isNotEmpty;
final noteStyle = opensNote
? _annotationStyle(defaultStyle, defaultStyle, note: true)
: null;
if (opensNote) spans.add(TextSpan(text: '[הערה: ', style: noteStyle));
_appendHtmlSpans(
child,
style: !opens
? style
: tag == 'mark'
? markStyle
: highlightStyle,
defaultStyle: defaultStyle,
spans: spans,
highlightStyle: highlightStyle,
markStyle: markStyle,
highlighted: highlighted || opens,
inNote: inNote || opensNote,
inMarker: inMarker || tag == 'otzaria-note-marker',
);
if (opensNote) spans.add(TextSpan(text: ']', style: noteStyle));
}
}
}

static TextStyle _annotationStyle(
TextStyle style,
TextStyle defaultStyle, {
bool note = false,
bool marker = false,
}) {
if (!note && !marker) return style;
final size = style.fontSize ?? defaultStyle.fontSize;
return style.copyWith(
fontStyle: note ? FontStyle.italic : style.fontStyle,
fontSize: size == null ? null : size * (marker ? 0.75 : 0.9),
);
}

/// מחלץ את המונחים שהמנוע סימן כהתאמות (תוכן תגי [_highlightTags]) מתוך
/// [html]. משמש להדגשת ההתאמות האמיתיות על גבי דפי PDF.
static Set<String> extractHighlightedTerms(String html) {
Expand Down Expand Up @@ -191,15 +231,32 @@ class SnippetBuilder {
return _collapseWhitespace(body?.text ?? '').trim();
}

/// טקסט ההעתקה עם תוויות הערה; null משאיר תוכן ישן במסלול ההעתקה שלו.
static String? annotatedPlainText(String html) {
if (!html.contains('otzaria-note') ||
html_parser.parse(html).body?.querySelector('otzaria-note') == null) {
return null;
}
return TextSpan(
children: fromHighlightedHtml(
html: html,
defaultStyle: const TextStyle(),
highlightStyle: const TextStyle(),
),
).toPlainText().trim();
}

/// בונה [InlineSpan] מטקסט גולמי [plainText] וטווחי הדגשה [ranges]
/// (זוגות [start, end]). משמש להדגשה עקבית עם פאנל הקריאה בסרגל התוצאות.
/// [sourceHtml] משמר את סימוני ההערות רק כשהטקסט שבו זהה ל-[plainText].
static List<InlineSpan> spansFromRanges({
required String plainText,
required List<List<int>> ranges,
required TextStyle defaultStyle,
required TextStyle highlightStyle,
String? sourceHtml,
}) {
if (plainText.isEmpty || ranges.isEmpty) {
if (plainText.isEmpty) {
return [TextSpan(text: plainText, style: defaultStyle)];
}
final spans = <InlineSpan>[];
Expand All @@ -217,10 +274,7 @@ class SnippetBuilder {
);
}
spans.add(
TextSpan(
text: plainText.substring(start, end),
style: highlightStyle,
),
TextSpan(text: plainText.substring(start, end), style: highlightStyle),
);
position = end;
}
Expand All @@ -229,7 +283,128 @@ class SnippetBuilder {
TextSpan(text: plainText.substring(position), style: defaultStyle),
);
}
return spans;
if (sourceHtml == null || !sourceHtml.contains('otzaria-note')) {
return spans;
}
return _annotateRanges(sourceHtml, plainText, spans, defaultStyle);
}

/// הטווחים נשארים בטקסט המנוע; תווית ההערה נוספת רק אחרי ההדגשה.
static List<InlineSpan> _annotateRanges(
String html,
String plain,
List<InlineSpan> spans,
TextStyle defaultStyle,
) {
final body = html_parser.parse(_withLineBreakMarks(html)).body;
if (body == null) return spans;
final raw = StringBuffer();
final annotations = <({int start, int end, bool marker})>[];
void visit(dom.Node node, {bool inNote = false}) {
if (node is dom.Text) {
raw.write(node.text);
return;
}
final tag = node is dom.Element ? node.localName : null;
final note = tag == 'otzaria-note' && !inNote;
final marker = tag == 'otzaria-note-marker';
final start = raw.length;
for (final child in node.nodes) {
visit(child, inNote: inNote || note);
}
if (note || marker) {
annotations.add((start: start, end: raw.length, marker: marker));
}
}

visit(body);
if (annotations.isEmpty) return spans;

final source = raw.toString();
final offsets = List<int>.filled(source.length + 1, 0);
final normalized = StringBuffer();
var previous = 0;
void appendLiteral(int end) {
final target = normalized.length;
for (var i = previous; i <= end; i++) {
offsets[i] = target + i - previous;
}
normalized.write(source.substring(previous, end));
previous = end;
}

final spaces = RegExp('\\s*$_lineBreakMark\\s*|\\s+');
for (final match in spaces.allMatches(source)) {
appendLiteral(match.start);
normalized.write(match[0]!.contains(_lineBreakMark) ? '\n' : ' ');
for (var i = match.start + 1; i <= match.end; i++) {
offsets[i] = normalized.length;
}
previous = match.end;
}
appendLiteral(source.length);
final untrimmed = normalized.toString();
// טקסט שונה, גם אם אורכו זהה, אינו בסיס בטוח להלבשת טווחי המקור.
if (untrimmed.trim() != plain) return spans;
final leading = untrimmed.length - untrimmed.trimLeft().length;
int mapped(int offset) =>
(offsets[offset] - leading).clamp(0, plain.length);
final mappedAnnotations = [
for (final item in annotations)
if (mapped(item.start) < mapped(item.end))
(
start: mapped(item.start),
end: mapped(item.end),
marker: item.marker,
),
];
final boundaries = <int>{0, plain.length};
final styled = <({int end, TextStyle style})>[];
var position = 0;
for (final span in spans.cast<TextSpan>()) {
position += span.text!.length;
boundaries.add(position);
styled.add((end: position, style: span.style!));
}
for (final item in mappedAnnotations) {
boundaries.addAll([item.start, item.end]);
}
final points = boundaries.toList()..sort();
final result = <InlineSpan>[];
final noteStyle = _annotationStyle(defaultStyle, defaultStyle, note: true);
var styleIndex = 0;
for (var i = 0; i < points.length; i++) {
final start = points[i];
for (final item in mappedAnnotations) {
if (!item.marker && item.end == start) {
result.add(TextSpan(text: ']', style: noteStyle));
}
}
for (final item in mappedAnnotations) {
if (!item.marker && item.start == start) {
result.add(TextSpan(text: '[הערה: ', style: noteStyle));
}
}
if (i == points.length - 1) break;
while (styled[styleIndex].end <= start) {
styleIndex++;
}
final active = mappedAnnotations.where(
(item) => item.start <= start && item.end > start,
);
result.add(
TextSpan(
text: plain.substring(start, points[i + 1]),
style: _annotationStyle(
styled[styleIndex].style,
defaultStyle,
note: active.any((item) => !item.marker),
marker: active.any((item) => item.marker),
),
),
);
}
return result;
}

/// מדגיש הופעות ליטרליות של [query] בטקסט מקומי [plainText].
Expand Down Expand Up @@ -278,10 +453,7 @@ class SnippetBuilder {
}
if (position < plainText.length) {
spans.add(
TextSpan(
text: plainText.substring(position),
style: defaultStyle,
),
TextSpan(text: plainText.substring(position), style: defaultStyle),
);
}
return spans;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import 'semantic_result_item.dart';
if (span is! TextSpan) continue;
final text = span.text ?? '';
plain.write(text);
final isMark = identical(span.style, markStyle);
final isMark = span.style?.fontWeight == markStyle.fontWeight;
if (isMark && inMark) {
matched.last += text;
} else if (isMark) {
Expand Down
9 changes: 4 additions & 5 deletions lib/semantic_search/view/semantic_search_results_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,7 @@ class _SemanticSearchResultsScreenState
void _toggleDimension(String facet) {
final dimensions = FacetHelper.dimensionFacetsOf(_currentFacets);
if (!dimensions.remove(facet)) dimensions.add(facet);
_narrow(
FacetHelper.categoryFacetsOf(_currentFacets),
dimensions..sort(),
);
_narrow(FacetHelper.categoryFacetsOf(_currentFacets), dimensions..sort());
}

/// ספירה לפי קטגוריה של התוצאות שמוצגות כעת.
Expand Down Expand Up @@ -443,7 +440,9 @@ class _SemanticSearchResultsScreenState
String ref,
) {
final plainText = CopyUtils.applyCopyPreferences(
text: utils.stripHtmlIfNeeded(snippetHtml),
text:
SnippetBuilder.annotatedPlainText(snippetHtml) ??
utils.stripHtmlIfNeeded(snippetHtml),
replaceHolyNames: settings.replaceHolyNames,
holyNameStyle: settings.holyNameStyle,
);
Expand Down
1 change: 1 addition & 0 deletions lib/text_book/view/text_book_search_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1104,6 +1104,7 @@ class TextBookSearchViewState extends State<TextBookSearchView>
ranges: ranges,
defaultStyle: defaultStyle,
highlightStyle: highlightStyle,
sourceHtml: snippet,
);
}

Expand Down
Loading
Loading