@use "sass:meta";
@use "sass:string";

$_kendo-svg-escaped-characters: (
    ("%", "%25"),
    ("<", "%3c"),
    (">", "%3e"),
    ("#", "%23"),
    ("(", "%28"),
    (")", "%29")
) !default;

$_kendo-escape-class-name: (
    ".": "\\.",
    "/": "\\/"
);


/// Returns a copy of `$string` with all occurrences of `$search`
/// replaced by `$replace`.
/// @param {String} $string - The string to process.
/// @param {String} $search - The substring to look for.
/// @param {String} $replace - The replacement string.
/// @return {String} - The resulting string.
///
/// @link https://www.sassmeister.com/gist/1b4f2da5527830088e4d
///
/// @example scss - Usage
///   @debug k-string-replace( "foo bar", "bar", "baz" ); // => "foo baz"
@function k-string-replace( $string, $search, $replace: "" ) {
    @if meta.type-of( $string ) == number {
        $string: $string + "";
    }

    $index: string.index( $string, $search );

    @if $index {
        @return string.slice( $string, 1, $index - 1 ) + $replace + k-string-replace( string.slice( $string, $index + string.length( $search ) ), $search, $replace );
    }

    @return $string;
}

// See https://www.sassmeister.com/gist/1b4f2da5527830088e4d
@function str-replace($string, $search, $replace: "") {
    $index: string.index($string, $search);

    @if $index {
        @return string.slice($string, 1, $index - 1) + $replace + str-replace(string.slice($string, $index + string.length($search)), $search, $replace);
    }

    @return $string;
}

// See https://codepen.io/kevinweber/pen/dXWoRw
@function k-escape-svg($string) {
    @if string.index($string, "data:image/svg+xml") {
        @each $char, $encoded in $_kendo-svg-escaped-characters {
            // Do not escape the url brackets
            @if string.index($string, "url(") == 1 {
                $string: url("#{k-string-replace(string.slice($string, 6, -3), $char, $encoded)}");
            } @else {
                $string: k-string-replace($string, $char, $encoded);
            }
        }
    }

    @return $string;
}

/// Escapes special characters in a class name
/// @param {String} $text - The string to escape
/// @return {String} - The escaped string
@function k-escape-class-name( $text ) {
    $_text: $text;

    @each $char, $rep in $_kendo-escape-class-name {
        $_text: k-string-replace( $_text, string.unquote( $char ), string.unquote( $rep ) );
    }

    @return $_text;
}
