Skip to main content

sea_orm_sluggable/
config.rs

1use crate::transliterate::{AnyAscii, Transliterator};
2
3type SuffixFn = Box<dyn Fn(&str, u32) -> String + Send + Sync>;
4
5/// How slugs are built: separator, length, suffix numbering and transliteration.
6///
7/// ```
8/// use sea_orm_sluggable::SlugOptions;
9///
10/// let options = SlugOptions::default().separator("_").max_length(100);
11/// ```
12pub struct SlugOptions {
13    separator: String,
14    max_length: usize,
15    suffix_start: u32,
16    suffix_on_first: bool,
17    suffix: Option<SuffixFn>,
18    reserved: Vec<String>,
19    transliterator: Box<dyn Transliterator>,
20}
21
22impl Default for SlugOptions {
23    fn default() -> Self {
24        Self {
25            separator: "-".to_string(),
26            max_length: 250,
27            suffix_start: 1,
28            suffix_on_first: false,
29            suffix: None,
30            reserved: Vec::new(),
31            transliterator: Box::new(AnyAscii),
32        }
33    }
34}
35
36impl SlugOptions {
37    /// Joins words and the uniqueness suffix. Default: `-`.
38    #[must_use]
39    pub fn separator(mut self, separator: &str) -> Self {
40        self.separator = separator.to_string();
41        self
42    }
43
44    /// Cuts the slug before a uniqueness suffix is added, so the final value
45    /// can be a few characters longer. Default: 250.
46    #[must_use]
47    pub const fn max_length(mut self, max_length: usize) -> Self {
48        self.max_length = max_length;
49        self
50    }
51
52    /// First number used when a slug is taken: `title-1` by default,
53    /// `title-2` with `suffix_start(2)`.
54    #[must_use]
55    pub const fn suffix_start(mut self, suffix_start: u32) -> Self {
56        self.suffix_start = suffix_start;
57        self
58    }
59
60    /// Adds a suffix even to the first slug: `title-1`, `title-2`, ...
61    /// instead of `title`, `title-1`, ... Default: off.
62    #[must_use]
63    pub const fn suffix_on_first(mut self, suffix_on_first: bool) -> Self {
64        self.suffix_on_first = suffix_on_first;
65        self
66    }
67
68    /// Replaces the numeric suffix. Gets the base slug and the attempt number
69    /// (starting at [`suffix_start`](Self::suffix_start)) and returns the part
70    /// that goes after the separator. It must eventually return something new,
71    /// or the uniqueness search never ends.
72    ///
73    /// ```
74    /// use sea_orm_sluggable::SlugOptions;
75    ///
76    /// // title-v1, title-v2, ...
77    /// let options = SlugOptions::default().suffix_with(|_slug, attempt| format!("v{attempt}"));
78    /// ```
79    #[must_use]
80    pub fn suffix_with(
81        mut self,
82        suffix: impl Fn(&str, u32) -> String + Send + Sync + 'static,
83    ) -> Self {
84        self.suffix = Some(Box::new(suffix));
85        self
86    }
87
88    /// Slugs that must never be used, typically words your routes already
89    /// take: with `reserved(["new"])` a post titled "New" gets `new-1`, so it
90    /// cannot shadow `/posts/new`. Compared case-insensitively. Default: none.
91    ///
92    /// ```
93    /// use sea_orm_sluggable::SlugOptions;
94    ///
95    /// let options = SlugOptions::default().reserved(["new", "edit", "feed"]);
96    /// ```
97    #[must_use]
98    pub fn reserved<I, S>(mut self, words: I) -> Self
99    where
100        I: IntoIterator<Item = S>,
101        S: AsRef<str>,
102    {
103        self.reserved = words
104            .into_iter()
105            .map(|word| word.as_ref().to_lowercase())
106            .collect();
107        self
108    }
109
110    /// Replaces the default [`AnyAscii`] transliteration.
111    #[must_use]
112    pub fn transliterator(mut self, transliterator: impl Transliterator + 'static) -> Self {
113        self.transliterator = Box::new(transliterator);
114        self
115    }
116
117    pub(crate) fn separator_str(&self) -> &str {
118        &self.separator
119    }
120
121    pub(crate) const fn max_len(&self) -> usize {
122        self.max_length
123    }
124
125    pub(crate) const fn first_suffix(&self) -> u32 {
126        self.suffix_start
127    }
128
129    pub(crate) const fn always_suffix(&self) -> bool {
130        self.suffix_on_first
131    }
132
133    pub(crate) fn is_reserved(&self, slug: &str) -> bool {
134        self.reserved
135            .iter()
136            .any(|word| word.eq_ignore_ascii_case(slug))
137    }
138
139    pub(crate) fn to_ascii(&self, text: &str) -> String {
140        self.transliterator.transliterate(text)
141    }
142
143    /// `base` plus the separator and the suffix for this attempt.
144    /// `base`, the separator and the suffix for `attempt`, with `base` shortened so
145    /// the whole slug still fits `max_length`.
146    pub(crate) fn with_suffix(&self, base: &str, attempt: u32) -> String {
147        let suffix = self
148            .suffix
149            .as_ref()
150            .map_or_else(|| attempt.to_string(), |make| make(base, attempt));
151        let room = self
152            .max_length
153            .saturating_sub(self.separator.len() + suffix.len());
154        let short = crate::text::cut(base.to_string(), room, &self.separator);
155        let base = if short.is_empty() {
156            base
157        } else {
158            short.as_str()
159        };
160        format!("{base}{}{suffix}", self.separator)
161    }
162
163    pub(crate) const fn has_default_suffix(&self) -> bool {
164        self.suffix.is_none()
165    }
166}