UniWebViewEmbeddedToolbarConfig.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using UniWebViewExternal;
  5. using UnityEngine;
  6. /// <summary>
  7. /// Represents the configuration for the embedded toolbar.
  8. ///
  9. /// A config object describes the full toolbar layout: which items appear (back, forward, done, reload, title, or
  10. /// custom buttons), how they are arranged (left, center, right sections), their colors, and title interaction
  11. /// behaviors.
  12. ///
  13. /// Use `UniWebViewEmbeddedToolbarConfig.Default` for the standard layout (back + forward on the left, title in the
  14. /// center, done on the right), or construct your own config from scratch. Apply the config by calling
  15. /// `UniWebViewEmbeddedToolbar.ApplyConfig`.
  16. /// </summary>
  17. [Serializable]
  18. public class UniWebViewEmbeddedToolbarConfig {
  19. /// <summary>
  20. /// The current config version. Currently `1`.
  21. /// </summary>
  22. public const int CurrentVersion = 1;
  23. /// <summary>
  24. /// The prefix used for all built-in item identifiers.
  25. /// </summary>
  26. public const string BuiltInIdentifierPrefix = "uwv.toolbar.";
  27. /// <summary>
  28. /// Contains the identifier constants for built-in toolbar items.
  29. /// </summary>
  30. public static class BuiltInIdentifier {
  31. /// <summary>Identifier for the back navigation button.</summary>
  32. public const string Back = "uwv.toolbar.back";
  33. /// <summary>Identifier for the forward navigation button.</summary>
  34. public const string Forward = "uwv.toolbar.forward";
  35. /// <summary>Identifier for the done (close) button.</summary>
  36. public const string Done = "uwv.toolbar.done";
  37. /// <summary>Identifier for the reload button.</summary>
  38. public const string Reload = "uwv.toolbar.reload";
  39. /// <summary>Identifier for the title item.</summary>
  40. public const string Title = "uwv.toolbar.title";
  41. }
  42. /// <summary>
  43. /// The type of a toolbar item.
  44. /// </summary>
  45. public enum ItemType {
  46. /// <summary>A built-in item with predefined behavior (back, forward, done, reload, title).</summary>
  47. BuiltIn,
  48. /// <summary>A custom button defined by the user.</summary>
  49. Custom
  50. }
  51. /// <summary>
  52. /// The kind of a built-in toolbar item.
  53. /// </summary>
  54. public enum BuiltInItemKind {
  55. /// <summary>Back navigation button. Default text: "❮".</summary>
  56. Back,
  57. /// <summary>Forward navigation button. Default text: "❯".</summary>
  58. Forward,
  59. /// <summary>Done (close) button. Default text: "Done".</summary>
  60. Done,
  61. /// <summary>Reload button. Default text: "↻".</summary>
  62. Reload,
  63. /// <summary>Title label displayed in the center section.</summary>
  64. Title
  65. }
  66. /// <summary>
  67. /// Represents a color with RGBA components, each in the range [0, 1].
  68. /// </summary>
  69. [Serializable]
  70. public class ColorValue {
  71. /// <summary>Red component, in the range [0, 1].</summary>
  72. public float r;
  73. /// <summary>Green component, in the range [0, 1].</summary>
  74. public float g;
  75. /// <summary>Blue component, in the range [0, 1].</summary>
  76. public float b;
  77. /// <summary>Alpha component, in the range [0, 1].</summary>
  78. public float a;
  79. /// <summary>
  80. /// Creates a `ColorValue` from a Unity `Color`.
  81. /// </summary>
  82. /// <param name="color">The Unity color to convert.</param>
  83. /// <returns>A new `ColorValue` instance.</returns>
  84. public static ColorValue FromColor(Color color) {
  85. return new ColorValue {
  86. r = color.r,
  87. g = color.g,
  88. b = color.b,
  89. a = color.a
  90. };
  91. }
  92. /// <summary>
  93. /// Converts this `ColorValue` to a Unity `Color`.
  94. /// </summary>
  95. /// <returns>A Unity `Color` instance.</returns>
  96. public Color ToColor() {
  97. return new Color(r, g, b, a);
  98. }
  99. }
  100. /// <summary>
  101. /// Represents the visual style of a toolbar item.
  102. /// </summary>
  103. [Serializable]
  104. public class ItemStyle {
  105. /// <summary>
  106. /// The text color of this item. When set, overrides the global `ButtonTextColor` or `TitleTextColor`.
  107. /// </summary>
  108. public ColorValue TextColor;
  109. }
  110. /// <summary>
  111. /// Configures interaction behaviors for the built-in Title item.
  112. ///
  113. /// You can set `OnTap` to `ScrollToTop` so tapping the title scrolls the web view to the top.
  114. /// You can set `OnLongPress` to `CopyUrl` so long-pressing the title copies the current URL to the clipboard
  115. /// and shows a toast message. The toast text can be customized via `CopyToastText`.
  116. /// </summary>
  117. [Serializable]
  118. public class TitleInteraction {
  119. /// <summary>
  120. /// The action to perform when the title item is tapped.
  121. /// </summary>
  122. public enum TapAction {
  123. /// <summary>No action on tap.</summary>
  124. None,
  125. /// <summary>Scroll the web view content to the top of the page.</summary>
  126. ScrollToTop
  127. }
  128. /// <summary>
  129. /// The action to perform when the title item is long-pressed.
  130. /// </summary>
  131. public enum LongPressAction {
  132. /// <summary>No action on long press.</summary>
  133. None,
  134. /// <summary>Copy the current page URL to the system clipboard and show a toast.</summary>
  135. CopyUrl
  136. }
  137. /// <summary>
  138. /// The action to perform when the title is tapped. Default is `None`.
  139. /// </summary>
  140. public TapAction OnTap = TapAction.None;
  141. /// <summary>
  142. /// The action to perform when the title is long-pressed. Default is `None`.
  143. /// </summary>
  144. public LongPressAction OnLongPress = LongPressAction.None;
  145. /// <summary>
  146. /// The toast message text shown after copying the URL. If not set, "URL copied" is used.
  147. /// Only applicable when `OnLongPress` is `CopyUrl`.
  148. /// </summary>
  149. public string CopyToastText;
  150. }
  151. /// <summary>
  152. /// Represents a single item in the toolbar. An item is either a built-in item (back, forward, done, reload,
  153. /// title) or a custom button. Use `Item.BuiltIn` or `Item.Custom` factory methods to create items.
  154. /// </summary>
  155. [Serializable]
  156. public class Item {
  157. /// <summary>The type of this item (built-in or custom).</summary>
  158. public ItemType Type;
  159. /// <summary>
  160. /// A unique identifier for this item. Built-in items use `uwv.toolbar.*` identifiers by default.
  161. /// Custom items must provide their own identifier.
  162. /// </summary>
  163. public string Identifier;
  164. /// <summary>Optional per-item visual style. When set, overrides global color settings.</summary>
  165. public ItemStyle Style;
  166. /// <summary>The kind of built-in item. Only applicable when `Type` is `BuiltIn`.</summary>
  167. public BuiltInItemKind? Kind;
  168. /// <summary>
  169. /// The display text for this item. For built-in items, if not set, a platform default is used.
  170. /// For custom items, this is the button label.
  171. /// </summary>
  172. public string Title;
  173. /// <summary>
  174. /// Whether this item is visible. If `null` or `true`, the item is shown. Set to `false` to hide it.
  175. /// </summary>
  176. public bool? Visible;
  177. /// <summary>
  178. /// Interaction config for the built-in Title item. Only applicable when `Kind` is `Title`.
  179. /// </summary>
  180. public TitleInteraction TitleInteraction;
  181. /// <summary>
  182. /// Creates a built-in toolbar item.
  183. /// </summary>
  184. /// <param name="kind">The kind of built-in item to create.</param>
  185. /// <param name="title">Optional title text override. If `null`, the platform default is used.</param>
  186. /// <param name="visible">Optional visibility. If `null`, the item is visible.</param>
  187. /// <param name="style">Optional per-item style override.</param>
  188. /// <param name="titleInteraction">Optional title interaction config. Only for `Title` items.</param>
  189. /// <param name="identifier">Optional identifier override. By default uses `uwv.toolbar.*`.</param>
  190. /// <returns>A new built-in `Item` instance.</returns>
  191. public static Item BuiltIn(
  192. BuiltInItemKind kind,
  193. string title = null,
  194. bool? visible = null,
  195. ItemStyle style = null,
  196. TitleInteraction titleInteraction = null,
  197. string identifier = null
  198. ) {
  199. return new Item {
  200. Type = ItemType.BuiltIn,
  201. Kind = kind,
  202. Identifier = string.IsNullOrEmpty(identifier) ? IdentifierForBuiltInKind(kind) : identifier,
  203. Title = title,
  204. Visible = visible,
  205. Style = style,
  206. TitleInteraction = titleInteraction
  207. };
  208. }
  209. /// <summary>
  210. /// Creates a custom toolbar button.
  211. /// </summary>
  212. /// <param name="identifier">A unique identifier for this item. Used to identify it in action callbacks.</param>
  213. /// <param name="title">The button label text.</param>
  214. /// <param name="style">Optional per-item style.</param>
  215. /// <returns>A new custom `Item` instance.</returns>
  216. public static Item Custom(string identifier, string title, ItemStyle style = null) {
  217. return new Item {
  218. Type = ItemType.Custom,
  219. Identifier = identifier,
  220. Title = title,
  221. Style = style
  222. };
  223. }
  224. /// <summary>
  225. /// Returns whether this item is visible. An item is visible when `Visible` is `null` or `true`.
  226. /// </summary>
  227. /// <returns>`true` if the item should be displayed.</returns>
  228. public bool IsVisible() {
  229. return !Visible.HasValue || Visible.Value;
  230. }
  231. }
  232. /// <summary>
  233. /// Gets the JSON string representation of the default config.
  234. /// </summary>
  235. public static string DefaultJson => CreateDefault().ToJson();
  236. /// <summary>
  237. /// Gets the default toolbar config.
  238. ///
  239. /// The default contains: back and forward buttons on the left, a title item in the center, and a done button
  240. /// on the right. Position is `Top`, visibility is `true`, and colors use platform defaults.
  241. /// </summary>
  242. public static UniWebViewEmbeddedToolbarConfig Default => CreateDefault();
  243. /// <summary>The config version. Currently always `1`.</summary>
  244. public int Version = CurrentVersion;
  245. /// <summary>Whether the toolbar is visible. Default is `true`.</summary>
  246. public bool Visible = true;
  247. /// <summary>
  248. /// The position of the toolbar (`Top` or `Bottom`). Default is `Top`.
  249. /// Only effective on iOS and Android; macOS toolbar is always in the title bar.
  250. /// </summary>
  251. public UniWebViewToolbarPosition Position = UniWebViewToolbarPosition.Top;
  252. /// <summary>
  253. /// The maximum height of the toolbar in points. If smaller than the standard height, the toolbar shrinks.
  254. /// Only effective on iOS and Android.
  255. /// </summary>
  256. public float? MaxHeight;
  257. /// <summary>The background color of the toolbar. When `null`, the platform default is used.</summary>
  258. public ColorValue BackgroundColor;
  259. /// <summary>
  260. /// The default text color for toolbar buttons. When `null`, the platform default is used.
  261. /// Individual items can override this via `Item.Style.TextColor`.
  262. /// </summary>
  263. public ColorValue ButtonTextColor;
  264. /// <summary>
  265. /// The text color for the title item. When `null`, the platform default is used.
  266. /// The title item can override this via its own `Item.Style.TextColor`.
  267. /// </summary>
  268. public ColorValue TitleTextColor;
  269. /// <summary>Items in the left section. Default: back and forward buttons.</summary>
  270. public List<Item> Left = new List<Item>();
  271. /// <summary>Items in the center section. Default: title item.</summary>
  272. public List<Item> Center = new List<Item>();
  273. /// <summary>Items in the right section. Default: done button.</summary>
  274. public List<Item> Right = new List<Item>();
  275. /// <summary>
  276. /// Serializes this config to a JSON string.
  277. /// </summary>
  278. /// <returns>A JSON string representing this config.</returns>
  279. public string ToJson() {
  280. return Json.Serialize(ToDictionary());
  281. }
  282. /// <summary>
  283. /// Converts this config to a dictionary representation.
  284. /// </summary>
  285. /// <returns>A dictionary that can be serialized to JSON.</returns>
  286. public Dictionary<string, object> ToDictionary() {
  287. var dict = new Dictionary<string, object> {
  288. { "version", Version },
  289. { "visible", Visible },
  290. { "position", SerializePosition(Position) },
  291. { "maxHeight", MaxHeight.HasValue ? (object)MaxHeight.Value : null },
  292. { "backgroundColor", SerializeColor(BackgroundColor) },
  293. { "buttonTextColor", SerializeColor(ButtonTextColor) },
  294. { "titleTextColor", SerializeColor(TitleTextColor) },
  295. { "left", SerializeItems(Left) },
  296. { "center", SerializeItems(Center) },
  297. { "right", SerializeItems(Right) }
  298. };
  299. return dict;
  300. }
  301. /// <summary>
  302. /// Creates a config from a JSON string.
  303. /// </summary>
  304. /// <param name="json">A JSON string representing the toolbar config.</param>
  305. /// <returns>A parsed config, or `null` if the JSON is invalid or empty.</returns>
  306. public static UniWebViewEmbeddedToolbarConfig FromJson(string json) {
  307. if (string.IsNullOrEmpty(json)) {
  308. return null;
  309. }
  310. try {
  311. var dict = Json.Deserialize(json) as Dictionary<string, object>;
  312. if (dict == null) {
  313. UniWebViewLogger.Instance.Debug("Embedded toolbar config JSON is not an object.");
  314. return null;
  315. }
  316. return FromDictionary(dict);
  317. } catch (Exception e) {
  318. UniWebViewLogger.Instance.Debug("Failed to parse embedded toolbar config JSON: " + e.Message);
  319. return null;
  320. }
  321. }
  322. /// <summary>
  323. /// Creates a config from a dictionary.
  324. /// </summary>
  325. /// <param name="dict">A dictionary representing the toolbar config.</param>
  326. /// <returns>A parsed config, or `null` if the dictionary is `null`.</returns>
  327. public static UniWebViewEmbeddedToolbarConfig FromDictionary(Dictionary<string, object> dict) {
  328. if (dict == null) {
  329. return null;
  330. }
  331. var config = new UniWebViewEmbeddedToolbarConfig {
  332. Version = ReadInt(dict, "version", CurrentVersion),
  333. Visible = ReadBool(dict, "visible", true),
  334. Position = ParsePosition(ReadString(dict, "position")),
  335. MaxHeight = ReadNullableFloat(dict, "maxHeight"),
  336. BackgroundColor = ReadColor(dict, "backgroundColor"),
  337. ButtonTextColor = ReadColor(dict, "buttonTextColor"),
  338. TitleTextColor = ReadColor(dict, "titleTextColor")
  339. };
  340. config.Left = ReadItems(dict, "left");
  341. config.Center = ReadItems(dict, "center");
  342. config.Right = ReadItems(dict, "right");
  343. return config;
  344. }
  345. /// <summary>
  346. /// Enumerates all items across all sections (left, center, right) in order.
  347. /// </summary>
  348. /// <returns>An enumerable of all items.</returns>
  349. public IEnumerable<Item> EnumerateItems() {
  350. foreach (var item in Left) {
  351. yield return item;
  352. }
  353. foreach (var item in Center) {
  354. yield return item;
  355. }
  356. foreach (var item in Right) {
  357. yield return item;
  358. }
  359. }
  360. /// <summary>
  361. /// Finds the first built-in item matching the given kind across all sections (left, center, right).
  362. /// </summary>
  363. /// <param name="kind">The built-in item kind to search for.</param>
  364. /// <returns>The matching item, or `null` if not found.</returns>
  365. public Item FindFirstBuiltInItem(BuiltInItemKind kind) {
  366. foreach (var item in EnumerateItems()) {
  367. if (item == null || item.Type != ItemType.BuiltIn || !item.Kind.HasValue) {
  368. continue;
  369. }
  370. if (item.Kind.Value == kind) {
  371. return item;
  372. }
  373. }
  374. return null;
  375. }
  376. private static UniWebViewEmbeddedToolbarConfig CreateDefault() {
  377. return new UniWebViewEmbeddedToolbarConfig {
  378. Version = CurrentVersion,
  379. Visible = true,
  380. Position = UniWebViewToolbarPosition.Top,
  381. MaxHeight = null,
  382. BackgroundColor = null,
  383. ButtonTextColor = null,
  384. TitleTextColor = null,
  385. Left = new List<Item> {
  386. Item.BuiltIn(BuiltInItemKind.Back),
  387. Item.BuiltIn(BuiltInItemKind.Forward)
  388. },
  389. Center = new List<Item> {
  390. Item.BuiltIn(BuiltInItemKind.Title, title: string.Empty)
  391. },
  392. Right = new List<Item> {
  393. Item.BuiltIn(BuiltInItemKind.Done)
  394. }
  395. };
  396. }
  397. private static string IdentifierForBuiltInKind(BuiltInItemKind kind) {
  398. switch (kind) {
  399. case BuiltInItemKind.Back:
  400. return BuiltInIdentifier.Back;
  401. case BuiltInItemKind.Forward:
  402. return BuiltInIdentifier.Forward;
  403. case BuiltInItemKind.Done:
  404. return BuiltInIdentifier.Done;
  405. case BuiltInItemKind.Reload:
  406. return BuiltInIdentifier.Reload;
  407. case BuiltInItemKind.Title:
  408. return BuiltInIdentifier.Title;
  409. default:
  410. return string.Empty;
  411. }
  412. }
  413. private static string SerializePosition(UniWebViewToolbarPosition position) {
  414. return position == UniWebViewToolbarPosition.Bottom ? "bottom" : "top";
  415. }
  416. private static UniWebViewToolbarPosition ParsePosition(string value) {
  417. return string.Equals(value, "bottom", StringComparison.OrdinalIgnoreCase)
  418. ? UniWebViewToolbarPosition.Bottom
  419. : UniWebViewToolbarPosition.Top;
  420. }
  421. private static string SerializeItemType(ItemType type) {
  422. return type == ItemType.Custom ? "custom" : "builtIn";
  423. }
  424. private static ItemType ParseItemType(string type) {
  425. return string.Equals(type, "custom", StringComparison.OrdinalIgnoreCase)
  426. ? ItemType.Custom
  427. : ItemType.BuiltIn;
  428. }
  429. private static string SerializeBuiltInKind(BuiltInItemKind? kind) {
  430. if (!kind.HasValue) {
  431. return null;
  432. }
  433. switch (kind.Value) {
  434. case BuiltInItemKind.Back:
  435. return "back";
  436. case BuiltInItemKind.Forward:
  437. return "forward";
  438. case BuiltInItemKind.Done:
  439. return "done";
  440. case BuiltInItemKind.Reload:
  441. return "reload";
  442. case BuiltInItemKind.Title:
  443. return "title";
  444. default:
  445. return null;
  446. }
  447. }
  448. private static BuiltInItemKind? ParseBuiltInKind(string kind) {
  449. if (string.IsNullOrEmpty(kind)) {
  450. return null;
  451. }
  452. switch (kind.ToLowerInvariant()) {
  453. case "back":
  454. return BuiltInItemKind.Back;
  455. case "forward":
  456. return BuiltInItemKind.Forward;
  457. case "done":
  458. return BuiltInItemKind.Done;
  459. case "reload":
  460. return BuiltInItemKind.Reload;
  461. case "title":
  462. return BuiltInItemKind.Title;
  463. default:
  464. return null;
  465. }
  466. }
  467. private static object SerializeColor(ColorValue color) {
  468. if (color == null) {
  469. return null;
  470. }
  471. return new Dictionary<string, object> {
  472. { "r", color.r },
  473. { "g", color.g },
  474. { "b", color.b },
  475. { "a", color.a }
  476. };
  477. }
  478. private static ColorValue ReadColor(Dictionary<string, object> dict, string key) {
  479. if (!dict.TryGetValue(key, out var raw) || raw == null) {
  480. return null;
  481. }
  482. if (!(raw is Dictionary<string, object> colorDict)) {
  483. return null;
  484. }
  485. if (!TryReadFloat(colorDict, "r", out var r) ||
  486. !TryReadFloat(colorDict, "g", out var g) ||
  487. !TryReadFloat(colorDict, "b", out var b) ||
  488. !TryReadFloat(colorDict, "a", out var a)) {
  489. return null;
  490. }
  491. return new ColorValue {
  492. r = r,
  493. g = g,
  494. b = b,
  495. a = a
  496. };
  497. }
  498. private static object SerializeStyle(ItemStyle style) {
  499. if (style == null) {
  500. return null;
  501. }
  502. return new Dictionary<string, object> {
  503. { "textColor", SerializeColor(style.TextColor) }
  504. };
  505. }
  506. private static ItemStyle ReadStyle(Dictionary<string, object> dict, string key) {
  507. if (!dict.TryGetValue(key, out var raw) || raw == null) {
  508. return null;
  509. }
  510. if (!(raw is Dictionary<string, object> styleDict)) {
  511. return null;
  512. }
  513. return new ItemStyle {
  514. TextColor = ReadColor(styleDict, "textColor")
  515. };
  516. }
  517. private static object SerializeTitleInteraction(TitleInteraction interaction) {
  518. if (interaction == null) {
  519. return null;
  520. }
  521. return new Dictionary<string, object> {
  522. { "onTap", SerializeTitleTapAction(interaction.OnTap) },
  523. { "onLongPress", SerializeTitleLongPressAction(interaction.OnLongPress) },
  524. { "copyToastText", interaction.CopyToastText }
  525. };
  526. }
  527. private static TitleInteraction ReadTitleInteraction(Dictionary<string, object> dict, string key) {
  528. if (!dict.TryGetValue(key, out var raw) || raw == null) {
  529. return null;
  530. }
  531. if (!(raw is Dictionary<string, object> interactionDict)) {
  532. return null;
  533. }
  534. return new TitleInteraction {
  535. OnTap = ParseTitleTapAction(ReadString(interactionDict, "onTap")),
  536. OnLongPress = ParseTitleLongPressAction(ReadString(interactionDict, "onLongPress")),
  537. CopyToastText = ReadString(interactionDict, "copyToastText")
  538. };
  539. }
  540. private static string SerializeTitleTapAction(TitleInteraction.TapAction action) {
  541. switch (action) {
  542. case TitleInteraction.TapAction.ScrollToTop:
  543. return "scrollToTop";
  544. default:
  545. return "none";
  546. }
  547. }
  548. private static TitleInteraction.TapAction ParseTitleTapAction(string value) {
  549. return string.Equals(value, "scrollToTop", StringComparison.OrdinalIgnoreCase)
  550. ? TitleInteraction.TapAction.ScrollToTop
  551. : TitleInteraction.TapAction.None;
  552. }
  553. private static string SerializeTitleLongPressAction(TitleInteraction.LongPressAction action) {
  554. switch (action) {
  555. case TitleInteraction.LongPressAction.CopyUrl:
  556. return "copyUrl";
  557. default:
  558. return "none";
  559. }
  560. }
  561. private static TitleInteraction.LongPressAction ParseTitleLongPressAction(string value) {
  562. return string.Equals(value, "copyUrl", StringComparison.OrdinalIgnoreCase)
  563. ? TitleInteraction.LongPressAction.CopyUrl
  564. : TitleInteraction.LongPressAction.None;
  565. }
  566. private static List<object> SerializeItems(List<Item> items) {
  567. var result = new List<object>();
  568. if (items == null) {
  569. return result;
  570. }
  571. foreach (var item in items) {
  572. if (item == null) {
  573. continue;
  574. }
  575. result.Add(SerializeItem(item));
  576. }
  577. return result;
  578. }
  579. private static object SerializeItem(Item item) {
  580. var dict = new Dictionary<string, object> {
  581. { "type", SerializeItemType(item.Type) },
  582. { "identifier", item.Identifier },
  583. { "style", SerializeStyle(item.Style) }
  584. };
  585. if (item.Type == ItemType.BuiltIn) {
  586. dict["kind"] = SerializeBuiltInKind(item.Kind);
  587. dict["title"] = item.Title;
  588. dict["visible"] = item.Visible.HasValue ? (object)item.Visible.Value : null;
  589. if (item.Kind == BuiltInItemKind.Title) {
  590. dict["titleInteraction"] = SerializeTitleInteraction(item.TitleInteraction);
  591. }
  592. } else {
  593. dict["title"] = item.Title;
  594. }
  595. return dict;
  596. }
  597. private static List<Item> ReadItems(Dictionary<string, object> dict, string key) {
  598. var items = new List<Item>();
  599. if (!dict.TryGetValue(key, out var raw) || raw == null) {
  600. return items;
  601. }
  602. if (!(raw is List<object> itemList)) {
  603. return items;
  604. }
  605. foreach (var itemObj in itemList) {
  606. if (!(itemObj is Dictionary<string, object> itemDict)) {
  607. continue;
  608. }
  609. var item = ReadItem(itemDict);
  610. if (item != null) {
  611. items.Add(item);
  612. }
  613. }
  614. return items;
  615. }
  616. private static Item ReadItem(Dictionary<string, object> dict) {
  617. var type = ParseItemType(ReadString(dict, "type"));
  618. var kind = ParseBuiltInKind(ReadString(dict, "kind"));
  619. var identifier = ReadString(dict, "identifier");
  620. if (string.IsNullOrEmpty(identifier) && type == ItemType.BuiltIn && kind.HasValue) {
  621. identifier = IdentifierForBuiltInKind(kind.Value);
  622. }
  623. if (type == ItemType.BuiltIn && !kind.HasValue && !string.IsNullOrEmpty(identifier)) {
  624. kind = ParseBuiltInKindFromIdentifier(identifier);
  625. }
  626. if (string.IsNullOrEmpty(identifier)) {
  627. UniWebViewLogger.Instance.Debug("Embedded toolbar config item misses identifier and will be ignored.");
  628. return null;
  629. }
  630. var item = new Item {
  631. Type = type,
  632. Identifier = identifier,
  633. Kind = type == ItemType.BuiltIn ? kind : null,
  634. Title = ReadString(dict, "title"),
  635. Visible = type == ItemType.BuiltIn ? ReadNullableBool(dict, "visible") : null,
  636. Style = ReadStyle(dict, "style")
  637. };
  638. if (type == ItemType.BuiltIn && item.Kind == BuiltInItemKind.Title) {
  639. item.TitleInteraction = ReadTitleInteraction(dict, "titleInteraction");
  640. }
  641. return item;
  642. }
  643. private static BuiltInItemKind? ParseBuiltInKindFromIdentifier(string identifier) {
  644. switch (identifier) {
  645. case BuiltInIdentifier.Back:
  646. return BuiltInItemKind.Back;
  647. case BuiltInIdentifier.Forward:
  648. return BuiltInItemKind.Forward;
  649. case BuiltInIdentifier.Done:
  650. return BuiltInItemKind.Done;
  651. case BuiltInIdentifier.Reload:
  652. return BuiltInItemKind.Reload;
  653. case BuiltInIdentifier.Title:
  654. return BuiltInItemKind.Title;
  655. default:
  656. return null;
  657. }
  658. }
  659. private static string ReadString(Dictionary<string, object> dict, string key) {
  660. if (!dict.TryGetValue(key, out var value) || value == null) {
  661. return null;
  662. }
  663. return value as string ?? value.ToString();
  664. }
  665. private static int ReadInt(Dictionary<string, object> dict, string key, int defaultValue) {
  666. if (!dict.TryGetValue(key, out var value) || value == null) {
  667. return defaultValue;
  668. }
  669. if (value is long longValue) {
  670. return (int)longValue;
  671. }
  672. if (value is double doubleValue) {
  673. return (int)doubleValue;
  674. }
  675. return int.TryParse(value.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed)
  676. ? parsed
  677. : defaultValue;
  678. }
  679. private static bool ReadBool(Dictionary<string, object> dict, string key, bool defaultValue) {
  680. var value = ReadNullableBool(dict, key);
  681. return value.HasValue ? value.Value : defaultValue;
  682. }
  683. private static bool? ReadNullableBool(Dictionary<string, object> dict, string key) {
  684. if (!dict.TryGetValue(key, out var value) || value == null) {
  685. return null;
  686. }
  687. if (value is bool boolValue) {
  688. return boolValue;
  689. }
  690. if (value is long longValue) {
  691. return longValue != 0;
  692. }
  693. if (value is double doubleValue) {
  694. return Math.Abs(doubleValue) > double.Epsilon;
  695. }
  696. if (bool.TryParse(value.ToString(), out var parsedBool)) {
  697. return parsedBool;
  698. }
  699. return null;
  700. }
  701. private static bool TryReadFloat(Dictionary<string, object> dict, string key, out float value) {
  702. value = 0f;
  703. if (!dict.TryGetValue(key, out var raw) || raw == null) {
  704. return false;
  705. }
  706. return TryConvertToFloat(raw, out value);
  707. }
  708. private static float? ReadNullableFloat(Dictionary<string, object> dict, string key) {
  709. if (!dict.TryGetValue(key, out var raw) || raw == null) {
  710. return null;
  711. }
  712. return TryConvertToFloat(raw, out var value) ? value : (float?)null;
  713. }
  714. private static bool TryConvertToFloat(object raw, out float value) {
  715. value = 0f;
  716. if (raw is float floatValue) {
  717. value = floatValue;
  718. return true;
  719. }
  720. if (raw is double doubleValue) {
  721. value = (float)doubleValue;
  722. return true;
  723. }
  724. if (raw is long longValue) {
  725. value = longValue;
  726. return true;
  727. }
  728. if (raw is int intValue) {
  729. value = intValue;
  730. return true;
  731. }
  732. return float.TryParse(raw.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out value);
  733. }
  734. }
  735. /// <summary>
  736. /// Applies embedded toolbar config via JSON bridge.
  737. /// </summary>
  738. public static class UniWebViewEmbeddedToolbarConfigApplier {
  739. public interface IBridge {
  740. bool TrySetEmbeddedToolbarConfig(string name, string json);
  741. }
  742. private sealed class NativeBridge : IBridge {
  743. public bool TrySetEmbeddedToolbarConfig(string name, string json) {
  744. return UniWebViewInterface.SetEmbeddedToolbarConfig(name, json);
  745. }
  746. }
  747. private static readonly IBridge DefaultBridge = new NativeBridge();
  748. public static bool Apply(string name, UniWebViewEmbeddedToolbarConfig config) {
  749. return Apply(name, config, DefaultBridge);
  750. }
  751. public static bool ApplyJson(string name, string json) {
  752. return ApplyJson(name, json, DefaultBridge);
  753. }
  754. public static bool Apply(string name, UniWebViewEmbeddedToolbarConfig config, IBridge bridge) {
  755. if (string.IsNullOrEmpty(name)) {
  756. UniWebViewLogger.Instance.Debug("Embedded toolbar config apply skipped due to empty listener name.");
  757. return false;
  758. }
  759. if (config == null) {
  760. config = UniWebViewEmbeddedToolbarConfig.Default;
  761. }
  762. if (bridge == null) {
  763. bridge = DefaultBridge;
  764. }
  765. return ApplyJson(name, config.ToJson(), bridge);
  766. }
  767. public static bool ApplyJson(string name, string json, IBridge bridge) {
  768. if (string.IsNullOrEmpty(name)) {
  769. UniWebViewLogger.Instance.Debug("Embedded toolbar config apply skipped due to empty listener name.");
  770. return false;
  771. }
  772. if (string.IsNullOrEmpty(json)) {
  773. json = UniWebViewEmbeddedToolbarConfig.DefaultJson;
  774. }
  775. if (bridge == null) {
  776. bridge = DefaultBridge;
  777. }
  778. return bridge.TrySetEmbeddedToolbarConfig(name, json);
  779. }
  780. }