sea-orm-sluggable 0.1.1

Unique, transliterated slugs for SeaORM entities
Documentation
use crate::transliterate::{AnyAscii, Transliterator};

type SuffixFn = Box<dyn Fn(&str, u32) -> String + Send + Sync>;

/// How slugs are built: separator, length, suffix numbering and transliteration.
///
/// ```
/// use sea_orm_sluggable::SlugOptions;
///
/// let options = SlugOptions::default().separator("_").max_length(100);
/// ```
pub struct SlugOptions {
    separator: String,
    max_length: usize,
    suffix_start: u32,
    suffix_on_first: bool,
    suffix: Option<SuffixFn>,
    reserved: Vec<String>,
    transliterator: Box<dyn Transliterator>,
}

impl Default for SlugOptions {
    fn default() -> Self {
        Self {
            separator: "-".to_string(),
            max_length: 250,
            suffix_start: 1,
            suffix_on_first: false,
            suffix: None,
            reserved: Vec::new(),
            transliterator: Box::new(AnyAscii),
        }
    }
}

impl SlugOptions {
    /// Joins words and the uniqueness suffix. Default: `-`.
    #[must_use]
    pub fn separator(mut self, separator: &str) -> Self {
        self.separator = separator.to_string();
        self
    }

    /// Cuts the slug before a uniqueness suffix is added, so the final value
    /// can be a few characters longer. Default: 250.
    #[must_use]
    pub const fn max_length(mut self, max_length: usize) -> Self {
        self.max_length = max_length;
        self
    }

    /// First number used when a slug is taken: `title-1` by default,
    /// `title-2` with `suffix_start(2)`.
    #[must_use]
    pub const fn suffix_start(mut self, suffix_start: u32) -> Self {
        self.suffix_start = suffix_start;
        self
    }

    /// Adds a suffix even to the first slug: `title-1`, `title-2`, ...
    /// instead of `title`, `title-1`, ... Default: off.
    #[must_use]
    pub const fn suffix_on_first(mut self, suffix_on_first: bool) -> Self {
        self.suffix_on_first = suffix_on_first;
        self
    }

    /// Replaces the numeric suffix. Gets the base slug and the attempt number
    /// (starting at [`suffix_start`](Self::suffix_start)) and returns the part
    /// that goes after the separator. It must eventually return something new,
    /// or the uniqueness search never ends.
    ///
    /// ```
    /// use sea_orm_sluggable::SlugOptions;
    ///
    /// // title-v1, title-v2, ...
    /// let options = SlugOptions::default().suffix_with(|_slug, attempt| format!("v{attempt}"));
    /// ```
    #[must_use]
    pub fn suffix_with(
        mut self,
        suffix: impl Fn(&str, u32) -> String + Send + Sync + 'static,
    ) -> Self {
        self.suffix = Some(Box::new(suffix));
        self
    }

    /// Slugs that must never be used, typically words your routes already
    /// take: with `reserved(["new"])` a post titled "New" gets `new-1`, so it
    /// cannot shadow `/posts/new`. Compared case-insensitively. Default: none.
    ///
    /// ```
    /// use sea_orm_sluggable::SlugOptions;
    ///
    /// let options = SlugOptions::default().reserved(["new", "edit", "feed"]);
    /// ```
    #[must_use]
    pub fn reserved<I, S>(mut self, words: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.reserved = words
            .into_iter()
            .map(|word| word.as_ref().to_lowercase())
            .collect();
        self
    }

    /// Replaces the default [`AnyAscii`] transliteration.
    #[must_use]
    pub fn transliterator(mut self, transliterator: impl Transliterator + 'static) -> Self {
        self.transliterator = Box::new(transliterator);
        self
    }

    pub(crate) fn separator_str(&self) -> &str {
        &self.separator
    }

    pub(crate) const fn max_len(&self) -> usize {
        self.max_length
    }

    pub(crate) const fn first_suffix(&self) -> u32 {
        self.suffix_start
    }

    pub(crate) const fn always_suffix(&self) -> bool {
        self.suffix_on_first
    }

    pub(crate) fn is_reserved(&self, slug: &str) -> bool {
        self.reserved
            .iter()
            .any(|word| word.eq_ignore_ascii_case(slug))
    }

    pub(crate) fn to_ascii(&self, text: &str) -> String {
        self.transliterator.transliterate(text)
    }

    /// `base` plus the separator and the suffix for this attempt.
    /// `base`, the separator and the suffix for `attempt`, with `base` shortened so
    /// the whole slug still fits `max_length`.
    pub(crate) fn with_suffix(&self, base: &str, attempt: u32) -> String {
        let suffix = self
            .suffix
            .as_ref()
            .map_or_else(|| attempt.to_string(), |make| make(base, attempt));
        let room = self
            .max_length
            .saturating_sub(self.separator.len() + suffix.len());
        let short = crate::text::cut(base.to_string(), room, &self.separator);
        let base = if short.is_empty() {
            base
        } else {
            short.as_str()
        };
        format!("{base}{}{suffix}", self.separator)
    }

    pub(crate) const fn has_default_suffix(&self) -> bool {
        self.suffix.is_none()
    }
}