mgui-core 0.6.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! Grapheme cluster 边界工具 —— 编辑器/输入框的选择、删除、左右移动共用同一套边界。
//!
//! 0.6 Text 2.0:此前 `mgui-editor` 用 `chars()` 做列转换,emoji ZWJ(如 👨‍👩‍👧‍👦)、
//! 组合记号(如 `e\u{301}`)会被拆到两个字符之间,光标停在字形内部、退格拆散 emoji。
//! 这里提供以 **grapheme cluster** 为单位的字节边界,与 `unicode-segmentation` 对齐。
//!
//! 约定:`column` 指「第 N 个 grapheme 的起始字节偏移」,行尾 = `text.len()`。
//! 所有函数对非法字节偏移向下取整到最近合法边界,绝不 panic。

use unicode_segmentation::UnicodeSegmentation;

/// 返回 `text` 中所有 grapheme 簇的起始字节偏移,末尾追加 `text.len()`。
/// 空串返回 `[0]`。
pub fn grapheme_byte_offsets(text: &str) -> Vec<usize> {
    let mut offsets: Vec<usize> = text.grapheme_indices(true).map(|(i, _)| i).collect();
    offsets.push(text.len());
    offsets
}

/// grapheme 列 → 字节偏移。`col` 超出簇数时返回 `text.len()`。
pub fn grapheme_col_to_byte(text: &str, col: usize) -> usize {
    let offsets = grapheme_byte_offsets(text);
    offsets.get(col).copied().unwrap_or(text.len())
}

/// 字节偏移 → grapheme 列(向下取整到簇起点)。越界返回簇数。
pub fn byte_to_grapheme_col(text: &str, byte: usize) -> usize {
    let offsets = grapheme_byte_offsets(text);
    let byte = byte.min(text.len());
    match offsets.binary_search(&byte) {
        Ok(col) => col,
        Err(next) => next.saturating_sub(1),
    }
}

/// 把任意字节偏移向下取整到 grapheme 簇起点;越界返回 `text.len()`。
///
/// 与 `prev_grapheme_boundary` 的区别:末尾偏移保持末尾,不会回退到最后一个簇起点。
pub fn floor_grapheme_boundary(text: &str, byte: usize) -> usize {
    grapheme_col_to_byte(text, byte_to_grapheme_col(text, byte))
}

/// 光标左移一个 grapheme(返回新字节偏移)。已在起点则原地不动。
pub fn prev_grapheme_boundary(text: &str, byte: usize) -> usize {
    let offsets = grapheme_byte_offsets(text);
    let byte = byte.min(text.len());
    match offsets.binary_search(&byte) {
        Ok(0) | Err(0) => 0,
        Ok(col) => offsets[col - 1],
        Err(next) => offsets[next - 1],
    }
}

/// 光标右移一个 grapheme(返回新字节偏移)。已在末尾则原地不动。
pub fn next_grapheme_boundary(text: &str, byte: usize) -> usize {
    let offsets = grapheme_byte_offsets(text);
    let byte = byte.min(text.len());
    match offsets.binary_search(&byte) {
        Ok(col) => offsets.get(col + 1).copied().unwrap_or(text.len()),
        Err(next) => offsets.get(next).copied().unwrap_or(text.len()),
    }
}

/// grapheme 簇数量(等于光标可停靠的位置数 - 1)。
pub fn grapheme_count(text: &str) -> usize {
    text.graphemes(true).count()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ascii_is_unchanged() {
        let t = "hello";
        assert_eq!(grapheme_count(t), 5);
        assert_eq!(grapheme_col_to_byte(t, 2), 2);
        assert_eq!(byte_to_grapheme_col(t, 3), 3);
        assert_eq!(prev_grapheme_boundary(t, 3), 2);
        assert_eq!(next_grapheme_boundary(t, 3), 4);
    }

    #[test]
    fn emoji_zwj_is_one_grapheme() {
        let family = "👨‍👩‍👧‍👦";
        let t = format!("A{family}B");
        let offsets = grapheme_byte_offsets(&t);
        assert_eq!(offsets.len(), 4, "A + family + B + end = 4 个边界");
        assert_eq!(offsets[2] - offsets[1], family.len(), "ZWJ 序列整体是一个簇");
        assert_eq!(grapheme_count(&t), 3);
        // 光标落在 ZWJ 序列中间时,左右移动都跳到「所在簇」的起止边界,不落在簇内部
        let middle = offsets[1] + 2;
        assert_eq!(prev_grapheme_boundary(&t, middle), offsets[1]);
        assert_eq!(next_grapheme_boundary(&t, middle), offsets[2]);
    }

    #[test]
    fn combining_mark_stays_with_base() {
        let t = "e\u{301}x"; // é (e + combining acute) + x
        assert_eq!(grapheme_count(t), 2);
        assert_eq!(grapheme_col_to_byte(t, 1), "e\u{301}".len());
        assert_eq!(byte_to_grapheme_col(t, 1), 0, "落在组合记号中间向下取整到基字");
    }

    #[test]
    fn out_of_range_is_clamped() {
        let t = "你好";
        assert_eq!(grapheme_col_to_byte(t, 99), t.len());
        assert_eq!(byte_to_grapheme_col(t, 99), 2);
        assert_eq!(prev_grapheme_boundary(t, 0), 0);
        assert_eq!(next_grapheme_boundary(t, t.len()), t.len());
    }

    #[test]
    fn empty_text_has_single_boundary() {
        assert_eq!(grapheme_byte_offsets(""), vec![0]);
        assert_eq!(grapheme_count(""), 0);
        assert_eq!(grapheme_col_to_byte("", 3), 0);
    }

    #[test]
    fn floor_boundary_keeps_end_position() {
        let t = "e\u{301}x";
        assert_eq!(floor_grapheme_boundary(t, 1), 0, "组合记号中间向下取整到基字");
        assert_eq!(floor_grapheme_boundary(t, t.len()), t.len(), "末尾不应回退到最后一个簇起点");
        assert_eq!(floor_grapheme_boundary(t, 99), t.len());
    }
}