From 85ed7eda9490077c2af96ea01643e07e70770b6c Mon Sep 17 00:00:00 2001 From: "alonso.torres" Date: Wed, 25 Nov 2026 17:28:37 +0100 Subject: [PATCH] :bug: Keep readings from spreading to typed text Typed text always went into an existing span and took its reading and warichu note with it: selecting all and typing, deleting everything and typing again, or typing right after a reading extended it to the new characters. Text typed at either edge of a reading or warichu note now goes to the neighbouring plain span, or to a new span with the same style and no annotation. Inside a reading, including between spans that share one, it keeps the reading. A span emptied by a deletion or an Enter at its edge drops its annotation, and overtype at the end of a reading replaces the text after it. The editor export marks those spans with `d`, and the frontend drops their `:ruby`, `:ruby-group` and `:warichu` when it merges the content. Readings WASM does not draw, hidden ones or those the text language leaves out, reach it as flag 8, so typed text stays out of them too. AI-assisted-by: claude-opus-5-5 --- .../app/common/render_wasm/text_content.cljs | 16 +- .../src/app/common/types/text/cjk_layout.cljc | 12 +- common/test/common_tests/types/text_test.cljc | 5 +- frontend/src/app/render_wasm/text_editor.cljs | 20 +- .../render_wasm/texts_test.cljs | 26 ++ render-wasm/src/shapes/text.rs | 46 +++ render-wasm/src/wasm/text.rs | 33 ++- render-wasm/src/wasm/text/helpers.rs | 276 ++++++++++++++++-- render-wasm/src/wasm/text_editor.rs | 9 +- 9 files changed, 397 insertions(+), 46 deletions(-) diff --git a/common/src/app/common/render_wasm/text_content.cljs b/common/src/app/common/render_wasm/text_content.cljs index 85babbeaf8..af01cbde9e 100644 --- a/common/src/app/common/render_wasm/text_content.cljs +++ b/common/src/app/common/render_wasm/text_content.cljs @@ -84,6 +84,15 @@ "" (d/nilv (:ruby span) ""))) +(defn- unshown-annotation? + "True when `span` annotates its text with a reading or warichu note that + is not drawn: a hidden reading, or one its language does not render + (`cjk/active-content`)." + [span] + (or (true? (::cjk/unshown-annotation span)) + (and (true? (:ruby-hidden span)) + (cjk/ruby-span? span)))) + (defn- encode-text "Into an UTF8 buffer. Returns an ArrayBuffer instance." [text] @@ -196,10 +205,13 @@ (mem/write-u8 dview ruby-align) (mem/write-u8 dview ruby-overhang) ;; Bit 1 selects Zhuyin; bit 2 joins the span to the reading of - ;; the span before it (`cjk/ruby-groups`). + ;; the span before it (`cjk/ruby-groups`); bit 3 marks a reading + ;; or warichu note that is not drawn: hidden (`span-ruby` leaves + ;; it out) or not rendered in the text language. (mem/write-u8 dview (bit-or ruby-side (if (true? (:ruby-zhuyin span)) 2 0) - (if (cjk/ruby-joins-previous? previous span) 4 0))) + (if (cjk/ruby-joins-previous? previous span) 4 0) + (if (unshown-annotation? span) 8 0))) ;; Use the former padding bytes; the span header stays the same size. (mem/write-u8 dview emphasis-position) (mem/write-u8 dview underline-position) diff --git a/common/src/app/common/types/text/cjk_layout.cljc b/common/src/app/common/types/text/cjk_layout.cljc index 65956d1f21..07d429b8d8 100644 --- a/common/src/app/common/types/text/cjk_layout.cljc +++ b/common/src/app/common/types/text/cjk_layout.cljc @@ -372,13 +372,23 @@ node (get language-dependent-attrs level)))) +(defn- active-span + "`span` with the CJK attrs of its language `family` only. A span whose + reading or warichu note is left out gets `::unshown-annotation`: the + annotation still belongs to its text, so typed text stays out of it." + [span family] + (let [active (keep-language-attrs span family :span)] + (cond-> active + (and (annotated-span? span) (not (annotated-span? active))) + (assoc ::unshown-annotation true)))) + (defn- active-paragraph [paragraph] (let [language (:text-language paragraph) family (language-family language)] (cond-> (-> paragraph (d/update-when :children - (partial mapv #(keep-language-attrs % family :span))) + (partial mapv #(active-span % family))) (keep-language-attrs family :paragraph)) (some? language) (assoc :text-language language) diff --git a/common/test/common_tests/types/text_test.cljc b/common/test/common_tests/types/text_test.cljc index 871c1b8c36..cccca024d0 100644 --- a/common/test/common_tests/types/text_test.cljc +++ b/common/test/common_tests/types/text_test.cljc @@ -607,7 +607,8 @@ (t/is (not (contains? paragraph :text-orientation))) (t/is (= "left" (:text-align paragraph))) (t/is (not (contains? paragraph :korean-wrap))) - (t/is (= {:text "日本"} (first (:children paragraph)))) + ;; The reading and note stay with their text, which the editor needs. + (t/is (= {:text "日本" ::cjk/unshown-annotation true} (first (:children paragraph)))) (t/is (not (contains? active :line-adjustment))) (t/is (nil? (cjk/active-writing-mode content))) (t/is (= content (cjk-content {})) "the stored content keeps every attr"))) @@ -627,7 +628,7 @@ (span active))) (t/is (not (contains? active :line-adjustment)))) (let [active (cjk/active-content (cjk-content {:text-language "ko"}))] - (t/is (= {:text "日本"} (span active))) + (t/is (= {:text "日本" ::cjk/unshown-annotation true} (span active))) (t/is (= "keep-words" (:korean-wrap (first-paragraph active)))) (t/is (= "vertical-rl" (:writing-mode (first-paragraph active))))))) diff --git a/frontend/src/app/render_wasm/text_editor.cljs b/frontend/src/app/render_wasm/text_editor.cljs index 8a55f46fa4..9ccbb06aeb 100644 --- a/frontend/src/app/render_wasm/text_editor.cljs +++ b/frontend/src/app/render_wasm/text_editor.cljs @@ -722,8 +722,10 @@ `:pp` tracks paragraph attrs independently of span styling, including when a merge removes all the surviving paragraph's original characters. + `:d` marks a span that takes the style of its source span but not its + reading or warichu note (`cjk/text-content-attrs`). - exported vector of paragraphs, each a vector of `{:pp 0 :p 0 :s 0 :t \"text\"}` + exported vector of paragraphs, each a vector of `{:pp 0 :p 0 :s 0 :d false :t \"text\"}` content existing Penpot content map (root -> paragraph-set -> …)" [content exported] (let [para-set (first (get content :children)) @@ -740,11 +742,14 @@ last-orig-para)) styling-span - (fn [orig-para span-idx {:keys [p s]}] - (or (get-in orig-paras [p :children s]) - (get-in orig-para [:children span-idx]) - (-> orig-para :children last) - template-span)) + (fn [orig-para span-idx {:keys [p s d]}] + (let [span (or (get-in orig-paras [p :children s]) + (get-in orig-para [:children span-idx]) + (-> orig-para :children last) + template-span)] + (if (true? d) + (apply dissoc span cjk/text-content-attrs) + span))) new-paras (mapv (fn [para-idx spans] @@ -758,7 +763,8 @@ spans) ;; A paragraph with no spans is dropped on the way ;; back to WASM (and fails the content schema). - [(assoc (or template-span {}) :text "")])))) + [(-> (apply dissoc template-span cjk/text-content-attrs) + (assoc :text ""))])))) (range (count exported)) exported) new-para-set (assoc para-set :children new-paras)] diff --git a/frontend/test/frontend_tests/render_wasm/texts_test.cljs b/frontend/test/frontend_tests/render_wasm/texts_test.cljs index 45574850b0..5eaadf2c35 100644 --- a/frontend/test/frontend_tests/render_wasm/texts_test.cljs +++ b/frontend/test/frontend_tests/render_wasm/texts_test.cljs @@ -470,6 +470,32 @@ ;; A stored nil reading sends no bytes, as an absent one does. (t/is (= 0 (ruby-length (serialized-span {:text "日" :ruby nil})))))) +(t/deftest write-spans-flags-annotations-that-are-not-drawn + (let [hidden-bit #(bit-and 8 (span-byte (serialized-span %) :ruby-side))] + (t/is (= 8 (hidden-bit {:text "日" :ruby "にち" :ruby-hidden true}))) + (t/is (= 0 (hidden-bit {:text "日" :ruby "にち" :ruby-hidden false}))) + ;; Without a reading there is nothing hidden. + (t/is (= 0 (hidden-bit {:text "日" :ruby "" :ruby-hidden true}))) + ;; A reading or note the text language does not render. + (t/is (= 8 (hidden-bit {:text "日" ::cjk/unshown-annotation true}))))) + +(t/deftest merged-spans-flagged-by-wasm-drop-their-reading-and-warichu + (let [content (editor-content [{:text "漢字" :ruby "かんじ" :ruby-group "g1" + :ruby-size "quarter" :font-weight "700"} + {:text "注" :warichu "warichu"}]) + result (text-editor/merge-exported-texts-into-content + content [[{:p 0 :s 0 :d false :t "漢字"} + {:p 0 :s 0 :d true :t "X"} + {:p 0 :s 1 :d true :t "Y"}]]) + spans (get-in result [:children 0 :children 0 :children])] + (t/is (= ["漢字" "X" "Y"] (mapv :text spans))) + (t/is (= ["かんじ" nil nil] (mapv :ruby spans))) + (t/is (= ["g1" nil nil] (mapv :ruby-group spans))) + (t/is (not-any? #(contains? % :warichu) spans)) + ;; Style, including how a reading would look, stays. + (t/is (= ["700" "700"] (mapv :font-weight (take 2 spans)))) + (t/is (= "quarter" (:ruby-size (nth spans 1)))))) + (t/deftest write-spans-serializes-counted-digits-tcy (let [dview (serialized-span {:text "平成31年" :text-combine-upright "digits2"})] (t/is (= 3 (span-byte dview :text-combine-upright))))) diff --git a/render-wasm/src/shapes/text.rs b/render-wasm/src/shapes/text.rs index 2ffe341d13..a13898096b 100644 --- a/render-wasm/src/shapes/text.rs +++ b/render-wasm/src/shapes/text.rs @@ -633,6 +633,16 @@ impl TextContent { } } + /// Clears `TextSpan::annotations_dropped` once the host has been told; + /// the layout does not depend on it. + pub fn clear_dropped_annotations(&mut self) { + for paragraph in &mut self.paragraphs { + for span in &mut paragraph.children { + span.annotations_dropped = false; + } + } + } + pub fn paragraphs(&self) -> &[Paragraph] { &self.paragraphs } @@ -2585,6 +2595,10 @@ pub struct TextSpan { /// Ruby (furigana) annotation for this span; empty means no ruby. pub ruby: String, pub ruby_zhuyin: bool, + /// The span has a reading or warichu note the host does not draw: a + /// hidden reading, or one the text language does not render. `ruby` and + /// `warichu` do not hold it then. + pub hidden_annotation: bool, /// The span continues the reading of the span before it: the frontend /// gives the spans of one reading the same group, so their text forms /// one base (`Paragraph::ruby_groups`). @@ -2595,6 +2609,9 @@ pub struct TextSpan { pub ruby_side: AnnotationSide, /// Warichu (割注): two half-size lines stacked in one column position. pub warichu: bool, + /// The editor removed the span's reading or warichu note, which the host + /// still holds for the span this one takes its style from. + pub annotations_dropped: bool, pub font_features: FontFeatures, pub annotation_clearance: AnnotationClearance, pub fills: Vec, @@ -2624,12 +2641,14 @@ impl Default for TextSpan { text_underline_position: TextUnderlinePosition::default(), ruby: String::default(), ruby_zhuyin: false, + hidden_annotation: false, ruby_joins_previous: false, ruby_size: RubySize::default(), ruby_align: RubyAlign::default(), ruby_overhang: RubyOverhang::default(), ruby_side: AnnotationSide::default(), warichu: false, + annotations_dropped: false, font_features: FontFeatures::default(), annotation_clearance: AnnotationClearance::default(), fills: vec![], @@ -2699,6 +2718,33 @@ impl TextSpan { !self.warichu && !self.ruby_text().is_empty() } + /// True when the span annotates its own text with a reading or is a + /// warichu note, drawn or not. Both belong to the span's characters. + pub fn is_annotated(&self) -> bool { + self.warichu || self.hidden_annotation || !self.ruby_text().is_empty() + } + + /// Removes the reading and warichu note, keeping the style, and flags the + /// span so the host removes them too. + pub fn drop_annotations(&mut self) { + if !self.is_annotated() { + return; + } + self.ruby.clear(); + self.hidden_annotation = false; + self.ruby_joins_previous = false; + self.warichu = false; + self.annotations_dropped = true; + } + + /// An empty span with this style and no reading or warichu note. + pub fn unannotated_copy(&self) -> Self { + let mut span = self.clone(); + span.set_text(String::new()); + span.drop_annotations(); + span + } + /// True when this span continues the reading of `previous`, the span /// before it: it joins that reading and shows the same one, so their text /// forms one base whose first span sets the presentation. Neighbours with diff --git a/render-wasm/src/wasm/text.rs b/render-wasm/src/wasm/text.rs index a0b06d855f..a598c9d628 100644 --- a/render-wasm/src/wasm/text.rs +++ b/render-wasm/src/wasm/text.rs @@ -149,7 +149,9 @@ pub struct RawTextSpan { ruby_size: u8, ruby_align: u8, ruby_overhang: u8, - /// Bit 0: over/under side of normal ruby. Bit 1: Zhuyin. + /// Bit 0: over/under side of normal ruby. Bit 1: Zhuyin. Bit 2: joins + /// the previous span's reading. Bit 3: the span has a reading or + /// warichu note that is not drawn. ruby_flags: u8, text_emphasis_position: u8, text_underline_position: u8, @@ -226,10 +228,11 @@ impl From for shapes::TextSpan { span.ruby_size = RawRubySize::from(value.ruby_size).into(); span.ruby_align = RawRubyAlign::from(value.ruby_align).into(); span.ruby_overhang = RawRubyOverhang::from(value.ruby_overhang).into(); - // Bit 2 joins the span to the reading of the span before it, bit 1 - // selects Zhuyin and bit 0 retains the existing over/under side. - // Reject unknown flags instead of treating corrupt bytes as Zhuyin. - let ruby_flags = if value.ruby_flags <= 7 { + // Bit 3 marks an annotation that is not drawn, bit 2 joins the span + // to the reading of the span before it, bit 1 selects Zhuyin and bit 0 + // retains the existing over/under side. Reject unknown flags instead + // of treating corrupt bytes as Zhuyin. + let ruby_flags = if value.ruby_flags <= 15 { value.ruby_flags } else { 0 @@ -237,6 +240,7 @@ impl From for shapes::TextSpan { span.ruby_side = RawRubySide::from(ruby_flags & 1).into(); span.ruby_zhuyin = ruby_flags & 2 != 0; span.ruby_joins_previous = ruby_flags & 4 != 0; + span.hidden_annotation = ruby_flags & 8 != 0; span } } @@ -549,14 +553,16 @@ mod tests { /// layouts. #[test] fn zhuyin_flags_keep_legacy_side_and_header_size() { - for (flags, zhuyin, side, joins) in [ - (0, false, AnnotationSide::Over, false), - (1, false, AnnotationSide::Under, false), - (2, true, AnnotationSide::Over, false), - (3, true, AnnotationSide::Under, false), - (4, false, AnnotationSide::Over, true), - (5, false, AnnotationSide::Under, true), - (255, false, AnnotationSide::Over, false), + for (flags, zhuyin, side, joins, hidden) in [ + (0, false, AnnotationSide::Over, false, false), + (1, false, AnnotationSide::Under, false, false), + (2, true, AnnotationSide::Over, false, false), + (3, true, AnnotationSide::Under, false, false), + (4, false, AnnotationSide::Over, true, false), + (5, false, AnnotationSide::Under, true, false), + (8, false, AnnotationSide::Over, false, true), + (13, false, AnnotationSide::Under, true, true), + (255, false, AnnotationSide::Over, false, false), ] { let mut bytes = [0u8; std::mem::size_of::()]; bytes[13] = flags; @@ -564,6 +570,7 @@ mod tests { assert_eq!(span.ruby_zhuyin, zhuyin); assert_eq!(span.ruby_side, side); assert_eq!(span.ruby_joins_previous, joins); + assert_eq!(span.hidden_annotation, hidden); } } diff --git a/render-wasm/src/wasm/text/helpers.rs b/render-wasm/src/wasm/text/helpers.rs index 0360998c74..881a7d4cb0 100644 --- a/render-wasm/src/wasm/text/helpers.rs +++ b/render-wasm/src/wasm/text/helpers.rs @@ -1,4 +1,4 @@ -use crate::shapes::{Paragraph, TextContent, TextDirection, TextPositionWithAffinity}; +use crate::shapes::{Paragraph, TextContent, TextDirection, TextPositionWithAffinity, TextSpan}; use crate::state::TextSelection; /// Get total character count in a paragraph. @@ -373,11 +373,12 @@ pub fn insert_text_at_cursor( } if children.len() == 1 && children[0].text.is_empty() { + children[0].drop_annotations(); children[0].set_text(text.to_string()); return Some(text.chars().count()); } - let (span_idx, offset_in_span) = find_text_span_at_offset(para, cursor.offset)?; + let (span_idx, offset_in_span) = insertion_point(para, cursor.offset)?; let children = para.children_mut(); let span = &mut children[span_idx]; @@ -395,6 +396,50 @@ pub fn insert_text_at_cursor( Some(cursor.offset + text.chars().count()) } +/// Span and offset in it where text typed at `char_offset` goes. A reading or +/// warichu note belongs to the text it annotates, so typed text joins it only +/// inside its base: at either edge it goes into the unannotated neighbour on +/// that side, or into a new unannotated span with the same style. +pub fn insertion_point(para: &mut Paragraph, char_offset: usize) -> Option<(usize, usize)> { + let (span_idx, offset_in_span) = find_text_span_at_offset(para, char_offset)?; + let children = para.children_mut(); + let span = &children[span_idx]; + let span_len = span.text.chars().count(); + + if !span.is_annotated() || (offset_in_span > 0 && offset_in_span < span_len) { + return Some((span_idx, offset_in_span)); + } + + if span_len == 0 { + children[span_idx].drop_annotations(); + return Some((span_idx, 0)); + } + + if offset_in_span == span_len { + return match children.get(span_idx + 1) { + Some(next) if next.shares_ruby_base_with(span) => Some((span_idx, offset_in_span)), + Some(next) if !next.is_annotated() => Some((span_idx + 1, 0)), + _ => { + let plain = span.unannotated_copy(); + children.insert(span_idx + 1, plain); + Some((span_idx + 1, 0)) + } + }; + } + + match span_idx.checked_sub(1).map(|idx| &children[idx]) { + Some(previous) if span.shares_ruby_base_with(previous) => Some((span_idx, 0)), + Some(previous) if !previous.is_annotated() => { + Some((span_idx - 1, previous.text.chars().count())) + } + _ => { + let plain = span.unannotated_copy(); + children.insert(span_idx, plain); + Some((span_idx, 0)) + } + } +} + /// Replace text at cursor position (overtype mode). Replaces N characters where N is the /// length of the input text, returning the new cursor offset. pub fn replace_text_at_cursor( @@ -419,11 +464,19 @@ pub fn replace_text_at_cursor( } if children.len() == 1 && children[0].text.is_empty() { + children[0].drop_annotations(); children[0].set_text(text.to_string()); return Some(text_len); } - let (span_idx, offset_in_span) = find_text_span_at_offset(para, cursor.offset)?; + // At the end of a span there is nothing of it to replace, so the text + // goes where an insertion would. + let (span_idx, offset_in_span) = match find_text_span_at_offset(para, cursor.offset)? { + (idx, offset) if offset == para.children()[idx].text.chars().count() => { + insertion_point(para, cursor.offset)? + } + found => found, + }; let children = para.children_mut(); let span = &mut children[span_idx]; @@ -476,13 +529,19 @@ pub fn delete_selection_range(text_content: &mut TextContent, selection: &TextSe paragraphs.drain((start.paragraph + 1)..=end_paragraph); - let children = paragraphs[start.paragraph].children_mut(); - let has_content = children.iter().any(|span| !span.text.is_empty()); - if has_content { - children.retain(|span| !span.text.is_empty()); - } else if children.len() > 1 { - children.truncate(1); - } + drop_empty_spans(paragraphs[start.paragraph].children_mut()); + } +} + +/// Removes the empty spans of a paragraph. One that is left with no text +/// keeps its first span as a placeholder, without its reading or warichu +/// note: the text typed next takes its style but not those. +fn drop_empty_spans(children: &mut Vec) { + if children.iter().any(|span| !span.text.is_empty()) { + children.retain(|span| !span.text.is_empty()); + } else if let Some(placeholder) = children.first_mut() { + placeholder.drop_annotations(); + children.truncate(1); } } @@ -557,12 +616,7 @@ pub fn delete_range_in_paragraph(para: &mut Paragraph, start_offset: usize, end_ } } - let has_content = children.iter().any(|span| !span.text.is_empty()); - if has_content { - children.retain(|span| !span.text.is_empty()); - } else if !children.is_empty() { - children.truncate(1); - } + drop_empty_spans(children); } /// Delete the character before the cursor. Returns the new cursor position. @@ -798,9 +852,7 @@ pub fn split_paragraph_at_cursor( } if new_para_children.is_empty() { - let mut empty_span = current_span.clone(); - empty_span.set_text(String::new()); - new_para_children.push(empty_span); + new_para_children.push(current_span.unannotated_copy()); } let text_align = para.text_align(); @@ -826,6 +878,7 @@ pub fn split_paragraph_at_cursor( let new_text: String = text.chars().take(offset_in_span).collect(); span.set_text(new_text); } + drop_empty_spans(children); let mut new_para = crate::shapes::Paragraph::new( text_align, @@ -1048,4 +1101,189 @@ mod tests { delete_selection_range(&mut content, &selection((0, 0), (5, 99))); assert_eq!(text_of(&content), ""); } + + fn reading(text: &str, ruby: &str) -> TextSpan { + TextSpan { + ruby: ruby.to_string(), + ..span(text) + } + } + + /// Text and reading of each span of paragraph `index`. + fn spans_of(content: &TextContent, index: usize) -> Vec<(String, String)> { + content.paragraphs()[index] + .children() + .iter() + .map(|span| (span.text.clone(), span.ruby.clone())) + .collect() + } + + fn pairs(expected: &[(&str, &str)]) -> Vec<(String, String)> { + expected + .iter() + .map(|(text, ruby)| (text.to_string(), ruby.to_string())) + .collect() + } + + fn type_at(content: &mut TextContent, paragraph: usize, offset: usize, text: &str) { + insert_text_with_newlines(content, &caret(paragraph, offset), text); + } + + #[test] + fn text_typed_over_a_whole_reading_drops_it() { + let mut content = content(vec![Paragraph::new( + TextAlign::Left, + TextDirection::LTR, + None, + None, + 1.2, + 0.0, + vec![reading("漢字", "かんじ"), span("です")], + )]); + delete_selection_range(&mut content, &selection((0, 0), (0, 4))); + type_at(&mut content, 0, 0, "テスト"); + assert_eq!(spans_of(&content, 0), pairs(&[("テスト", "")])); + assert!(content.paragraphs()[0].children()[0].annotations_dropped); + } + + #[test] + fn text_typed_after_deleting_a_reading_drops_it() { + let mut content = content(vec![Paragraph::new( + TextAlign::Left, + TextDirection::LTR, + None, + None, + 1.2, + 0.0, + vec![reading("漢字", "かんじ")], + )]); + let cursor = delete_char_before(&mut content, &caret(0, 2)).unwrap(); + delete_char_before(&mut content, &cursor); + assert_eq!(spans_of(&content, 0), pairs(&[("", "")])); + type_at(&mut content, 0, 0, "テスト"); + assert_eq!(spans_of(&content, 0), pairs(&[("テスト", "")])); + } + + fn reading_paragraph(spans: Vec) -> TextContent { + content(vec![Paragraph::new( + TextAlign::Left, + TextDirection::LTR, + None, + None, + 1.2, + 0.0, + spans, + )]) + } + + #[test] + fn text_typed_after_a_reading_joins_the_next_plain_span() { + let mut content = reading_paragraph(vec![reading("漢字", "かんじ"), span("です")]); + type_at(&mut content, 0, 2, "X"); + assert_eq!( + spans_of(&content, 0), + pairs(&[("漢字", "かんじ"), ("Xです", "")]) + ); + } + + #[test] + fn text_typed_at_the_edges_of_a_reading_gets_its_own_span() { + let mut content = reading_paragraph(vec![reading("漢字", "かんじ")]); + type_at(&mut content, 0, 2, "X"); + type_at(&mut content, 0, 0, "Y"); + assert_eq!( + spans_of(&content, 0), + pairs(&[("Y", ""), ("漢字", "かんじ"), ("X", "")]) + ); + let spans = content.paragraphs()[0].children(); + assert!(spans[0].annotations_dropped && spans[2].annotations_dropped); + assert!(!spans[1].annotations_dropped); + } + + #[test] + fn text_typed_between_two_readings_stays_out_of_both() { + let mut content = reading_paragraph(vec![ + reading("漢字", "かんじ"), + reading("東京", "とうきょう"), + ]); + type_at(&mut content, 0, 2, "X"); + assert_eq!( + spans_of(&content, 0), + pairs(&[("漢字", "かんじ"), ("X", ""), ("東京", "とうきょう")]) + ); + } + + #[test] + fn text_typed_inside_a_reading_base_keeps_it() { + let mut content = reading_paragraph(vec![reading("漢字", "かんじ")]); + type_at(&mut content, 0, 1, "X"); + assert_eq!(spans_of(&content, 0), pairs(&[("漢X字", "かんじ")])); + + // Between two spans of one reading the caret is inside its base. + let joined = TextSpan { + ruby_joins_previous: true, + ..reading("字", "かんじ") + }; + let mut content = reading_paragraph(vec![reading("漢", "かんじ"), joined]); + type_at(&mut content, 0, 1, "X"); + assert_eq!( + spans_of(&content, 0), + pairs(&[("漢X", "かんじ"), ("字", "かんじ")]) + ); + } + + #[test] + fn text_typed_after_an_undrawn_annotation_or_warichu_stays_out() { + for annotated in [ + TextSpan { + hidden_annotation: true, + ..span("漢字") + }, + TextSpan { + warichu: true, + ..span("注記") + }, + ] { + let mut content = reading_paragraph(vec![annotated]); + type_at(&mut content, 0, 2, "X"); + let spans = content.paragraphs()[0].children(); + assert_eq!(spans.len(), 2); + assert!(spans[0].is_annotated()); + assert!(!spans[1].is_annotated() && spans[1].annotations_dropped); + assert_eq!(spans[1].text, "X"); + } + } + + #[test] + fn overtyping_at_the_end_of_a_reading_replaces_the_next_text() { + let mut content = reading_paragraph(vec![reading("漢字", "かんじ"), span("です")]); + replace_text_with_newlines(&mut content, &caret(0, 2), "X"); + assert_eq!( + spans_of(&content, 0), + pairs(&[("漢字", "かんじ"), ("Xす", "")]) + ); + } + + #[test] + fn a_new_paragraph_never_starts_inside_a_reading() { + let mut content = reading_paragraph(vec![reading("漢字", "かんじ")]); + assert!(split_paragraph_at_cursor(&mut content, &caret(0, 2))); + assert_eq!(spans_of(&content, 1), pairs(&[("", "")])); + + let mut content = reading_paragraph(vec![reading("漢字", "かんじ")]); + assert!(split_paragraph_at_cursor(&mut content, &caret(0, 0))); + assert_eq!(spans_of(&content, 0), pairs(&[("", "")])); + assert_eq!(spans_of(&content, 1), pairs(&[("漢字", "かんじ")])); + } + + #[test] + fn clearing_dropped_annotations_unmarks_every_span() { + let mut content = reading_paragraph(vec![reading("漢字", "かんじ")]); + type_at(&mut content, 0, 2, "X"); + content.clear_dropped_annotations(); + assert!(content.paragraphs()[0] + .children() + .iter() + .all(|span| !span.annotations_dropped)); + } } diff --git a/render-wasm/src/wasm/text_editor.rs b/render-wasm/src/wasm/text_editor.rs index a6c66b9723..6b9d9dc2cd 100644 --- a/render-wasm/src/wasm/text_editor.rs +++ b/render-wasm/src/wasm/text_editor.rs @@ -1030,11 +1030,14 @@ pub extern "C" fn text_editor_export_content() -> *mut u8 { .replace('\n', "\\n") .replace('\r', "\\r") .replace('\t', "\\t"); + // `d` asks the host to drop the reading and warichu note of + // the span this one takes its style from. span_parts.push(format!( - "{{\"pp\":{},\"p\":{},\"s\":{},\"t\":\"{}\"}}", + "{{\"pp\":{},\"p\":{},\"s\":{},\"d\":{},\"t\":\"{}\"}}", para.source_position(), span.paragraph_position, span.span_position, + span.annotations_dropped, escaped_text )); } @@ -1043,8 +1046,10 @@ pub extern "C" fn text_editor_export_content() -> *mut u8 { let json = format!("[{}]", json_parts.join(",")); // The host rebuilds its content tree out of this JSON, so the current - // positions are what the next call has to report against. + // positions are what the next call has to report against, and the + // dropped annotations are gone from it. text_content.reset_span_positions(); + text_content.clear_dropped_annotations(); let mut bytes = json.into_bytes(); bytes.push(0);