inkferro-core 0.1.0

Layout, text measurement, ANSI render, and frame-diff engine for inkferro — a Rust-backed, byte-for-byte drop-in for the ink terminal UI library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Port of [`slice-ansi@9`](https://github.com/chalk/slice-ansi) to Rust.
//!
//! Slices a string by *visible* column positions while preserving ANSI SGR
//! styling and OSC 8 hyperlinks: styles active at the slice start are re-opened
//! at the start of the result and closed at the end, so the slice renders
//! identically to the corresponding region of the original.
//!
//! This is a faithful port of upstream `index.js` (the slice state machine) on
//! top of [`tokenize_ansi`] (a port of `tokenize-ansi.js`). The tokenizer is
//! slice-ansi's own — distinct from [`crate::text::ansi_tokenize`] and from
//! `wrap_ansi`'s scanner — and lives in its own module because of its size and
//! its load-bearing two-tier grapheme strategy.
//!
//! # Known divergences from JS
//!
//! - **No input preprocessing.** Unlike `wrap_ansi`, slice-ansi does *not*
//!   NFC-normalise or convert `\r\n`. The tokenizer segments the raw string and
//!   intentionally keeps CRLF as one grapheme cluster (UAX29 GB3). This port
//!   preserves that — the input is passed through untouched.
//! - **Astral indexing.** JS indexes strings by UTF-16 code units; this port
//!   indexes by byte offset / Unicode scalar. The two agree on all observable
//!   token boundaries (escape parsing keys off the same scalars), and the
//!   public API works in *visible columns*, which are identical. The only
//!   place the unit choice is observable internally is the slow-path fallback
//!   width for an astral scalar with no grapheme metadata, where JS uses
//!   `value.length` (UTF-16 units = 2); this port matches via `len_utf16`.

mod tokenize_ansi;

use std::collections::BTreeMap;

use tokenize_ansi::{HyperlinkAction, SgrFragment, Token, tokenize_ansi};

/// Slices `input` by visible column range `[start, end)`.
///
/// `end == None` slices to the end of the string. Styles active at `start` are
/// re-opened at the start of the result and closed at the end. A character that
/// straddles `end` (e.g. a fullwidth char whose far half is past `end`) is
/// excluded.
///
/// # Examples
///
/// ```
/// use inkferro_core::text::slice_ansi::slice_ansi;
///
/// assert_eq!(slice_ansi("hello world", 0, Some(5)), "hello");
/// assert_eq!(
///     slice_ansi("\x1b[31mhello\x1b[39m", 1, Some(3)),
///     "\x1b[31mel\x1b[39m"
/// );
/// ```
pub fn slice_ansi(input: &str, start: usize, end: Option<usize>) -> String {
    let tokens = tokenize_ansi(input, end);
    let has_continuation_ahead = create_has_continuation_ahead_map(&tokens);

    let mut params = SliceState::new();

    for (token_index, token) in tokens.iter().enumerate() {
        let mut is_past_end = is_past_end_boundary(token, params.position, end);
        if is_past_end
            && !matches!(token, Token::Character { .. })
            && has_continuation_ahead[token_index]
        {
            is_past_end = false;
        }

        if is_past_end && is_non_continuation_character(token) {
            params.roll_back_at_boundary();
            break;
        }

        params.apply_token(token, is_past_end, start);
    }

    params.finish()
}

/// `activeStyles`: an ordered map from end-code → open-code with JS `Map`
/// semantics. `delete(k)` then `set(k, v)` moves `k` to the end of iteration
/// order; we model that with [`OrderedStyleMap`].
struct OrderedStyleMap {
    /// Insertion-ordered keys (end codes). Reflects current Map iteration order.
    order: Vec<String>,
    /// end-code → open-code.
    values: BTreeMap<String, String>,
}

impl OrderedStyleMap {
    fn new() -> Self {
        Self {
            order: Vec::new(),
            values: BTreeMap::new(),
        }
    }

    fn clear(&mut self) {
        self.order.clear();
        self.values.clear();
    }

    fn delete(&mut self, key: &str) {
        if self.values.remove(key).is_none() {
            return;
        }
        if let Some(pos) = self.order.iter().position(|k| k == key) {
            self.order.remove(pos);
        }
    }

    /// `set(key, value)`. If `key` already present, JS preserves its position;
    /// callers that want "move to end" call `delete` first (matching the JS in
    /// `applySgrFragments` for `start` fragments).
    fn set(&mut self, key: String, value: String) {
        if self.values.insert(key.clone(), value).is_none() {
            self.order.push(key);
        }
    }

    fn has(&self, key: &str) -> bool {
        self.values.contains_key(key)
    }

    fn size(&self) -> usize {
        self.order.len()
    }

    /// `[...map.values()].join('')` — values in iteration order.
    fn values_joined(&self) -> String {
        let mut out = String::new();
        for key in &self.order {
            if let Some(v) = self.values.get(key) {
                out.push_str(v);
            }
        }
        out
    }

    /// `[...map.keys()].toReversed().join('')` — keys reversed.
    fn keys_reversed_joined(&self) -> String {
        let mut out = String::new();
        for key in self.order.iter().rev() {
            out.push_str(key);
        }
        out
    }

    fn snapshot(&self) -> StyleSnapshot {
        StyleSnapshot {
            order: self.order.clone(),
            values: self.values.clone(),
        }
    }

    fn restore(&mut self, snapshot: StyleSnapshot) {
        self.order = snapshot.order;
        self.values = snapshot.values;
    }
}

/// A copy of the active style map (`new Map(activeStyles)`), for rollback.
#[derive(Clone)]
struct StyleSnapshot {
    order: Vec<String>,
    values: BTreeMap<String, String>,
}

/// `applySgrFragments(activeStyles, fragments)`.
fn apply_sgr_fragments(active_styles: &mut OrderedStyleMap, fragments: &[SgrFragment]) {
    for fragment in fragments {
        match fragment {
            SgrFragment::Reset => active_styles.clear(),
            SgrFragment::End { end_code } => active_styles.delete(end_code),
            SgrFragment::Start { code, end_code } => {
                // delete then set → move to end of iteration order.
                active_styles.delete(end_code);
                active_styles.set(end_code.clone(), code.clone());
            }
        }
    }
}

/// An open hyperlink token's data needed to close it / discard it.
#[derive(Clone)]
struct ActiveHyperlink {
    code: String,
    close_prefix: String,
    terminator: String,
}

/// `closeHyperlink(hyperlinkToken)` → `closePrefix + terminator`.
fn close_hyperlink(link: &ActiveHyperlink) -> String {
    format!("{}{}", link.close_prefix, link.terminator)
}

/// `shouldIncludeSgrAfterEnd(token, activeStyles)`.
fn should_include_sgr_after_end(
    fragments: &[SgrFragment],
    active_styles: &OrderedStyleMap,
) -> bool {
    let mut has_start_fragment = false;
    let mut has_closing_effect = false;

    for fragment in fragments {
        match fragment {
            SgrFragment::Start { .. } => has_start_fragment = true,
            SgrFragment::Reset if active_styles.size() > 0 => has_closing_effect = true,
            SgrFragment::End { end_code } if active_styles.has(end_code) => {
                has_closing_effect = true;
            }
            _ => {}
        }
    }

    has_closing_effect && !has_start_fragment
}

/// `hasSgrStartFragment(token)`.
fn has_sgr_start_fragment(fragments: &[SgrFragment]) -> bool {
    fragments
        .iter()
        .any(|f| matches!(f, SgrFragment::Start { .. }))
}

/// The full slice loop's mutable state — mirrors the JS `parameters` object,
/// field-for-field.
struct SliceState {
    active_styles: OrderedStyleMap,
    active_hyperlink: Option<ActiveHyperlink>,
    active_hyperlink_has_visible_text: bool,
    active_hyperlink_output_index: Option<usize>,
    pending_sgr_output_index: Option<usize>,
    pending_sgr_active_styles: Option<StyleSnapshot>,
    position: usize,
    return_value: String,
    include: bool,
}

impl SliceState {
    fn new() -> Self {
        Self {
            active_styles: OrderedStyleMap::new(),
            active_hyperlink: None,
            active_hyperlink_has_visible_text: false,
            active_hyperlink_output_index: None,
            pending_sgr_output_index: None,
            pending_sgr_active_styles: None,
            position: 0,
            return_value: String::new(),
            include: false,
        }
    }

    /// `discardPendingHyperlink(parameters)`.
    fn discard_pending_hyperlink(&mut self) {
        self.splice_out_pending_hyperlink();
        self.active_hyperlink = None;
        self.active_hyperlink_has_visible_text = false;
        self.active_hyperlink_output_index = None;
    }

    /// The body of `discardPendingHyperlink`'s
    /// `if (activeHyperlink && !hasVisibleText && outputIndex !== undefined)`
    /// guard: splice the open hyperlink code out of `return_value` and shift
    /// `pending_sgr_output_index` if it pointed past the removed span.
    fn splice_out_pending_hyperlink(&mut self) {
        // Resolve the three-part JS guard without nesting.
        let Some(link) = &self.active_hyperlink else {
            return;
        };
        if self.active_hyperlink_has_visible_text {
            return;
        }
        let Some(output_index) = self.active_hyperlink_output_index else {
            return;
        };

        let open_code_length = link.code.len();
        // returnValue.slice(0, idx) + returnValue.slice(idx + len)
        let mut new_value = String::with_capacity(self.return_value.len());
        new_value.push_str(&self.return_value[..output_index]);
        new_value.push_str(&self.return_value[output_index + open_code_length..]);
        self.return_value = new_value;

        if self
            .pending_sgr_output_index
            .is_some_and(|p| p > output_index)
        {
            let pending = self.pending_sgr_output_index.expect("checked is_some_and");
            self.pending_sgr_output_index = Some(pending - open_code_length);
        }
    }

    /// The boundary rollback in the main loop's `isPastEnd && character` branch.
    fn roll_back_at_boundary(&mut self) {
        if self.active_hyperlink.is_some() && !self.active_hyperlink_has_visible_text {
            self.discard_pending_hyperlink();
        }

        if let Some(pending) = self.pending_sgr_output_index {
            self.return_value.truncate(pending);
            if let Some(snapshot) = self.pending_sgr_active_styles.take() {
                self.active_styles.restore(snapshot);
            }
            self.pending_sgr_output_index = None;
        }
    }

    fn apply_token(&mut self, token: &Token, is_past_end: bool, start: usize) {
        match token {
            Token::Sgr { code, fragments } => self.apply_sgr_token(code, fragments, is_past_end),
            Token::Hyperlink {
                code,
                action,
                close_prefix,
                terminator,
            } => self.apply_hyperlink_token(code, *action, close_prefix, terminator, is_past_end),
            Token::Control { code } => self.apply_control_token(code, is_past_end),
            Token::Character {
                value,
                visible_width,
                is_grapheme_continuation,
            } => {
                self.apply_character_token(value, *visible_width, *is_grapheme_continuation, start)
            }
        }
    }

    /// `applySgrToken(parameters)`.
    fn apply_sgr_token(&mut self, code: &str, fragments: &[SgrFragment], is_past_end: bool) {
        if is_past_end && !should_include_sgr_after_end(fragments, &self.active_styles) {
            return;
        }

        if self.include
            && has_sgr_start_fragment(fragments)
            && self.pending_sgr_output_index.is_none()
        {
            self.pending_sgr_output_index = Some(self.return_value.len());
            self.pending_sgr_active_styles = Some(self.active_styles.snapshot());
        }

        apply_sgr_fragments(&mut self.active_styles, fragments);
        if self.include {
            self.return_value.push_str(code);
        }
    }

    /// `applyHyperlinkToken(parameters)`.
    fn apply_hyperlink_token(
        &mut self,
        code: &str,
        action: HyperlinkAction,
        close_prefix: &str,
        terminator: &str,
        is_past_end: bool,
    ) {
        if is_past_end && (action != HyperlinkAction::Close || self.active_hyperlink.is_none()) {
            return;
        }

        match action {
            HyperlinkAction::Open => {
                self.active_hyperlink = Some(ActiveHyperlink {
                    code: code.to_owned(),
                    close_prefix: close_prefix.to_owned(),
                    terminator: terminator.to_owned(),
                });
                self.active_hyperlink_has_visible_text = false;
                self.active_hyperlink_output_index = None;
                if self.include {
                    self.active_hyperlink_output_index = Some(self.return_value.len());
                }
            }
            HyperlinkAction::Close => {
                if self.include
                    && self.active_hyperlink.is_some()
                    && !self.active_hyperlink_has_visible_text
                {
                    self.discard_pending_hyperlink();
                    return;
                }
                self.active_hyperlink = None;
                self.active_hyperlink_has_visible_text = false;
                self.active_hyperlink_output_index = None;
            }
        }

        if self.include {
            self.return_value.push_str(code);
        }
    }

    /// `applyControlToken(parameters)`.
    fn apply_control_token(&mut self, code: &str, is_past_end: bool) {
        if !is_past_end && self.include {
            self.return_value.push_str(code);
        }
    }

    /// `applyCharacterToken(parameters)`.
    fn apply_character_token(
        &mut self,
        value: &str,
        visible_width: usize,
        is_grapheme_continuation: bool,
        start: usize,
    ) {
        if !self.include && self.position >= start && !is_grapheme_continuation {
            self.include = true;
            self.return_value = self.active_styles.values_joined();
            if let Some(link) = &self.active_hyperlink {
                self.active_hyperlink_output_index = Some(self.return_value.len());
                let code = link.code.clone();
                self.return_value.push_str(&code);
            }
        }

        if self.include {
            self.return_value.push_str(value);
            self.pending_sgr_output_index = None;
            self.pending_sgr_active_styles = None;
            if self.active_hyperlink.is_some() {
                self.active_hyperlink_has_visible_text = true;
            }
        }

        self.position += visible_width;
    }

    /// The tail of `sliceAnsi`: close any open hyperlink, undo active styles.
    fn finish(mut self) -> String {
        if !self.include {
            return String::new();
        }

        if let Some(link) = &self.active_hyperlink {
            self.return_value.push_str(&close_hyperlink(link));
        }

        self.return_value
            .push_str(&self.active_styles.keys_reversed_joined());
        self.return_value
    }
}

/// `createHasContinuationAheadMap(tokens)`.
fn create_has_continuation_ahead_map(tokens: &[Token]) -> Vec<bool> {
    let mut has_continuation_ahead = vec![false; tokens.len()];
    let mut next_is_continuation = false;

    for token_index in (0..tokens.len()).rev() {
        has_continuation_ahead[token_index] = next_is_continuation;
        if let Token::Character {
            is_grapheme_continuation,
            ..
        } = &tokens[token_index]
        {
            next_is_continuation = *is_grapheme_continuation;
        }
    }

    has_continuation_ahead
}

/// `isPastEndBoundary(token, position, end)`.
fn is_past_end_boundary(token: &Token, position: usize, end: Option<usize>) -> bool {
    let Some(end) = end else {
        return false;
    };

    if position >= end {
        return true;
    }

    matches!(
        token,
        Token::Character {
            is_grapheme_continuation: false,
            visible_width,
            ..
        } if position + visible_width > end
    )
}

/// `token.type === 'character' && !token.isGraphemeContinuation`.
fn is_non_continuation_character(token: &Token) -> bool {
    matches!(
        token,
        Token::Character {
            is_grapheme_continuation: false,
            ..
        }
    )
}

#[cfg(test)]
mod tests;