using System;
using System.Collections.Generic;
using System.Globalization;
using UniWebViewExternal;
using UnityEngine;
///
/// Represents the configuration for the embedded toolbar.
///
/// A config object describes the full toolbar layout: which items appear (back, forward, done, reload, title, or
/// custom buttons), how they are arranged (left, center, right sections), their colors, and title interaction
/// behaviors.
///
/// Use `UniWebViewEmbeddedToolbarConfig.Default` for the standard layout (back + forward on the left, title in the
/// center, done on the right), or construct your own config from scratch. Apply the config by calling
/// `UniWebViewEmbeddedToolbar.ApplyConfig`.
///
[Serializable]
public class UniWebViewEmbeddedToolbarConfig {
///
/// The current config version. Currently `1`.
///
public const int CurrentVersion = 1;
///
/// The prefix used for all built-in item identifiers.
///
public const string BuiltInIdentifierPrefix = "uwv.toolbar.";
///
/// Contains the identifier constants for built-in toolbar items.
///
public static class BuiltInIdentifier {
/// Identifier for the back navigation button.
public const string Back = "uwv.toolbar.back";
/// Identifier for the forward navigation button.
public const string Forward = "uwv.toolbar.forward";
/// Identifier for the done (close) button.
public const string Done = "uwv.toolbar.done";
/// Identifier for the reload button.
public const string Reload = "uwv.toolbar.reload";
/// Identifier for the title item.
public const string Title = "uwv.toolbar.title";
}
///
/// The type of a toolbar item.
///
public enum ItemType {
/// A built-in item with predefined behavior (back, forward, done, reload, title).
BuiltIn,
/// A custom button defined by the user.
Custom
}
///
/// The kind of a built-in toolbar item.
///
public enum BuiltInItemKind {
/// Back navigation button. Default text: "❮".
Back,
/// Forward navigation button. Default text: "❯".
Forward,
/// Done (close) button. Default text: "Done".
Done,
/// Reload button. Default text: "↻".
Reload,
/// Title label displayed in the center section.
Title
}
///
/// Represents a color with RGBA components, each in the range [0, 1].
///
[Serializable]
public class ColorValue {
/// Red component, in the range [0, 1].
public float r;
/// Green component, in the range [0, 1].
public float g;
/// Blue component, in the range [0, 1].
public float b;
/// Alpha component, in the range [0, 1].
public float a;
///
/// Creates a `ColorValue` from a Unity `Color`.
///
/// The Unity color to convert.
/// A new `ColorValue` instance.
public static ColorValue FromColor(Color color) {
return new ColorValue {
r = color.r,
g = color.g,
b = color.b,
a = color.a
};
}
///
/// Converts this `ColorValue` to a Unity `Color`.
///
/// A Unity `Color` instance.
public Color ToColor() {
return new Color(r, g, b, a);
}
}
///
/// Represents the visual style of a toolbar item.
///
[Serializable]
public class ItemStyle {
///
/// The text color of this item. When set, overrides the global `ButtonTextColor` or `TitleTextColor`.
///
public ColorValue TextColor;
}
///
/// Configures interaction behaviors for the built-in Title item.
///
/// You can set `OnTap` to `ScrollToTop` so tapping the title scrolls the web view to the top.
/// You can set `OnLongPress` to `CopyUrl` so long-pressing the title copies the current URL to the clipboard
/// and shows a toast message. The toast text can be customized via `CopyToastText`.
///
[Serializable]
public class TitleInteraction {
///
/// The action to perform when the title item is tapped.
///
public enum TapAction {
/// No action on tap.
None,
/// Scroll the web view content to the top of the page.
ScrollToTop
}
///
/// The action to perform when the title item is long-pressed.
///
public enum LongPressAction {
/// No action on long press.
None,
/// Copy the current page URL to the system clipboard and show a toast.
CopyUrl
}
///
/// The action to perform when the title is tapped. Default is `None`.
///
public TapAction OnTap = TapAction.None;
///
/// The action to perform when the title is long-pressed. Default is `None`.
///
public LongPressAction OnLongPress = LongPressAction.None;
///
/// The toast message text shown after copying the URL. If not set, "URL copied" is used.
/// Only applicable when `OnLongPress` is `CopyUrl`.
///
public string CopyToastText;
}
///
/// Represents a single item in the toolbar. An item is either a built-in item (back, forward, done, reload,
/// title) or a custom button. Use `Item.BuiltIn` or `Item.Custom` factory methods to create items.
///
[Serializable]
public class Item {
/// The type of this item (built-in or custom).
public ItemType Type;
///
/// A unique identifier for this item. Built-in items use `uwv.toolbar.*` identifiers by default.
/// Custom items must provide their own identifier.
///
public string Identifier;
/// Optional per-item visual style. When set, overrides global color settings.
public ItemStyle Style;
/// The kind of built-in item. Only applicable when `Type` is `BuiltIn`.
public BuiltInItemKind? Kind;
///
/// The display text for this item. For built-in items, if not set, a platform default is used.
/// For custom items, this is the button label.
///
public string Title;
///
/// Whether this item is visible. If `null` or `true`, the item is shown. Set to `false` to hide it.
///
public bool? Visible;
///
/// Interaction config for the built-in Title item. Only applicable when `Kind` is `Title`.
///
public TitleInteraction TitleInteraction;
///
/// Creates a built-in toolbar item.
///
/// The kind of built-in item to create.
/// Optional title text override. If `null`, the platform default is used.
/// Optional visibility. If `null`, the item is visible.
/// Optional per-item style override.
/// Optional title interaction config. Only for `Title` items.
/// Optional identifier override. By default uses `uwv.toolbar.*`.
/// A new built-in `Item` instance.
public static Item BuiltIn(
BuiltInItemKind kind,
string title = null,
bool? visible = null,
ItemStyle style = null,
TitleInteraction titleInteraction = null,
string identifier = null
) {
return new Item {
Type = ItemType.BuiltIn,
Kind = kind,
Identifier = string.IsNullOrEmpty(identifier) ? IdentifierForBuiltInKind(kind) : identifier,
Title = title,
Visible = visible,
Style = style,
TitleInteraction = titleInteraction
};
}
///
/// Creates a custom toolbar button.
///
/// A unique identifier for this item. Used to identify it in action callbacks.
/// The button label text.
/// Optional per-item style.
/// A new custom `Item` instance.
public static Item Custom(string identifier, string title, ItemStyle style = null) {
return new Item {
Type = ItemType.Custom,
Identifier = identifier,
Title = title,
Style = style
};
}
///
/// Returns whether this item is visible. An item is visible when `Visible` is `null` or `true`.
///
/// `true` if the item should be displayed.
public bool IsVisible() {
return !Visible.HasValue || Visible.Value;
}
}
///
/// Gets the JSON string representation of the default config.
///
public static string DefaultJson => CreateDefault().ToJson();
///
/// Gets the default toolbar config.
///
/// The default contains: back and forward buttons on the left, a title item in the center, and a done button
/// on the right. Position is `Top`, visibility is `true`, and colors use platform defaults.
///
public static UniWebViewEmbeddedToolbarConfig Default => CreateDefault();
/// The config version. Currently always `1`.
public int Version = CurrentVersion;
/// Whether the toolbar is visible. Default is `true`.
public bool Visible = true;
///
/// The position of the toolbar (`Top` or `Bottom`). Default is `Top`.
/// Only effective on iOS and Android; macOS toolbar is always in the title bar.
///
public UniWebViewToolbarPosition Position = UniWebViewToolbarPosition.Top;
///
/// The maximum height of the toolbar in points. If smaller than the standard height, the toolbar shrinks.
/// Only effective on iOS and Android.
///
public float? MaxHeight;
/// The background color of the toolbar. When `null`, the platform default is used.
public ColorValue BackgroundColor;
///
/// The default text color for toolbar buttons. When `null`, the platform default is used.
/// Individual items can override this via `Item.Style.TextColor`.
///
public ColorValue ButtonTextColor;
///
/// The text color for the title item. When `null`, the platform default is used.
/// The title item can override this via its own `Item.Style.TextColor`.
///
public ColorValue TitleTextColor;
/// Items in the left section. Default: back and forward buttons.
public List Left = new List();
/// Items in the center section. Default: title item.
public List Center = new List();
/// Items in the right section. Default: done button.
public List Right = new List();
///
/// Serializes this config to a JSON string.
///
/// A JSON string representing this config.
public string ToJson() {
return Json.Serialize(ToDictionary());
}
///
/// Converts this config to a dictionary representation.
///
/// A dictionary that can be serialized to JSON.
public Dictionary ToDictionary() {
var dict = new Dictionary {
{ "version", Version },
{ "visible", Visible },
{ "position", SerializePosition(Position) },
{ "maxHeight", MaxHeight.HasValue ? (object)MaxHeight.Value : null },
{ "backgroundColor", SerializeColor(BackgroundColor) },
{ "buttonTextColor", SerializeColor(ButtonTextColor) },
{ "titleTextColor", SerializeColor(TitleTextColor) },
{ "left", SerializeItems(Left) },
{ "center", SerializeItems(Center) },
{ "right", SerializeItems(Right) }
};
return dict;
}
///
/// Creates a config from a JSON string.
///
/// A JSON string representing the toolbar config.
/// A parsed config, or `null` if the JSON is invalid or empty.
public static UniWebViewEmbeddedToolbarConfig FromJson(string json) {
if (string.IsNullOrEmpty(json)) {
return null;
}
try {
var dict = Json.Deserialize(json) as Dictionary;
if (dict == null) {
UniWebViewLogger.Instance.Debug("Embedded toolbar config JSON is not an object.");
return null;
}
return FromDictionary(dict);
} catch (Exception e) {
UniWebViewLogger.Instance.Debug("Failed to parse embedded toolbar config JSON: " + e.Message);
return null;
}
}
///
/// Creates a config from a dictionary.
///
/// A dictionary representing the toolbar config.
/// A parsed config, or `null` if the dictionary is `null`.
public static UniWebViewEmbeddedToolbarConfig FromDictionary(Dictionary dict) {
if (dict == null) {
return null;
}
var config = new UniWebViewEmbeddedToolbarConfig {
Version = ReadInt(dict, "version", CurrentVersion),
Visible = ReadBool(dict, "visible", true),
Position = ParsePosition(ReadString(dict, "position")),
MaxHeight = ReadNullableFloat(dict, "maxHeight"),
BackgroundColor = ReadColor(dict, "backgroundColor"),
ButtonTextColor = ReadColor(dict, "buttonTextColor"),
TitleTextColor = ReadColor(dict, "titleTextColor")
};
config.Left = ReadItems(dict, "left");
config.Center = ReadItems(dict, "center");
config.Right = ReadItems(dict, "right");
return config;
}
///
/// Enumerates all items across all sections (left, center, right) in order.
///
/// An enumerable of all items.
public IEnumerable EnumerateItems() {
foreach (var item in Left) {
yield return item;
}
foreach (var item in Center) {
yield return item;
}
foreach (var item in Right) {
yield return item;
}
}
///
/// Finds the first built-in item matching the given kind across all sections (left, center, right).
///
/// The built-in item kind to search for.
/// The matching item, or `null` if not found.
public Item FindFirstBuiltInItem(BuiltInItemKind kind) {
foreach (var item in EnumerateItems()) {
if (item == null || item.Type != ItemType.BuiltIn || !item.Kind.HasValue) {
continue;
}
if (item.Kind.Value == kind) {
return item;
}
}
return null;
}
private static UniWebViewEmbeddedToolbarConfig CreateDefault() {
return new UniWebViewEmbeddedToolbarConfig {
Version = CurrentVersion,
Visible = true,
Position = UniWebViewToolbarPosition.Top,
MaxHeight = null,
BackgroundColor = null,
ButtonTextColor = null,
TitleTextColor = null,
Left = new List {
Item.BuiltIn(BuiltInItemKind.Back),
Item.BuiltIn(BuiltInItemKind.Forward)
},
Center = new List {
Item.BuiltIn(BuiltInItemKind.Title, title: string.Empty)
},
Right = new List {
Item.BuiltIn(BuiltInItemKind.Done)
}
};
}
private static string IdentifierForBuiltInKind(BuiltInItemKind kind) {
switch (kind) {
case BuiltInItemKind.Back:
return BuiltInIdentifier.Back;
case BuiltInItemKind.Forward:
return BuiltInIdentifier.Forward;
case BuiltInItemKind.Done:
return BuiltInIdentifier.Done;
case BuiltInItemKind.Reload:
return BuiltInIdentifier.Reload;
case BuiltInItemKind.Title:
return BuiltInIdentifier.Title;
default:
return string.Empty;
}
}
private static string SerializePosition(UniWebViewToolbarPosition position) {
return position == UniWebViewToolbarPosition.Bottom ? "bottom" : "top";
}
private static UniWebViewToolbarPosition ParsePosition(string value) {
return string.Equals(value, "bottom", StringComparison.OrdinalIgnoreCase)
? UniWebViewToolbarPosition.Bottom
: UniWebViewToolbarPosition.Top;
}
private static string SerializeItemType(ItemType type) {
return type == ItemType.Custom ? "custom" : "builtIn";
}
private static ItemType ParseItemType(string type) {
return string.Equals(type, "custom", StringComparison.OrdinalIgnoreCase)
? ItemType.Custom
: ItemType.BuiltIn;
}
private static string SerializeBuiltInKind(BuiltInItemKind? kind) {
if (!kind.HasValue) {
return null;
}
switch (kind.Value) {
case BuiltInItemKind.Back:
return "back";
case BuiltInItemKind.Forward:
return "forward";
case BuiltInItemKind.Done:
return "done";
case BuiltInItemKind.Reload:
return "reload";
case BuiltInItemKind.Title:
return "title";
default:
return null;
}
}
private static BuiltInItemKind? ParseBuiltInKind(string kind) {
if (string.IsNullOrEmpty(kind)) {
return null;
}
switch (kind.ToLowerInvariant()) {
case "back":
return BuiltInItemKind.Back;
case "forward":
return BuiltInItemKind.Forward;
case "done":
return BuiltInItemKind.Done;
case "reload":
return BuiltInItemKind.Reload;
case "title":
return BuiltInItemKind.Title;
default:
return null;
}
}
private static object SerializeColor(ColorValue color) {
if (color == null) {
return null;
}
return new Dictionary {
{ "r", color.r },
{ "g", color.g },
{ "b", color.b },
{ "a", color.a }
};
}
private static ColorValue ReadColor(Dictionary dict, string key) {
if (!dict.TryGetValue(key, out var raw) || raw == null) {
return null;
}
if (!(raw is Dictionary colorDict)) {
return null;
}
if (!TryReadFloat(colorDict, "r", out var r) ||
!TryReadFloat(colorDict, "g", out var g) ||
!TryReadFloat(colorDict, "b", out var b) ||
!TryReadFloat(colorDict, "a", out var a)) {
return null;
}
return new ColorValue {
r = r,
g = g,
b = b,
a = a
};
}
private static object SerializeStyle(ItemStyle style) {
if (style == null) {
return null;
}
return new Dictionary {
{ "textColor", SerializeColor(style.TextColor) }
};
}
private static ItemStyle ReadStyle(Dictionary dict, string key) {
if (!dict.TryGetValue(key, out var raw) || raw == null) {
return null;
}
if (!(raw is Dictionary styleDict)) {
return null;
}
return new ItemStyle {
TextColor = ReadColor(styleDict, "textColor")
};
}
private static object SerializeTitleInteraction(TitleInteraction interaction) {
if (interaction == null) {
return null;
}
return new Dictionary {
{ "onTap", SerializeTitleTapAction(interaction.OnTap) },
{ "onLongPress", SerializeTitleLongPressAction(interaction.OnLongPress) },
{ "copyToastText", interaction.CopyToastText }
};
}
private static TitleInteraction ReadTitleInteraction(Dictionary dict, string key) {
if (!dict.TryGetValue(key, out var raw) || raw == null) {
return null;
}
if (!(raw is Dictionary interactionDict)) {
return null;
}
return new TitleInteraction {
OnTap = ParseTitleTapAction(ReadString(interactionDict, "onTap")),
OnLongPress = ParseTitleLongPressAction(ReadString(interactionDict, "onLongPress")),
CopyToastText = ReadString(interactionDict, "copyToastText")
};
}
private static string SerializeTitleTapAction(TitleInteraction.TapAction action) {
switch (action) {
case TitleInteraction.TapAction.ScrollToTop:
return "scrollToTop";
default:
return "none";
}
}
private static TitleInteraction.TapAction ParseTitleTapAction(string value) {
return string.Equals(value, "scrollToTop", StringComparison.OrdinalIgnoreCase)
? TitleInteraction.TapAction.ScrollToTop
: TitleInteraction.TapAction.None;
}
private static string SerializeTitleLongPressAction(TitleInteraction.LongPressAction action) {
switch (action) {
case TitleInteraction.LongPressAction.CopyUrl:
return "copyUrl";
default:
return "none";
}
}
private static TitleInteraction.LongPressAction ParseTitleLongPressAction(string value) {
return string.Equals(value, "copyUrl", StringComparison.OrdinalIgnoreCase)
? TitleInteraction.LongPressAction.CopyUrl
: TitleInteraction.LongPressAction.None;
}
private static List