Truncate#
Operations / Transform / Truncate
Can Read
Cannot Write
Description#
Shortens a text that exceeds a maximum length and appends a suffix at its end
Parameters#
| Name | Description |
|---|---|
| Text | The text that is shortened when it is too long |
| Max Length | The maximum amount of characters of the resulting text, suffix included |
| Suffix | The text appended when the value is shortened |
Code#
using System;
using UnityEngine;
using VisualScript.Icons;
namespace VisualScript.Runtime
{
[Get]
[Title("Truncate")]
[Category("Operations/Transform/Truncate")]
[Description("Shortens a text that exceeds a maximum length and appends a suffix at its end")]
[Image(typeof(IconClamp), ColorTheme.Type.Yellow)]
[Parameter("Text", "The text that is shortened when it is too long")]
[Parameter("Max Length", "The maximum amount of characters of the resulting text, suffix included")]
[Parameter("Suffix", "The text appended when the value is shortened")]
[Keywords("Ellipsis", "Cut", "Shorten", "Clamp", "Limit", "Text")]
[Serializable]
public class TypeStringTruncate : TypeString
{
[SerializeField] private GetString m_Text = new GetString();
[SerializeField] private GetInteger m_MaxLength = new GetInteger(10);
[SerializeField] private GetString m_Suffix = new GetString("...");
public override string GetPreview(GameObject source) => Truncate(
this.m_Text.GetPreview(source),
(int) this.m_MaxLength.GetPreview(source),
this.m_Suffix.GetPreview(source)
);
public override string Get(Args args) => Truncate(
this.m_Text.Get(args),
this.m_MaxLength.GetInt(args),
this.m_Suffix.Get(args)
);
private static string Truncate(string text, int maxLength, string suffix)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
if (maxLength <= 0) return string.Empty;
if (text.Length <= maxLength) return text;
suffix ??= string.Empty;
if (suffix.Length >= maxLength) return suffix.Substring(0, maxLength);
return string.Concat(text.Substring(0, maxLength - suffix.Length), suffix);
}
public override string ToString()
{
return $"Truncate {this.m_Text} to {this.m_MaxLength}";
}
protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
}
}