From 14e19b8df32fe71228657e4192cc5633d030b489 Mon Sep 17 00:00:00 2001 From: "instance.id" Date: Sat, 24 Jul 2021 19:20:11 -0500 Subject: [PATCH] Refactorings, additional base animation overloads Some refactorings so that eventually it can be used for in-game UI and additional base animation overloads to allow and parse HTML hex color string to be passed in color fields. --- Editor/EATKEditor.cs | 47 +- Editor/ElementData.meta | 3 + Editor/ElementData/ObjectElementData.cs | 29 + Editor/ElementData/ObjectElementData.cs.meta | 3 + ...ance.elementanimationtoolkit.Editor.asmdef | 4 +- Runtime/Animations.meta | 3 + .../Animations/AnimationExtensions.cs | 5 +- .../Animations/AnimationExtensions.cs.meta | 11 + .../Animations/AnimationSequences.cs | 52 +- Runtime/Animations/AnimationSequences.cs.meta | 11 + .../Animations/ContinuousAnimations.cs | 20 +- .../Animations/ContinuousAnimations.cs.meta | 11 + .../Extensions => }/Animations/Easy.cs | 4 +- Runtime/Animations/Easy.cs.meta | 11 + .../Animations/HoverAnimations.cs | 13 +- Runtime/Animations/HoverAnimations.cs.meta | 11 + .../Animations/VisualElementBaseAnimation.cs | 87 +- .../VisualElementBaseAnimation.cs.meta | 2 +- Runtime/Elements.meta | 3 + Runtime/Elements/AnimatedFoldout.meta | 8 + .../AnimatedFoldout/AnimatedFoldout.cs | 6 +- .../AnimatedFoldout/AnimatedFoldout.cs.meta | 0 .../AnimatedFoldout/UIElementExpander.cs | 2 +- .../AnimatedFoldout/UIElementExpander.cs.meta | 0 Runtime/Elements/AnimatedLabel.meta | 8 + .../Elements/AnimatedLabel/AnimatedLabel.cs | 6 +- .../AnimatedLabel/AnimatedLabel.cs.meta | 0 .../Elements/AnimatedLabel/Style.meta | 0 .../AnimatedLabel/Style/AnimatedLabel.uss | 0 .../Style/AnimatedLabel.uss.meta | 0 Runtime/Elements/BetterTextField.meta | 8 + .../BetterTextField/MaskedInputField.cs | 20 +- .../BetterTextField/MaskedInputField.cs.meta | 0 .../Elements/BetterTextField/Style.meta | 0 .../Style/MaskedInputField.uss | 0 .../Style/MaskedInputField.uss.meta | 0 Runtime/Scripts/Extensions/Animations.meta | 3 - .../Animations/AnimationExtensions.cs.meta | 3 - .../Animations/AnimationSequences.cs.meta | 3 - .../Animations/ContinuousAnimations.cs.meta | 3 - .../Extensions/Animations/Easy.cs.meta | 3 - .../Animations/HoverAnimations.cs.meta | 3 - .../Scripts/Extensions/AssetFileExtensions.cs | 400 ++++++++ .../Extensions/AssetFileExtensions.cs.meta | 11 + .../Extensions/CollectionExtensions.cs | 223 +++++ .../Extensions/CollectionExtensions.cs.meta | 11 + .../Extensions/DataTypes/AnimatedItems.cs | 2 +- .../DataTypes/VisualElementStyleStore.cs | 442 +++++++++ .../DataTypes/VisualElementStyleStore.cs.meta | 11 + .../Extensions/Elements/AnimatedFoldout.meta | 3 - .../Extensions/Elements/AnimatedLabel.meta | 3 - .../Extensions/Elements/BetterTextField.meta | 3 - Runtime/Scripts/Extensions/JumpTarget.meta | 8 + .../Extensions/JumpTarget/JumpTarget.cs | 56 ++ .../Extensions/JumpTarget/JumpTarget.cs.meta | 11 + .../Scripts/Extensions/JumpTarget/JumpType.cs | 18 + .../Extensions/JumpTarget/JumpType.cs.meta | 11 + Runtime/Scripts/Extensions/ParseElements.cs | 334 +++++++ .../Scripts/Extensions/ParseElements.cs.meta | 11 + .../Extensions/VisualElementExtension.cs | 939 ++++++++++++++++++ .../Extensions/VisualElementExtension.cs.meta | 11 + Runtime/Util.meta | 3 + Runtime/Util/ColorUtil.cs | 43 + Runtime/Util/ColorUtil.cs.meta | 11 + Samples/Example_Scene.unity | 118 +-- .../Scripts/Editor/ExampleComponentEditor.cs | 14 +- package.json | 6 +- 67 files changed, 2841 insertions(+), 268 deletions(-) create mode 100644 Editor/ElementData.meta create mode 100644 Editor/ElementData/ObjectElementData.cs create mode 100644 Editor/ElementData/ObjectElementData.cs.meta create mode 100644 Runtime/Animations.meta rename Runtime/{Scripts/Extensions => }/Animations/AnimationExtensions.cs (93%) create mode 100644 Runtime/Animations/AnimationExtensions.cs.meta rename Runtime/{Scripts/Extensions => }/Animations/AnimationSequences.cs (89%) create mode 100644 Runtime/Animations/AnimationSequences.cs.meta rename Runtime/{Scripts/Extensions => }/Animations/ContinuousAnimations.cs (93%) create mode 100644 Runtime/Animations/ContinuousAnimations.cs.meta rename Runtime/{Scripts/Extensions => }/Animations/Easy.cs (98%) create mode 100644 Runtime/Animations/Easy.cs.meta rename Runtime/{Scripts/Extensions => }/Animations/HoverAnimations.cs (98%) create mode 100644 Runtime/Animations/HoverAnimations.cs.meta rename Runtime/{Scripts/Extensions => }/Animations/VisualElementBaseAnimation.cs (61%) rename Runtime/{Scripts/Extensions => }/Animations/VisualElementBaseAnimation.cs.meta (83%) create mode 100644 Runtime/Elements.meta create mode 100644 Runtime/Elements/AnimatedFoldout.meta rename Runtime/{Scripts/Extensions => }/Elements/AnimatedFoldout/AnimatedFoldout.cs (99%) rename Runtime/{Scripts/Extensions => }/Elements/AnimatedFoldout/AnimatedFoldout.cs.meta (100%) rename Runtime/{Scripts/Extensions => }/Elements/AnimatedFoldout/UIElementExpander.cs (99%) rename Runtime/{Scripts/Extensions => }/Elements/AnimatedFoldout/UIElementExpander.cs.meta (100%) create mode 100644 Runtime/Elements/AnimatedLabel.meta rename Runtime/{Scripts/Extensions => }/Elements/AnimatedLabel/AnimatedLabel.cs (99%) rename Runtime/{Scripts/Extensions => }/Elements/AnimatedLabel/AnimatedLabel.cs.meta (100%) rename Runtime/{Scripts/Extensions => }/Elements/AnimatedLabel/Style.meta (100%) rename Runtime/{Scripts/Extensions => }/Elements/AnimatedLabel/Style/AnimatedLabel.uss (100%) rename Runtime/{Scripts/Extensions => }/Elements/AnimatedLabel/Style/AnimatedLabel.uss.meta (100%) create mode 100644 Runtime/Elements/BetterTextField.meta rename Runtime/{Scripts/Extensions => }/Elements/BetterTextField/MaskedInputField.cs (92%) rename Runtime/{Scripts/Extensions => }/Elements/BetterTextField/MaskedInputField.cs.meta (100%) rename Runtime/{Scripts/Extensions => }/Elements/BetterTextField/Style.meta (100%) rename Runtime/{Scripts/Extensions => }/Elements/BetterTextField/Style/MaskedInputField.uss (100%) rename Runtime/{Scripts/Extensions => }/Elements/BetterTextField/Style/MaskedInputField.uss.meta (100%) delete mode 100644 Runtime/Scripts/Extensions/Animations.meta delete mode 100644 Runtime/Scripts/Extensions/Animations/AnimationExtensions.cs.meta delete mode 100644 Runtime/Scripts/Extensions/Animations/AnimationSequences.cs.meta delete mode 100644 Runtime/Scripts/Extensions/Animations/ContinuousAnimations.cs.meta delete mode 100644 Runtime/Scripts/Extensions/Animations/Easy.cs.meta delete mode 100644 Runtime/Scripts/Extensions/Animations/HoverAnimations.cs.meta create mode 100644 Runtime/Scripts/Extensions/AssetFileExtensions.cs create mode 100644 Runtime/Scripts/Extensions/AssetFileExtensions.cs.meta create mode 100644 Runtime/Scripts/Extensions/CollectionExtensions.cs create mode 100644 Runtime/Scripts/Extensions/CollectionExtensions.cs.meta create mode 100644 Runtime/Scripts/Extensions/DataTypes/VisualElementStyleStore.cs create mode 100644 Runtime/Scripts/Extensions/DataTypes/VisualElementStyleStore.cs.meta delete mode 100644 Runtime/Scripts/Extensions/Elements/AnimatedFoldout.meta delete mode 100644 Runtime/Scripts/Extensions/Elements/AnimatedLabel.meta delete mode 100644 Runtime/Scripts/Extensions/Elements/BetterTextField.meta create mode 100644 Runtime/Scripts/Extensions/JumpTarget.meta create mode 100644 Runtime/Scripts/Extensions/JumpTarget/JumpTarget.cs create mode 100644 Runtime/Scripts/Extensions/JumpTarget/JumpTarget.cs.meta create mode 100644 Runtime/Scripts/Extensions/JumpTarget/JumpType.cs create mode 100644 Runtime/Scripts/Extensions/JumpTarget/JumpType.cs.meta create mode 100644 Runtime/Scripts/Extensions/ParseElements.cs create mode 100644 Runtime/Scripts/Extensions/ParseElements.cs.meta create mode 100644 Runtime/Scripts/Extensions/VisualElementExtension.cs create mode 100644 Runtime/Scripts/Extensions/VisualElementExtension.cs.meta create mode 100644 Runtime/Util.meta create mode 100644 Runtime/Util/ColorUtil.cs create mode 100644 Runtime/Util/ColorUtil.cs.meta diff --git a/Editor/EATKEditor.cs b/Editor/EATKEditor.cs index d39377d..4a9f454 100644 --- a/Editor/EATKEditor.cs +++ b/Editor/EATKEditor.cs @@ -9,7 +9,6 @@ using System.Collections.Generic; using System.Linq; using instance.id.EATK.Extensions; -using instance.id.Extensions; using JetBrains.Annotations; using UnityEditor; using UnityEditor.UIElements; @@ -101,9 +100,9 @@ private void Assignments() animatedIcon = (Texture2D) EditorGUIUtility.IconContent("ScriptableObject Icon").image; // -- Color Assignments ----------------------- - originalColor = GetColor.FromHex("#BABABA"); - pulseStartColor = GetColor.FromHex("#7F3B3A"); - pulseEndColor = GetColor.FromHex("#607FAE"); + originalColor = ColorUtil.FromHex("#BABABA"); + pulseStartColor = ColorUtil.FromHex("#7F3B3A"); + pulseEndColor = ColorUtil.FromHex("#607FAE"); } private StyleSheet StylesheetSetup() @@ -277,8 +276,8 @@ private void BuildToolbarButtons(Toolbar toolbar) // -- Register the HoverBorderPulse callback -- toolbarInfo.HoverBorderPulse( - pulseStartColor: GetColor.FromHex("#7F3B3A"), - pulseEndColor: GetColor.FromHex("#2F569C"), + pulseStartColor: ColorUtil.FromHex("#7F3B3A"), + pulseEndColor: ColorUtil.FromHex("#2F569C"), colorDuration: 500); } @@ -754,7 +753,7 @@ private void FoldoutAnimation() // -- AnimatedFoldout values ------------------ var openDelayMs = 500; var closeDelayMs = 4500; - var animatedColor = GetColor.FromHex("#2F569C"); + var animatedColor = ColorUtil.FromHex("#2F569C"); // -- Animated Label values ------------------- var cascadeMs = 50; @@ -802,7 +801,7 @@ private void AnimateIdLabel() instanceidLabel.AnimCharacterSequence( color1: originalColor, - color2: GetColor.FromHex("#2F569C"), + color2: ColorUtil.FromHex("#2F569C"), cascadeMs: cascadeMs, durationMS: durationMs); } @@ -816,8 +815,8 @@ private void AnimateIdLabel() private void ButtonCascadeAnimation() // @formatter:on { // -- Image colors ------------------ - var buttonColor = GetColor.FromHex("#676767"); - var endButtonColor = GetColor.FromHex("#2F569C"); + var buttonColor = ColorUtil.FromHex("#676767"); + var endButtonColor = ColorUtil.FromHex("#2F569C"); const int durationInMs = 500; const int delayInMs = 1000; @@ -910,9 +909,9 @@ private void HeaderInfoMenuAnimation(bool evt, VisualElement menuInfoContainer, const int durationMs = 500; const int inDurationMs = 300; const int outDurationMs = 150; - var hoverLabelColor = GetColor.FromHex("#2F569C"); - var originalInfoBgColor = GetColor.FromHex("#303030"); - var toolbarHoverColor = GetColor.FromHex("#2F569C"); + var hoverLabelColor = ColorUtil.FromHex("#2F569C"); + var originalInfoBgColor = ColorUtil.FromHex("#303030"); + var toolbarHoverColor = ColorUtil.FromHex("#2F569C"); // -- Local Func which is used as a callback for AnimateWidth() -- // -- so that when the large => small animation completes, -- @@ -970,7 +969,7 @@ void UnregisterHoverCallback() menuInfoContainer.schedule.Execute(() => { var menupg = VisualElementBaseAnimation.AnimateBackgroundColor(menuInfoContainer, startColor: originalInfoBgColor, - endColor: GetColor.FromHex("#212121"), + endColor: ColorUtil.FromHex("#212121"), durationMs: 600); menupg.Start(); }).StartingIn(0); @@ -1034,7 +1033,7 @@ void UnregisterHoverCallback() menuInfoContainer.schedule.Execute(() => { - VisualElementBaseAnimation.AnimateBackgroundColor(menuInfoContainer, GetColor.FromHex("#212121"), + VisualElementBaseAnimation.AnimateBackgroundColor(menuInfoContainer, ColorUtil.FromHex("#212121"), originalInfoBgColor, 400); }).StartingIn(0); @@ -1055,8 +1054,8 @@ void UnregisterHoverCallback() private void ImageAnimation(VisualElement imageButton, Func easing = null) // @formatter:on { // -- Image colors ------------------ - var originalImageColor = GetColor.FromHex("#000000"); - var targetImageColor = GetColor.FromHex("#607FAE"); + var originalImageColor = ColorUtil.FromHex("#000000"); + var targetImageColor = ColorUtil.FromHex("#607FAE"); const int durationInMs = 1000; const int delayInMs = 1000; @@ -1091,8 +1090,8 @@ private void FadeTextAnimation(Label fadeTextAnimationLabel, Func const int fadeOutTime = 500; const string newText = "then back to the original!"; - var originalTextColor = GetColor.FromHex("#BABABA"); - var animatedTextColor = GetColor.FromHex("#607FAE"); + var originalTextColor = ColorUtil.FromHex("#BABABA"); + var animatedTextColor = ColorUtil.FromHex("#607FAE"); fadeTextAnimationLabel.AnimFadeInSequence( newText, @@ -1110,10 +1109,10 @@ private void FadeColorAnimation(VisualElement fadeColorAnimationLabel, Func elementData = new Dictionary(); + + public ObjectElementData(Object obj) + { + objectReference = obj; + objectName = obj.name; + objectType = obj.GetType(); + } + } +} diff --git a/Editor/ElementData/ObjectElementData.cs.meta b/Editor/ElementData/ObjectElementData.cs.meta new file mode 100644 index 0000000..053c454 --- /dev/null +++ b/Editor/ElementData/ObjectElementData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f3d4326287ac4ae093198c9beb9aae17 +timeCreated: 1605940592 \ No newline at end of file diff --git a/Editor/id.instance.elementanimationtoolkit.Editor.asmdef b/Editor/id.instance.elementanimationtoolkit.Editor.asmdef index 79d0357..5e2e47c 100644 --- a/Editor/id.instance.elementanimationtoolkit.Editor.asmdef +++ b/Editor/id.instance.elementanimationtoolkit.Editor.asmdef @@ -1,8 +1,10 @@ { "name": "id.instance.elementanimationtoolkit.Editor", + "rootNamespace": "", "references": [ "id.instance.elementanimationtoolkit", - "id.instance.extensions" + "id.instance.extensions", + "id.instance.extensions.Editor" ], "includePlatforms": [ "Editor" diff --git a/Runtime/Animations.meta b/Runtime/Animations.meta new file mode 100644 index 0000000..0f24641 --- /dev/null +++ b/Runtime/Animations.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b7560ffbe5b349c69ed650903f3d0d7f +timeCreated: 1627084437 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/Animations/AnimationExtensions.cs b/Runtime/Animations/AnimationExtensions.cs similarity index 93% rename from Runtime/Scripts/Extensions/Animations/AnimationExtensions.cs rename to Runtime/Animations/AnimationExtensions.cs index 5844b3e..3da03f9 100644 --- a/Runtime/Scripts/Extensions/Animations/AnimationExtensions.cs +++ b/Runtime/Animations/AnimationExtensions.cs @@ -2,11 +2,11 @@ // -- Project : https://github.com/instance-id/ElementAnimationToolkit -- // -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- // ---------------------------------------------------------------------------- - +#if UNITY_EDITOR using System; using UnityEngine.UIElements; -namespace instance.id.EATK.Extensions +namespace instance.id.EATK { public static class AnimationExtensions { @@ -21,3 +21,4 @@ public static void ExecuteIn(this Action action, VisualElement element, long de } } } +#endif diff --git a/Runtime/Animations/AnimationExtensions.cs.meta b/Runtime/Animations/AnimationExtensions.cs.meta new file mode 100644 index 0000000..465e0c8 --- /dev/null +++ b/Runtime/Animations/AnimationExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a966a2e1775ebb175bf0da08c7acc7e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Animations/AnimationSequences.cs b/Runtime/Animations/AnimationSequences.cs similarity index 89% rename from Runtime/Scripts/Extensions/Animations/AnimationSequences.cs rename to Runtime/Animations/AnimationSequences.cs index 7fc4f8e..d808733 100644 --- a/Runtime/Scripts/Extensions/Animations/AnimationSequences.cs +++ b/Runtime/Animations/AnimationSequences.cs @@ -5,15 +5,18 @@ // -- Note: EATK is still currently being developed - API subject to change -- // ---------------------------------------------------------------------------- +#if UNITY_EDITOR using System; using System.Collections.Generic; using System.Linq; -using instance.id.Extensions; +using instance.id.EATK.Extensions; +// using instance.id.Extensions; +// using instance.id.Extensions; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.Experimental; -namespace instance.id.EATK.Extensions +namespace instance.id.EATK { public static class AnimationSequences { @@ -35,9 +38,9 @@ public static class AnimationSequences /// Function that can be called when the animation is completed /// Set a custom flex basis public static List> AnimCharacterSequence(this VisualElement target, Color color1, Color color2, int cascadeMs, int durationMS, - bool reverse = false, - Action callback = null, - float flexBasis = default) + bool reverse = false, + Action callback = null, + float flexBasis = default) { var animatedValues = new List>(); VisualElementStyleStore styleData = new VisualElementStyleStore(); @@ -45,6 +48,7 @@ public static List> AnimCharacterSequence(this Visua Label labelRef = new Label(); + if (target is AnimatedLabel label) { labelRef = label.GetLabel(); @@ -53,15 +57,6 @@ public static List> AnimCharacterSequence(this Visua styleData.SourceName = target.name; } - if (doDebug) - { - var table = new TableBuilder(); - table.WithHeader("Name", "Value", "GetProperties - AnimSeq - l-54"); - var fields = styleData.GetType().GetProperties().ToList(); - fields.ForEach(x => { table.WithRow(x.Name, x.GetValue(styleData)); }); - table.ToConsole(); - } - new VisualElement().Create(out var animatedContainer).ToUSS(nameof(animatedContainer), "animated-label-container"); animatedContainer.style.height = new StyleLength(StyleKeyword.Auto); @@ -71,7 +66,7 @@ public static List> AnimCharacterSequence(this Visua Label animLabel = new Label(); if (!doDebug) animLabel = styleData.FromStyleData(new Label(textString[i].ToString())); - else if (i == 0) animLabel = styleData.FromStyleData(new Label(textString[i].ToString()), doDebug); + else if (i == 0) animLabel = styleData.FromStyleData(new Label(textString[i].ToString())); if (!flexBasis.Equals(default)) animLabel.style.flexBasis = new Length(flexBasis); animLabel.SetMargin(); @@ -162,26 +157,26 @@ void AnimationComplete() public static void AnimFadeInSequence(this Label element, string newText = default, Color textColor = default, Color textDefaultColor = default, float fadeIn = 0f, - float display = 0f, - float fadeOut = 0f, - Func easing = null) + float display = 0f, + float fadeOut = 0f, + Func easing = null) { DoFadeInSequence(element, newText, textColor, textDefaultColor, fadeIn, display, fadeOut, element.text, easing); } public static void AnimFadeInSequence(this VisualElement element, Color textColor = default, Color textDefaultColor = default, float fadeIn = 0f, - float display = 0f, - float fadeOut = 0f, - Func easing = null) + float display = 0f, + float fadeOut = 0f, + Func easing = null) { DoFadeInSequence(element, default, textColor, textDefaultColor, fadeIn, display, fadeOut, easing: easing); } private static void DoFadeInSequence(this VisualElement element, string newText = default, Color textColor = default, Color textDefaultColor = default, float fadeIn = 0f, - float display = 0f, - float fadeOut = 0f, - string originalText = default, - Func easing = null) + float display = 0f, + float fadeOut = 0f, + string originalText = default, + Func easing = null) { var animFadeIn = new ValueAnimation(); var animWaiter = new ValueAnimation(); @@ -240,7 +235,7 @@ private static ValueAnimation DoFadeIn(VisualElement elementToFadeI { if (easing == null) easing = Easy.OutQuad; return elementToFadeIn.experimental.animation - .Start(new StyleValues {opacity = 0.Zero()}, new StyleValues {opacity = 1}, (int) durationMs) + .Start(new StyleValues { opacity = 0.Zero() }, new StyleValues { opacity = 1 }, (int)durationMs) .Ease(easing) .OnCompleted(callback); } @@ -251,7 +246,7 @@ private static ValueAnimation DoDisplayMessage(VisualElement elemen { if (easing == null) easing = Easy.OutQuad; return elementToDisplay.experimental.animation - .Start(new StyleValues {opacity = 1}, new StyleValues {opacity = 1}, (int) durationMs) + .Start(new StyleValues { opacity = 1 }, new StyleValues { opacity = 1 }, (int)durationMs) .Ease(easing) .OnCompleted(callback); } @@ -262,7 +257,7 @@ private static ValueAnimation DoFadeOut(VisualElement elementToFade { if (easing == null) easing = Easy.OutQuad; return elementToFadeOut.experimental.animation - .Start(new StyleValues {opacity = 1}, new StyleValues {opacity = 0.Zero()}, (int) durationMs) + .Start(new StyleValues { opacity = 1 }, new StyleValues { opacity = 0.Zero() }, (int)durationMs) .Ease(easing) .OnCompleted(callback); } @@ -270,3 +265,4 @@ private static ValueAnimation DoFadeOut(VisualElement elementToFade #endregion } } +#endif diff --git a/Runtime/Animations/AnimationSequences.cs.meta b/Runtime/Animations/AnimationSequences.cs.meta new file mode 100644 index 0000000..877e628 --- /dev/null +++ b/Runtime/Animations/AnimationSequences.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f917f23d0d6a11d70a8df25935fc87de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Animations/ContinuousAnimations.cs b/Runtime/Animations/ContinuousAnimations.cs similarity index 93% rename from Runtime/Scripts/Extensions/Animations/ContinuousAnimations.cs rename to Runtime/Animations/ContinuousAnimations.cs index fd17f9a..cf879f0 100644 --- a/Runtime/Scripts/Extensions/Animations/ContinuousAnimations.cs +++ b/Runtime/Animations/ContinuousAnimations.cs @@ -2,14 +2,14 @@ // -- Project : https://github.com/instance-id/ElementAnimationToolkit -- // -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- // ---------------------------------------------------------------------------- - +#if UNITY_EDITOR using System; -using instance.id.Extensions; +using instance.id.EATK.Extensions; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.Experimental; -namespace instance.id.EATK.Extensions +namespace instance.id.EATK { public static class ContinuousAnimations { @@ -125,19 +125,6 @@ void ReplaceBorderValues() element.resolvedStyle.paddingRight, element.resolvedStyle.paddingBottom); SetBorderValues(); - - if (debug) - { - var table = new TableBuilder(); - table.WithHeader("border", "padding"); - - table.WithRow(borderValues.x, paddingValues.x); - table.WithRow(borderValues.y, paddingValues.y); - table.WithRow(borderValues.z, paddingValues.z); - table.WithRow(borderValues.w, paddingValues.w); - - table.ToConsole(); - } } void DoCleanup() @@ -188,3 +175,4 @@ void PulseOut(IVisualElementScheduledItem repeated) } } } +#endif diff --git a/Runtime/Animations/ContinuousAnimations.cs.meta b/Runtime/Animations/ContinuousAnimations.cs.meta new file mode 100644 index 0000000..ae22ec3 --- /dev/null +++ b/Runtime/Animations/ContinuousAnimations.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae8f37542b1f4a5beb5d5ae5eab8c857 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Animations/Easy.cs b/Runtime/Animations/Easy.cs similarity index 98% rename from Runtime/Scripts/Extensions/Animations/Easy.cs rename to Runtime/Animations/Easy.cs index 0f1e571..d618ef9 100644 --- a/Runtime/Scripts/Extensions/Animations/Easy.cs +++ b/Runtime/Animations/Easy.cs @@ -1,12 +1,12 @@ // ---------------------------------------------------------------------------- // -- Project : https://github.com/instance-id/ElementAnimationToolkit -- // -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- -// ---------------------------------------------------------------------------- +// -- From com.unity.ui ------------------------------------------------------- using System; using UnityEngine; -namespace instance.id.EATK.Extensions +namespace instance.id.EATK { /// /// A collection of easing curves to be used with ValueAnimations. diff --git a/Runtime/Animations/Easy.cs.meta b/Runtime/Animations/Easy.cs.meta new file mode 100644 index 0000000..b45fd62 --- /dev/null +++ b/Runtime/Animations/Easy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d5992efa274c95d3288e72d437bc7ec5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Animations/HoverAnimations.cs b/Runtime/Animations/HoverAnimations.cs similarity index 98% rename from Runtime/Scripts/Extensions/Animations/HoverAnimations.cs rename to Runtime/Animations/HoverAnimations.cs index e260cfa..04964ed 100644 --- a/Runtime/Scripts/Extensions/Animations/HoverAnimations.cs +++ b/Runtime/Animations/HoverAnimations.cs @@ -2,14 +2,14 @@ // -- Project : https://github.com/instance-id/ElementAnimationToolkit -- // -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- // ---------------------------------------------------------------------------- - +#if UNITY_EDITOR using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.Experimental; -namespace instance.id.EATK.Extensions +namespace instance.id.EATK { public static class HoverAnimations { @@ -22,8 +22,8 @@ public static class HoverAnimations /// /// /// - /// var originalColor = GetColor.FromHex("#BABABA"); - /// var hoverColor = GetColor.FromHex("#2F569C"); + /// var originalColor = ColorUtil.FromHex("#BABABA"); + /// var hoverColor = ColorUtil.FromHex("#2F569C"); /// /// label.HoverColor(originalColor, hoverColor); /// @@ -107,8 +107,8 @@ public static void HoverColor(this T target, StyleColor original, Color hover /// /// /// - /// var originalColor = GetColor.FromHex("#BABABA"); - /// var hoverBGColor = GetColor.FromHex("#2F569C"); + /// var originalColor = ColorUtil.FromHex("#BABABA"); + /// var hoverBGColor = ColorUtil.FromHex("#2F569C"); /// /// label.HoverBackground(originalColor, hoverBGColor); /// @@ -404,3 +404,4 @@ public static void HoverToolTip(this VisualElement target, Action callback) #endregion } } +#endif diff --git a/Runtime/Animations/HoverAnimations.cs.meta b/Runtime/Animations/HoverAnimations.cs.meta new file mode 100644 index 0000000..7f95d9d --- /dev/null +++ b/Runtime/Animations/HoverAnimations.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c99477eb0badf41ea23ce66311d2340 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Animations/VisualElementBaseAnimation.cs b/Runtime/Animations/VisualElementBaseAnimation.cs similarity index 61% rename from Runtime/Scripts/Extensions/Animations/VisualElementBaseAnimation.cs rename to Runtime/Animations/VisualElementBaseAnimation.cs index a17c389..ce09361 100644 --- a/Runtime/Scripts/Extensions/Animations/VisualElementBaseAnimation.cs +++ b/Runtime/Animations/VisualElementBaseAnimation.cs @@ -2,14 +2,14 @@ // -- Project : https://github.com/instance-id/ElementAnimationToolkit -- // -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- // ---------------------------------------------------------------------------- - +#if UNITY_EDITOR using System; -using instance.id.Extensions; +using instance.id.EATK.Extensions; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.Experimental; -namespace instance.id.EATK.Extensions +namespace instance.id.EATK { public static class VisualElementBaseAnimation { @@ -27,14 +27,27 @@ public static class VisualElementBaseAnimation /// Function that can be called when the animation is completed /// Controls the animation timing curve mathematically public static ValueAnimation AnimateBackgroundColor(this VisualElement target, Color startColor, Color endColor, int durationMs, Action callback = null, - Func easing = null) + Func easing = null) { if (easing == null) easing = Easy.EaseInOutQuint; return target.experimental.animation - .Start(new StyleValues {backgroundColor = startColor}, new StyleValues {backgroundColor = endColor}, durationMs) + .Start(new StyleValues { backgroundColor = startColor }, new StyleValues { backgroundColor = endColor }, durationMs) .Ease(easing) .OnCompleted(callback); } + + /// + /// Animate the background color of target element to desired value + /// + /// VisualElement to animate + /// Initial color of element as hexadecimal string (ex. "A4B5C6") + /// The desired end result color which to animate + /// The length of time in which the animation will occur(in milliseconds) + /// Function that can be called when the animation is completed + /// Controls the animation timing curve mathematically + public static ValueAnimation AnimateBackgroundColor(this VisualElement target, string startColor, string endColor, int durationMs, Action callback = null, + Func easing = null) => + AnimateBackgroundColor(target, startColor.EnsureHex().FromHex(), endColor.EnsureHex().FromHex(), durationMs, callback, easing); // ------------------------------------------- @AnimateBorderColor // --------------------------------------------------------------- @@ -48,15 +61,28 @@ public static ValueAnimation AnimateBackgroundColor(this VisualElem /// Function that can be called when the animation is completed /// Controls the animation timing curve mathematically public static ValueAnimation AnimateBorderColor(this VisualElement target, Color startColor, Color endColor, int durationMs, Action callback = null, - Func easing = null) + Func easing = null) { if (easing == null) easing = Easy.EaseInOutQuint; return target.experimental.animation - .Start(new StyleValues {borderColor = startColor}, new StyleValues {borderColor = endColor}, durationMs) + .Start(new StyleValues { borderColor = startColor }, new StyleValues { borderColor = endColor }, durationMs) .Ease(easing) .OnCompleted(callback); } + /// + /// Animate the background color of target element to desired value + /// + /// VisualElement to animate + /// Initial color of element as hexadecimal string (ex. "A4B5C6") + /// The desired end result color which to animate + /// The length of time in which the animation will occur(in milliseconds) + /// Function that can be called when the animation is completed + /// Controls the animation timing curve mathematically + public static ValueAnimation AnimateBorderColor(this VisualElement target, string startColor, string endColor, int durationMs, Action callback = null, + Func easing = null) => + AnimateBorderColor(target, startColor.EnsureHex().FromHex(), endColor.EnsureHex().FromHex(), durationMs, callback, easing); + // ------------------------------------------------- @AnimateColor // --------------------------------------------------------------- /// @@ -69,15 +95,28 @@ public static ValueAnimation AnimateBorderColor(this VisualElement /// Function that can be called when the animation is completed /// Controls the animation timing curve mathematically public static ValueAnimation AnimateColor(this VisualElement target, Color startColor, Color endColor, int durationMs, Action callback = null, - Func easing = null) + Func easing = null) { if (easing == null) easing = Easy.EaseInOutQuint; return target.experimental.animation - .Start(new StyleValues {color = startColor}, new StyleValues {color = endColor}, durationMs) + .Start(new StyleValues { color = startColor }, new StyleValues { color = endColor }, durationMs) .Ease(easing) .OnCompleted(callback); } + /// + /// Animate the background color of target element to desired value + /// + /// VisualElement to animate + /// Initial color of element as hexadecimal string (ex. "A4B5C6") + /// The desired end result color which to animate + /// The length of time in which the animation will occur(in milliseconds) + /// Function that can be called when the animation is completed + /// Controls the animation timing curve mathematically + public static ValueAnimation AnimateColor(this VisualElement target, string startColor, string endColor, int durationMs, Action callback = null, + Func easing = null) => + AnimateColor(target, startColor.EnsureHex().FromHex(), endColor.EnsureHex().FromHex(), durationMs, callback, easing); + // ---------------------------------------- @AnimateImageTintColor // --------------------------------------------------------------- /// @@ -90,14 +129,27 @@ public static ValueAnimation AnimateColor(this VisualElement target /// Function that can be called when the animation is completed /// Controls the animation timing curve mathematically public static ValueAnimation AnimateImageTintColor(this VisualElement target, Color startColor, Color endColor, int durationMs, Action callback = null, - Func easing = null) + Func easing = null) { if (easing == null) easing = Easy.EaseInOutQuint; return target.experimental.animation - .Start(new StyleValues {unityBackgroundImageTintColor = startColor}, new StyleValues {unityBackgroundImageTintColor = endColor}, durationMs) + .Start(new StyleValues { unityBackgroundImageTintColor = startColor }, new StyleValues { unityBackgroundImageTintColor = endColor }, durationMs) .Ease(easing) .OnCompleted(callback); } + + /// + /// Animate the background color of target element to desired value + /// + /// VisualElement to animate + /// Initial color of element as hexadecimal string (ex. "A4B5C6") + /// The desired end result color which to animate + /// The length of time in which the animation will occur(in milliseconds) + /// Function that can be called when the animation is completed + /// Controls the animation timing curve mathematically + public static ValueAnimation AnimateImageTintColor(this VisualElement target, string startColor, string endColor, int durationMs, Action callback = null, + Func easing = null) => + AnimateImageTintColor(target, startColor.EnsureHex().FromHex(), endColor.EnsureHex().FromHex(), durationMs, callback, easing); // ----------------------------------------------- @AnimateOpacity // --------------------------------------------------------------- @@ -111,14 +163,14 @@ public static ValueAnimation AnimateImageTintColor(this VisualEleme /// Function that can be called when the animation is completed /// Controls the animation timing curve mathematically public static ValueAnimation AnimateOpacity(this VisualElement target, float startOpacity, float endOpacity, int durationMs, Action callback = null, - Func easing = null) + Func easing = null) { if (startOpacity == 0) startOpacity = 0.Zero(); if (endOpacity == 0) endOpacity = 0.Zero(); if (easing == null) easing = Easy.EaseInOutQuint; return target.experimental.animation - .Start(new StyleValues {opacity = startOpacity}, new StyleValues {opacity = endOpacity}, durationMs) + .Start(new StyleValues { opacity = startOpacity }, new StyleValues { opacity = endOpacity }, durationMs) .Ease(easing) .OnCompleted(callback); } @@ -135,11 +187,11 @@ public static ValueAnimation AnimateOpacity(this VisualElement targ /// Function that can be called when the animation is completed /// Controls the animation timing curve mathematically public static ValueAnimation AnimateWidth(this VisualElement target, float startWidth, float endWidth, int durationMs, Action callback = null, - Func easing = null) + Func easing = null) { if (easing == null) easing = Easy.EaseInOutQuint; return target.experimental.animation - .Start(new StyleValues {width = startWidth}, new StyleValues {width = endWidth}, durationMs) + .Start(new StyleValues { width = startWidth }, new StyleValues { width = endWidth }, durationMs) .Ease(easing) .OnCompleted(callback); } @@ -156,11 +208,11 @@ public static ValueAnimation AnimateWidth(this VisualElement target /// Function that can be called when the animation is completed /// Controls the animation timing curve mathematically public static ValueAnimation AnimateHeight(this VisualElement target, float startHeight, float endHeight, int durationMs, Action callback = null, - Func easing = null) + Func easing = null) { if (easing == null) easing = Easy.EaseInOutQuint; return target.experimental.animation - .Start(new StyleValues {height = startHeight}, new StyleValues {height = endHeight}, durationMs) + .Start(new StyleValues { height = startHeight }, new StyleValues { height = endHeight }, durationMs) .Ease(easing) .OnCompleted(callback); } @@ -168,3 +220,4 @@ public static ValueAnimation AnimateHeight(this VisualElement targe #endregion } } +#endif diff --git a/Runtime/Scripts/Extensions/Animations/VisualElementBaseAnimation.cs.meta b/Runtime/Animations/VisualElementBaseAnimation.cs.meta similarity index 83% rename from Runtime/Scripts/Extensions/Animations/VisualElementBaseAnimation.cs.meta rename to Runtime/Animations/VisualElementBaseAnimation.cs.meta index c154278..bcaa3fc 100644 --- a/Runtime/Scripts/Extensions/Animations/VisualElementBaseAnimation.cs.meta +++ b/Runtime/Animations/VisualElementBaseAnimation.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c087b2714cf0fe34b8a42b57229a9344 +guid: 7daebc746d4b79eb8aa9be9bfce73cb2 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Runtime/Elements.meta b/Runtime/Elements.meta new file mode 100644 index 0000000..f481bb2 --- /dev/null +++ b/Runtime/Elements.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: facd88093d48418f84ec164ff7314b0b +timeCreated: 1621477552 \ No newline at end of file diff --git a/Runtime/Elements/AnimatedFoldout.meta b/Runtime/Elements/AnimatedFoldout.meta new file mode 100644 index 0000000..5f8c39a --- /dev/null +++ b/Runtime/Elements/AnimatedFoldout.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7fe32b164027cdd86b486cc2642ae2a5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedFoldout/AnimatedFoldout.cs b/Runtime/Elements/AnimatedFoldout/AnimatedFoldout.cs similarity index 99% rename from Runtime/Scripts/Extensions/Elements/AnimatedFoldout/AnimatedFoldout.cs rename to Runtime/Elements/AnimatedFoldout/AnimatedFoldout.cs index 1bd6dfb..aa4f373 100644 --- a/Runtime/Scripts/Extensions/Elements/AnimatedFoldout/AnimatedFoldout.cs +++ b/Runtime/Elements/AnimatedFoldout/AnimatedFoldout.cs @@ -2,11 +2,8 @@ // -- Project : https://github.com/instance-id/ElementAnimationToolkit -- // -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- // ---------------------------------------------------------------------------- - -using System; +#if UNITY_EDITOR using instance.id.EATK.Extensions; -using instance.id.Extensions; -using UnityEngine; using UnityEngine.UIElements; namespace instance.id.EATK @@ -170,3 +167,4 @@ public UxmlTraits() } } } +#endif diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedFoldout/AnimatedFoldout.cs.meta b/Runtime/Elements/AnimatedFoldout/AnimatedFoldout.cs.meta similarity index 100% rename from Runtime/Scripts/Extensions/Elements/AnimatedFoldout/AnimatedFoldout.cs.meta rename to Runtime/Elements/AnimatedFoldout/AnimatedFoldout.cs.meta diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedFoldout/UIElementExpander.cs b/Runtime/Elements/AnimatedFoldout/UIElementExpander.cs similarity index 99% rename from Runtime/Scripts/Extensions/Elements/AnimatedFoldout/UIElementExpander.cs rename to Runtime/Elements/AnimatedFoldout/UIElementExpander.cs index 15db53f..711d320 100644 --- a/Runtime/Scripts/Extensions/Elements/AnimatedFoldout/UIElementExpander.cs +++ b/Runtime/Elements/AnimatedFoldout/UIElementExpander.cs @@ -4,7 +4,7 @@ // ---------------------------------------------------------------------------- using System; -using instance.id.EATK.Extensions; +using instance.id.EATK; using JetBrains.Annotations; using UnityEngine.UIElements; using UnityEngine.UIElements.Experimental; diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedFoldout/UIElementExpander.cs.meta b/Runtime/Elements/AnimatedFoldout/UIElementExpander.cs.meta similarity index 100% rename from Runtime/Scripts/Extensions/Elements/AnimatedFoldout/UIElementExpander.cs.meta rename to Runtime/Elements/AnimatedFoldout/UIElementExpander.cs.meta diff --git a/Runtime/Elements/AnimatedLabel.meta b/Runtime/Elements/AnimatedLabel.meta new file mode 100644 index 0000000..436f96c --- /dev/null +++ b/Runtime/Elements/AnimatedLabel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 27a6b9aa77169b4c2aaa64cdebf1553f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedLabel/AnimatedLabel.cs b/Runtime/Elements/AnimatedLabel/AnimatedLabel.cs similarity index 99% rename from Runtime/Scripts/Extensions/Elements/AnimatedLabel/AnimatedLabel.cs rename to Runtime/Elements/AnimatedLabel/AnimatedLabel.cs index 354e790..effad7c 100644 --- a/Runtime/Scripts/Extensions/Elements/AnimatedLabel/AnimatedLabel.cs +++ b/Runtime/Elements/AnimatedLabel/AnimatedLabel.cs @@ -3,10 +3,11 @@ // -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- // ---------------------------------------------------------------------------- +#if UNITY_EDITOR + + using System; -using System.Collections.Generic; using instance.id.EATK.Extensions; -using instance.id.Extensions; using UnityEngine; using UnityEngine.UIElements; // ReSharper disable UnusedMember.Global @@ -199,3 +200,4 @@ public static bool UnregisterValueChangedCallback( } } } +#endif diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedLabel/AnimatedLabel.cs.meta b/Runtime/Elements/AnimatedLabel/AnimatedLabel.cs.meta similarity index 100% rename from Runtime/Scripts/Extensions/Elements/AnimatedLabel/AnimatedLabel.cs.meta rename to Runtime/Elements/AnimatedLabel/AnimatedLabel.cs.meta diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedLabel/Style.meta b/Runtime/Elements/AnimatedLabel/Style.meta similarity index 100% rename from Runtime/Scripts/Extensions/Elements/AnimatedLabel/Style.meta rename to Runtime/Elements/AnimatedLabel/Style.meta diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedLabel/Style/AnimatedLabel.uss b/Runtime/Elements/AnimatedLabel/Style/AnimatedLabel.uss similarity index 100% rename from Runtime/Scripts/Extensions/Elements/AnimatedLabel/Style/AnimatedLabel.uss rename to Runtime/Elements/AnimatedLabel/Style/AnimatedLabel.uss diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedLabel/Style/AnimatedLabel.uss.meta b/Runtime/Elements/AnimatedLabel/Style/AnimatedLabel.uss.meta similarity index 100% rename from Runtime/Scripts/Extensions/Elements/AnimatedLabel/Style/AnimatedLabel.uss.meta rename to Runtime/Elements/AnimatedLabel/Style/AnimatedLabel.uss.meta diff --git a/Runtime/Elements/BetterTextField.meta b/Runtime/Elements/BetterTextField.meta new file mode 100644 index 0000000..d0b927b --- /dev/null +++ b/Runtime/Elements/BetterTextField.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c533ce28fa8415d8d92f9a46999ba5f3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Elements/BetterTextField/MaskedInputField.cs b/Runtime/Elements/BetterTextField/MaskedInputField.cs similarity index 92% rename from Runtime/Scripts/Extensions/Elements/BetterTextField/MaskedInputField.cs rename to Runtime/Elements/BetterTextField/MaskedInputField.cs index bc51166..dc38e8e 100644 --- a/Runtime/Scripts/Extensions/Elements/BetterTextField/MaskedInputField.cs +++ b/Runtime/Elements/BetterTextField/MaskedInputField.cs @@ -1,13 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; -using instance.id.Extensions; +using instance.id.EATK.Extensions; using JetBrains.Annotations; using UnityEngine; using UnityEngine.UIElements; -using Cursor = UnityEngine.UIElements.Cursor; - -namespace instance.id.EATK.Extensions + #if UNITY_EDITOR +namespace instance.id.EATK { // Hopefully these features will eventually be in the default TextField. public class MaskedInputField : TextField @@ -51,10 +50,10 @@ public MaskedInputField() style.unityFont = monoFont; var textInputBase = this.Q("unity-text-input"); - textInputBase.NameAsUSS(nameof(textInputBase)); + VisualElementExtension.NameAsUSS(textInputBase, nameof(textInputBase)); textInputBase.style.display = DisplayStyle.Flex; textInputBase.style.color = new StyleColor(StyleKeyword.Initial); - textInputBase.SetBorderWidth(2); + VisualElementExtension.SetBorderWidth(textInputBase, 2); maskedText = new TextField { @@ -64,16 +63,16 @@ public MaskedInputField() }; maskedInput = maskedText.Q("unity-text-input"); maskedInput.pickingMode = PickingMode.Ignore; - maskedInput.NameAsUSS(nameof(maskedInput)); + VisualElementExtension.NameAsUSS(maskedInput, nameof(maskedInput)); - maskedText.NameAsUSS(nameof(maskedText)); + VisualElementExtension.NameAsUSS(maskedText, nameof(maskedText)); maskedText.AddToClassList(UssClassName); Add(maskedText); this.RegisterCallback(evt => { - this.SelectRangeDelayed(maskedText.text.Length, maskedText.text.Length); + VisualElementExtension.SelectRangeDelayed(this, maskedText.text.Length, maskedText.text.Length); evt.StopPropagation(); }); @@ -105,7 +104,7 @@ private void DeferredExecution(GeometryChangedEvent evt) maskedText.style.right = -4; maskedText.style.top = -3; maskedText.style.backgroundColor = new StyleColor(StyleKeyword.Initial); - maskedText.SetBorderWidth(2); + VisualElementExtension.SetBorderWidth(maskedText, 2); maskedInput.BringToFront(); } @@ -207,3 +206,4 @@ public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext } } } +#endif diff --git a/Runtime/Scripts/Extensions/Elements/BetterTextField/MaskedInputField.cs.meta b/Runtime/Elements/BetterTextField/MaskedInputField.cs.meta similarity index 100% rename from Runtime/Scripts/Extensions/Elements/BetterTextField/MaskedInputField.cs.meta rename to Runtime/Elements/BetterTextField/MaskedInputField.cs.meta diff --git a/Runtime/Scripts/Extensions/Elements/BetterTextField/Style.meta b/Runtime/Elements/BetterTextField/Style.meta similarity index 100% rename from Runtime/Scripts/Extensions/Elements/BetterTextField/Style.meta rename to Runtime/Elements/BetterTextField/Style.meta diff --git a/Runtime/Scripts/Extensions/Elements/BetterTextField/Style/MaskedInputField.uss b/Runtime/Elements/BetterTextField/Style/MaskedInputField.uss similarity index 100% rename from Runtime/Scripts/Extensions/Elements/BetterTextField/Style/MaskedInputField.uss rename to Runtime/Elements/BetterTextField/Style/MaskedInputField.uss diff --git a/Runtime/Scripts/Extensions/Elements/BetterTextField/Style/MaskedInputField.uss.meta b/Runtime/Elements/BetterTextField/Style/MaskedInputField.uss.meta similarity index 100% rename from Runtime/Scripts/Extensions/Elements/BetterTextField/Style/MaskedInputField.uss.meta rename to Runtime/Elements/BetterTextField/Style/MaskedInputField.uss.meta diff --git a/Runtime/Scripts/Extensions/Animations.meta b/Runtime/Scripts/Extensions/Animations.meta deleted file mode 100644 index 92cfea2..0000000 --- a/Runtime/Scripts/Extensions/Animations.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 70d4345ce6774aa382f3f82acbf01470 -timeCreated: 1605034321 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/Animations/AnimationExtensions.cs.meta b/Runtime/Scripts/Extensions/Animations/AnimationExtensions.cs.meta deleted file mode 100644 index c6c8c8d..0000000 --- a/Runtime/Scripts/Extensions/Animations/AnimationExtensions.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 8cbd629ea8e3480bb4b1846927ea1d13 -timeCreated: 1605586125 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/Animations/AnimationSequences.cs.meta b/Runtime/Scripts/Extensions/Animations/AnimationSequences.cs.meta deleted file mode 100644 index 260b01e..0000000 --- a/Runtime/Scripts/Extensions/Animations/AnimationSequences.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 6dd0f9490f8c4e18b94a848bf1b195a7 -timeCreated: 1605034348 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/Animations/ContinuousAnimations.cs.meta b/Runtime/Scripts/Extensions/Animations/ContinuousAnimations.cs.meta deleted file mode 100644 index 5d87fd4..0000000 --- a/Runtime/Scripts/Extensions/Animations/ContinuousAnimations.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 5986c86c7e4a49d982379d7f458592f9 -timeCreated: 1605035012 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/Animations/Easy.cs.meta b/Runtime/Scripts/Extensions/Animations/Easy.cs.meta deleted file mode 100644 index 0533d72..0000000 --- a/Runtime/Scripts/Extensions/Animations/Easy.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 7d30ed12c9a248749c430f87c984c78d -timeCreated: 1605069120 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/Animations/HoverAnimations.cs.meta b/Runtime/Scripts/Extensions/Animations/HoverAnimations.cs.meta deleted file mode 100644 index ee03361..0000000 --- a/Runtime/Scripts/Extensions/Animations/HoverAnimations.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 2a6bc67b6cec436cb796d9063af449c8 -timeCreated: 1605034507 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/AssetFileExtensions.cs b/Runtime/Scripts/Extensions/AssetFileExtensions.cs new file mode 100644 index 0000000..eb80d54 --- /dev/null +++ b/Runtime/Scripts/Extensions/AssetFileExtensions.cs @@ -0,0 +1,400 @@ +// ---------------------------------------------------------------------------- +// -- Project : https://github.com/instance-id/Extensions -- +// -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- +// ---------------------------------------------------------------------------- + +#if UNITY_EDITOR +using UnityEditor; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.UIElements; +using Object = UnityEngine.Object; + +namespace instance.id.EATK.Extensions +{ + public static class AssetFileExtensions + { + private static string searchStr = "a:all t:"; + public static StyleSheet GetStyleSheet(this Type type, string name = default, bool suffix = false, bool debug = false) + { + var sheetName = name == default && !suffix ? type.Name : suffix ? $"{type.Name}{name}" : name; + var str = $"{searchStr}StyleSheet {sheetName}"; + if (debug) Debug.Log($"ScriptDir: {type.GetScriptPath()} {type.GetScriptPath() + $"/Style/{sheetName}Style.uss"}"); + + var sheet = AssetDatabase.LoadAssetAtPath(type.GetScriptPath() + $"/Style/{sheetName}.uss"); + if (sheet == null) sheet = AssetDatabase.FindAssets(str) + .Select(guid => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid))) + .ToList().FirstOrDefault(); + return sheet; + } + + public static StyleSheet GetLocalStyleSheet(this Type type, string name = default, bool suffix = false, bool debug = false, [CallerFilePath] string sourceFilePath = "") + { + var sheetName = name == default && !suffix ? type.Name : suffix ? $"{type.Name}{name}" : name; + var path = new Uri(Application.dataPath).MakeRelativeUri(new Uri(sourceFilePath)).ToString(); + + if (debug) Debug.Log($"ScriptDir: {path} {path + $"/Style/{sheetName}.uss"}"); + return AssetDatabase.LoadAssetAtPath(path + $"/Style/{sheetName}.uss"); + } + + public static StyleSheet GetStyleSheet(this string path, string name, bool debug = false) + { + var sheetName = name; + if (debug) Debug.Log($"ScriptDir: {path} {path + $"/Style/{sheetName}.uss"}"); + return AssetDatabase.LoadAssetAtPath(path + $"/Style/{sheetName}.uss"); + } + + public static Texture2D GetImage(this Type type, string name) + { + Texture2D image; + image = AssetDatabase.LoadAssetAtPath(type.SearchScriptPath(getFolder: true) + $"/Images/{name}"); + if (image == null) Debug.Log($"Cannot locate : {name} {image}"); + return image; + } + + public static Font GetFont(string fontName) + { + var searchTerm = $"t:Font {fontName}"; + return AssetDatabase + .FindAssets(searchTerm) + .Select(guid => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid))) + .FirstOrDefault(); + } + + public static T GetObjectOfType(this Type type, string name) where T : Object + { + var searchTerm = $"t:{type.Name} {name}"; + return AssetDatabase + .FindAssets(searchTerm) + .Select(guid => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid))) + .FirstOrDefault(); + } + + public static string GetScriptPath(this object obj, [CallerFilePath] string sourceFilePath = "") + { + return new Uri(Application.dataPath).MakeRelativeUri(new Uri(sourceFilePath)).ToString(); + } + + /// + /// Locates the requested script file by type and searches the file for the locator string. If found, the line number is captured. + /// Then returns the script file as Type of Object and the line number as an out parameter. + /// + /// The Type of the file which initially called the JumpToCode method + /// Class containing data needed to determine the jump type and location + /// The line number of the locator string, if found. + /// Deprecated: Used to mark if the locator is on a different line than the calling method + /// The located script file from the AssetDatabase as Type of Object + public static Object GetScriptFile(this Type type, JumpTarget jumpTarget, out int lineNum, bool externalLocator = false) + { + var fullPath = ""; + var scriptFile = new Object(); + var guidArray = AssetDatabase.FindAssets($"t:Script {type.Name}"); + if (guidArray.Length == 1) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guidArray[0]); + scriptFile = AssetDatabase.LoadAssetAtPath(assetPath); + fullPath = Path.GetFullPath(assetPath); + } + + if (jumpTarget.Locator.StartsWith("_")) jumpTarget.Locator = jumpTarget.Locator.Replace("_", "@"); + else if (externalLocator || !jumpTarget.Locator.Contains(".")) + jumpTarget.Locator = $"@{jumpTarget.Locator}"; + + lineNum = fullPath.LocateLineNumber(jumpTarget.Locator); + return scriptFile; + } + + /// + /// Locates the requested script file by type and searches the file for the locator string. If found, the line number is captured. + /// Then returns the script file as Type of Object and the line number as an out parameter. + /// + /// The Type of the file which initially called the JumpToCode method + /// The string which is used to locate the desired line number in which to jump + /// The line number of the locator string, if found. + /// Deprecated: Used to mark if the locator is on a different line than the calling method + /// The located script file from the AssetDatabase as Type of Object + public static Object GetScriptFile(this Type type, string locator, out int lineNum, bool externalLocator = false) + { + var fullPath = ""; + var scriptFile = new Object(); + var guidArray = AssetDatabase.FindAssets($"t:Script {type.Name}"); + if (guidArray.Length == 1) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guidArray[0]); + scriptFile = AssetDatabase.LoadAssetAtPath(assetPath); + fullPath = Path.GetFullPath(assetPath); + } + + if (locator.StartsWith("_")) locator = locator.Replace("_", "@"); + else if (externalLocator || !locator.Contains(".")) + locator = $"@{locator}"; + + lineNum = fullPath.LocateLineNumber(locator); + return scriptFile; + } + + /// + /// Locates the requested Stylesheet file searches the file for the locator string. If found, the line number is captured. + /// Then returns the script file as Type of Object and the line number as an out parameter. + /// + /// The Type of the file which initially called the JumpToCode method + /// Class containing data needed to determine the jump type and location + /// The line number of the locator string, if found. + /// Deprecated: Used to mark if the locator is on a different line than the calling method + /// The located script file from the AssetDatabase as Type of Object + public static Object GetStylesheetFile(this Type type, JumpTarget jumpTarget, out int lineNum, bool externalLocator = false) + { + var fullPath = ""; + var scriptFile = new Object(); + var guidArray = AssetDatabase.FindAssets($"t:Stylesheet {type.Name}"); + if (guidArray.Length == 1) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guidArray[0]); + scriptFile = AssetDatabase.LoadAssetAtPath(assetPath); + fullPath = Path.GetFullPath(assetPath); + } + else Debug.Log($"Stylesheet: {type.Name} not found."); + + if (jumpTarget.Locator.StartsWith("_")) jumpTarget.Locator = jumpTarget.Locator.Replace("_", "@"); + else if (externalLocator || !jumpTarget.Locator.Contains(".")) + jumpTarget.Locator = $"@{jumpTarget.Locator}"; + + lineNum = fullPath.LocateLineNumber(jumpTarget.Locator); + return scriptFile; + } + + /// + /// Locates the requested Stylesheet file searches the file for the locator string. If found, the line number is captured. + /// Then returns the script file as Type of Object and the line number as an out parameter. + /// + /// The Type of the file which initially called the JumpToCode method + /// The string which is used to locate the desired line number in which to jump + /// The line number of the locator string, if found. + /// Deprecated: Used to mark if the locator is on a different line than the calling method + /// The located script file from the AssetDatabase as Type of Object + public static Object GetStylesheetFile(this Type type, string locator, out int lineNum, bool externalLocator = false) + { + var fullPath = ""; + var scriptFile = new Object(); + var guidArray = AssetDatabase.FindAssets($"t:Stylesheet {type.Name}"); + if (guidArray.Length == 1) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guidArray[0]); + scriptFile = AssetDatabase.LoadAssetAtPath(assetPath); + fullPath = Path.GetFullPath(assetPath); + } + else Debug.Log($"Stylesheet: {type.Name} not found."); + + if (locator.StartsWith("_")) locator = locator.Replace("_", "@"); + else if (externalLocator || !locator.Contains(".")) + locator = $"@{locator}"; + + lineNum = fullPath.LocateLineNumber(locator); + return scriptFile; + } + + /// + /// Locate the local path of a script file + /// + /// + /// + /// + /// + public static string SearchScriptPath(this Type type, bool getName = false, bool getFolder = false) + { + string guidValue = ""; + var guidArray = AssetDatabase.FindAssets($"t:Script {type.Name}"); + if (guidArray.Length > 1) + { + foreach (var guid in guidArray) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guid); + var folderPath = Directory.GetParent(assetPath); + var filePath = Path.ChangeExtension(assetPath, null); + var filename = Path.GetFileNameWithoutExtension(assetPath); + + if (filename != type.Name) continue; + if (getFolder) return folderPath.ToString(); + if (getName) return filePath; + + guidValue = guid; + break; + } + } + else if (guidArray.Length == 1) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guidArray[0]); + var folderPath = Directory.GetParent(assetPath); + var filePath = Path.ChangeExtension(assetPath, null); + var filename = Path.GetFileNameWithoutExtension(assetPath); + + if (filename != type.Name) return AssetDatabase.GUIDToAssetPath(guidValue); + + if (getFolder) return folderPath.ToString(); + if (getName) return filePath; + guidValue = guidArray[0]; + } + else + { + Debug.LogErrorFormat("Unable to locate {0}", type.Name); + return null; + } + + + return AssetDatabase.GUIDToAssetPath(guidValue); + } + + // -- UIElement extension that lets you jump straight ------------ + // -- to the line of code in which this method is used ----------- + /// + /// From an elements context menu, jump straight to a specific line of code in your IDE + /// (if supported by your specific IDE) by either a string of text, or by keyword in a comment beginning with @ + /// + /// + /// The element in which to add the "Jump to Code" context menu + /// The Type is used to locate the script/file in which you wish to jump to. + /// By default the Type is the type of the script in which JumpToCode is called. + /// If Type is passed as a parameter, this Type is used instead to locate the script/file. + /// The line of code in which to jump to is found by locating the "locator" string. This is where in the code in which to jump + /// + /// The directory location in which the code file exists. Notes, when variable is omitted, this path is found automatically via reflection + public static void JumpToCode(this VisualElement element, string locator = default, bool externalKeyword = false, string menuItemLabel = default, + string menuItemUSSLabel = default, + Type type = null, [CallerFilePath] string path = "", bool jumpUSS = false, bool jumpAnimation = false, Dictionary additionalMenus = null, + List jumpTargets = null) + { + element.AddManipulator(new ContextualMenuManipulator(evt => + { + Type GetIncomingType() + { + if (type != null) return type; + // -- Get Type name via script name, as they should be the same ----- + var typeName = Path.GetFileNameWithoutExtension(path); + + // -- Get type from TypeCache API: Much faster than reflection ------ + var types = TypeCache.GetTypesDerivedFrom(); + type = types.FirstOrDefault(x => x.Name == typeName); + if (type != null) return type; + + Debug.LogError("Error: Could not get proper type of desired file in which to jump."); + + // -- If it's not found, try a last ditch (probably failed) effort -- + if (type == null) type = Type.GetType($"instance.id.{typeName}"); + if (type == null) type = Type.GetType($"instance.id.Extensions.{typeName}"); + // -- If *still* not found, admit defeat ----------------------------- + if (type == null) Debug.LogError($"Could not locate Type: {typeName}"); + return type; + } + + jumpTargets?.ForEach(t => + { + switch (t.JumpType) + { + case JumpType.Element: + evt.menu.AppendAction( + t.MenuTitle = t.MenuTitle != default ? t.MenuTitle : $"Jump To {t.JumpType.ToString()}", + CallCodeJump, a => DropdownMenuAction.Status.Normal, + (GetIncomingType(), t).ToTuple()); + break; + case JumpType.Animation: + evt.menu.AppendAction( + t.MenuTitle = t.MenuTitle != default ? t.MenuTitle : $"Jump To {t.JumpType.ToString()}", + CallCodeJump, a => DropdownMenuAction.Status.Normal, + (GetIncomingType(), t).ToTuple()); + break; + case JumpType.USS: + evt.menu.AppendAction( + t.MenuTitle = t.MenuTitle != default ? t.MenuTitle : $"Jump To {t.JumpType.ToString()}", + CallUSSJump, a => DropdownMenuAction.Status.Normal, + (GetIncomingType(), t).ToTuple()); + break; + default: + throw new ArgumentOutOfRangeException(); + } + }); + + if (locator != null) + { + evt.menu.AppendAction( + menuItemLabel = menuItemLabel != default ? menuItemLabel : "Jump To Code", + CallStringCodeJump, a => DropdownMenuAction.Status.Normal, + (GetIncomingType(), locator).ToTuple()); + } + + // ------------------------------------------------------- + // -- Dynamically added context menus per element -------- + additionalMenus?.ForEach(x => // @formatter:off + { + evt.menu.AppendAction(x.Key, CallActionMenu, + a => DropdownMenuAction.Status.Normal, x.Value); + }); // @formatter:on + + void CallActionMenu(DropdownMenuAction dropdownMenuAction) + { + if (dropdownMenuAction.userData is Action action) action.Invoke(); + } + + // ------------------------------------------------------- + // -- Jump to editor code menu --------------------------- + void CallCodeJump(DropdownMenuAction dropdownMenuAction) + { + var uData = dropdownMenuAction.userData as Tuple; + uData.Item1.GetScriptFile(uData.Item2, out var lineNum).ToIDE(lineNum); + } + + // ------------------------------------------------------- + // -- Jump to editor code menu --------------------------- + void CallStringCodeJump(DropdownMenuAction dropdownMenuAction) + { + var uData = dropdownMenuAction.userData as Tuple; + uData.Item1.GetScriptFile(uData.Item2, out var lineNum).ToIDE(lineNum); + } + + // ------------------------------------------------------- + // -- Jump to USS menu item ------------------------------ + void CallUSSJump(DropdownMenuAction dropdownMenuAction) + { + var uData = dropdownMenuAction.userData as Tuple; + uData.Item1.GetStylesheetFile(uData.Item2, out var lineNum).ToIDE(lineNum); + } + + evt.StopPropagation(); + })); + } + + // -- Locate file from provided path, then use the provided string as the search criteria + // -- in which to locate the desired line number and then return said line number + public static int LocateLineNumber(this string filePath, string locator) + { + string line; + var counter = 1; + var locatedLine = 1; + + var file = new System.IO.StreamReader(filePath); + while ((line = file.ReadLine()) != null) + { + if (line.Contains(locator)) locatedLine = counter; + counter++; + } + + file.Close(); + return locatedLine; + } + + /// + /// Opens a supported IDE to the appropriate file and places the caret at the desired line number + /// + /// The script/file in which to open, of Type Object + /// The desired line number to place the caret + /// + public static bool ToIDE(this Object asset, int lineNumber = -1) + { + return AssetDatabase.OpenAsset(asset, lineNumber); + } + } +} +#endif diff --git a/Runtime/Scripts/Extensions/AssetFileExtensions.cs.meta b/Runtime/Scripts/Extensions/AssetFileExtensions.cs.meta new file mode 100644 index 0000000..c520b12 --- /dev/null +++ b/Runtime/Scripts/Extensions/AssetFileExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96ae55756c6b8df038ba1254b119d0e1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/CollectionExtensions.cs b/Runtime/Scripts/Extensions/CollectionExtensions.cs new file mode 100644 index 0000000..8c88060 --- /dev/null +++ b/Runtime/Scripts/Extensions/CollectionExtensions.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Object = UnityEngine.Object; + +namespace instance.id.EATK.Extensions +{ + public static class CollectionExtensions + { + // ------------------------------------------------------------------- Dictionary Functions + // -- Dictionary Functions ---------------------------------------------------------------- + + #region Dictionary + + public static Tvalue TryGet(this Dictionary dict, Tkey key) + { + dict.TryGetValue(key, out var value); + return value; + } + + public static T GetOrAdd(this Dictionary dictionary, TKey key, Func func) + { + if (dictionary.TryGetValue(key, out var result)) + { + return result; + } + + result = func(key); + dictionary.Add(key, result); + return result; + } + + public static bool TryAddValue(this IDictionary dictionary, TKey key, TValue value) + { + if (!dictionary.ContainsKey(key)) + { + dictionary.Add(key, value); + return true; + } + + return false; + } + + public static bool TryAddValue(this Dictionary dictionary, TKey key, TValue value) + { + if (!dictionary.ContainsKey(key)) + { + dictionary.Add(key, value); + return true; + } + + return false; + } + + public static void TryAddRange(this Dictionary dictionary, IEnumerable keys, TValue value) + { + foreach (var k in keys) + { + dictionary.TryAddValue(k, value); + } + } + + #region Removal + + public static bool TryRemove(this Dictionary dictionary, ref TKey key, out Exception any) + { + any = null; + + try + { + //Attempt to remove + return dictionary.Remove(key); + } + catch (Exception ex) + { + //Assign the exception + any = ex; + + //Indicate if a failure occured + return false; + } + } + + public static bool TryRemove(this Dictionary dictionary, ref TKey key, out TValue value, out Exception any) + { + any = null; + + value = default(TValue); + + try + { + //Attempt to remove if contaioned + if (dictionary.TryGetValue(key, out value)) + { + return TryRemove(dictionary, key, out any); + } + + //The item was not contained + return false; + } + catch (Exception ex) + { + //Assign the exception + any = ex; + + //Indicate if a failure occured + return false; + } + } + + public static bool TryRemove(this Dictionary dictionary, TKey key, out Exception any) + { + return TryRemove(dictionary, ref key, out any); + } + + public static bool TryRemove(this Dictionary dictionary, ref TKey key) + { + Exception any; + + return TryRemove(dictionary, ref key, out any); + } + + #endregion + + /// + /// Iterate the keys and return the length of the longest entry + /// + /// The collection to iterate + /// The items in which to find the desired longest entry + /// + /// + /// The int value of the longest length entry + public static int GetKeyWidth(this Dictionary dictionary, IEnumerable keys) + { + var keyList = dictionary.Keys.ToList(); + // -- Using the list of strings, check the length of each and return the value of the longest one - + return keyList + .Select(x => x.ToString()) + .Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur).Length; + } + + #endregion + + // ------------------------------------------------------------------------- List Functions + // -- List Functions ---------------------------------------------------------------------- + + #region List + + public static bool TryAddValue(this List list, TValue value) + { + if (list.Contains(value)) return false; + list.Add(value); + return true; + } + + public static TValue TryGetValue(this List list, string value) where TValue : Object + { + return list.FirstOrDefault(x => x.name == value); + } + + /// + /// Iterate the list values and return the length of the longest entry + /// + /// The collection to iterate + /// + /// The int value of the longest length entry + public static int GetIntWidth(this List list) + { + // -- Using the list of strings, check the length of each and return the value of the longest one - + return list + .Select(x => x.ToString()) + .Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur).Length; + } + + // -- Iteration -------------------------------------------------- + /// + /// Reverse ForEach. Same as the usual one, just.. the other way. + /// + /// + /// + /// + /// + /// + public static IEnumerable ForEachR(this List source, Action action, bool reverse = false) + { + var forEach = source as T[] ?? source.ToArray(); + + if (reverse) + for (var i = forEach.Length - 1; i >= 0; i--) + { + action(forEach[i]); + } + + else + foreach (var item in forEach) + action(item); + + return forEach; + } + + public static void ForEach(this IEnumerable ie, Action action) + { + foreach (var i in ie) + { + action(i); + } + } + + public static void ForEach(this IEnumerable ie, Action action) + { + int i = 0; + foreach (var e in ie) + { + action(e, i); + i++; + } + } + + #endregion + + + } +} diff --git a/Runtime/Scripts/Extensions/CollectionExtensions.cs.meta b/Runtime/Scripts/Extensions/CollectionExtensions.cs.meta new file mode 100644 index 0000000..e72ee60 --- /dev/null +++ b/Runtime/Scripts/Extensions/CollectionExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 234b6433887847034b56fa5d88c4aa5e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/DataTypes/AnimatedItems.cs b/Runtime/Scripts/Extensions/DataTypes/AnimatedItems.cs index 56a32d1..2f7d175 100644 --- a/Runtime/Scripts/Extensions/DataTypes/AnimatedItems.cs +++ b/Runtime/Scripts/Extensions/DataTypes/AnimatedItems.cs @@ -7,7 +7,7 @@ using UnityEngine.UIElements; using UnityEngine.UIElements.Experimental; -namespace instance.id.EATK.Extensions +namespace instance.id.EATK { public class AnimatedItems { diff --git a/Runtime/Scripts/Extensions/DataTypes/VisualElementStyleStore.cs b/Runtime/Scripts/Extensions/DataTypes/VisualElementStyleStore.cs new file mode 100644 index 0000000..a18bc3d --- /dev/null +++ b/Runtime/Scripts/Extensions/DataTypes/VisualElementStyleStore.cs @@ -0,0 +1,442 @@ +// ---------------------------------------------------------------------------- +// -- Project : https://github.com/instance-id/Extensions -- +// -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- +// ---------------------------------------------------------------------------- + +using UnityEngine.UIElements; + +#pragma warning disable 649 + +namespace instance.id.EATK.Extensions +{ + public struct VisualElementStyleStore + { + private string sourceName; + private StyleLength width; + private StyleLength height; + private StyleLength maxWidth; + private StyleLength maxHeight; + private StyleLength minWidth; + private StyleLength minHeight; + private StyleLength flexBasis; + private StyleFloat flexShrink; + private StyleFloat flexGrow; + private StyleInt overflow; + private StyleInt unityOverflowClipBox; + private StyleLength left; + private StyleLength top; + private StyleLength right; + private StyleLength bottom; + private StyleLength marginLeft; + private StyleLength marginTop; + private StyleLength marginRight; + private StyleLength marginBottom; + private StyleLength paddingLeft; + private StyleLength paddingTop; + private StyleLength paddingRight; + private StyleLength paddingBottom; + private StyleInt position; + private StyleInt alignSelf; + private StyleInt unityTextAlign; + private StyleInt unityFontStyleAndWeight; + private StyleFont unityFont; + private StyleLength fontSize; + private StyleInt whiteSpace; + private StyleColor color; + private StyleInt flexDirection; + private StyleColor backgroundColor; + private StyleBackground backgroundImage; + private StyleInt unityBackgroundScaleMode; + private StyleColor unityBackgroundImageTintColor; + private StyleInt alignItems; + private StyleInt alignContent; + private StyleInt justifyContent; + private StyleInt flexWrap; + private StyleColor borderLeftColor; + private StyleColor borderTopColor; + private StyleColor borderRightColor; + private StyleColor borderBottomColor; + private StyleFloat borderLeftWidth; + private StyleFloat borderTopWidth; + private StyleFloat borderRightWidth; + private StyleFloat borderBottomWidth; + private StyleLength borderTopLeftRadius; + private StyleLength borderTopRightRadius; + private StyleLength borderBottomRightRadius; + private StyleLength borderBottomLeftRadius; + private StyleInt unitySliceLeft; + private StyleInt unitySliceTop; + private StyleInt unitySliceRight; + private StyleInt unitySliceBottom; + private StyleFloat opacity; + private StyleCursor cursor; + private StyleInt visibility; + private StyleInt display; + + public string SourceName + { + get => sourceName; + set => sourceName = value; + } + + public StyleLength Width + { + get => width; + set => width = value; + } + + public StyleLength Height + { + get => height; + set => height = value; + } + + public StyleLength MaxWidth + { + get => maxWidth; + set => maxWidth = value; + } + + public StyleLength MaxHeight + { + get => maxHeight; + set => maxHeight = value; + } + + public StyleLength MinWidth + { + get => minWidth; + set => minWidth = value; + } + + public StyleLength MinHeight + { + get => minHeight; + set => minHeight = value; + } + + public StyleLength FlexBasis + { + get => flexBasis; + set => flexBasis = value; + } + + public StyleFloat FlexShrink + { + get => flexShrink; + set => flexShrink = value; + } + + public StyleFloat FlexGrow + { + get => flexGrow; + set => flexGrow = value; + } + + public StyleInt Overflow + { + get => overflow; + set => overflow = value; + } + + public StyleInt UnityOverflowClipBox + { + get => unityOverflowClipBox; + set => unityOverflowClipBox = value; + } + + public StyleLength Left + { + get => left; + set => left = value; + } + + public StyleLength Top + { + get => top; + set => top = value; + } + + public StyleLength Right + { + get => right; + set => right = value; + } + + public StyleLength Bottom + { + get => bottom; + set => bottom = value; + } + + public StyleLength MarginLeft + { + get => marginLeft; + set => marginLeft = value; + } + + public StyleLength MarginTop + { + get => marginTop; + set => marginTop = value; + } + + public StyleLength MarginRight + { + get => marginRight; + set => marginRight = value; + } + + public StyleLength MarginBottom + { + get => marginBottom; + set => marginBottom = value; + } + + public StyleLength PaddingLeft + { + get => paddingLeft; + set => paddingLeft = value; + } + + public StyleLength PaddingTop + { + get => paddingTop; + set => paddingTop = value; + } + + public StyleLength PaddingRight + { + get => paddingRight; + set => paddingRight = value; + } + + public StyleLength PaddingBottom + { + get => paddingBottom; + set => paddingBottom = value; + } + + public StyleInt Position + { + get => position; + set => position = value; + } + + public StyleInt AlignSelf + { + get => alignSelf; + set => alignSelf = value; + } + + public StyleInt UnityTextAlign + { + get => unityTextAlign; + set => unityTextAlign = value; + } + + public StyleInt UnityFontStyleAndWeight + { + get => unityFontStyleAndWeight; + set => unityFontStyleAndWeight = value; + } + + public StyleFont UnityFont + { + get => unityFont; + set => unityFont = value; + } + + public StyleLength FontSize + { + get => fontSize; + set => fontSize = value; + } + + public StyleInt WhiteSpace + { + get => whiteSpace; + set => whiteSpace = value; + } + + public StyleColor Color + { + get => color; + set => color = value; + } + + public StyleInt FlexDirection + { + get => flexDirection; + set => flexDirection = value; + } + + public StyleColor BackgroundColor + { + get => backgroundColor; + set => backgroundColor = value; + } + + public StyleBackground BackgroundImage + { + get => backgroundImage; + set => backgroundImage = value; + } + + public StyleInt UnityBackgroundScaleMode + { + get => unityBackgroundScaleMode; + set => unityBackgroundScaleMode = value; + } + + public StyleColor UnityBackgroundImageTintColor + { + get => unityBackgroundImageTintColor; + set => unityBackgroundImageTintColor = value; + } + + public StyleInt AlignItems + { + get => alignItems; + set => alignItems = value; + } + + public StyleInt AlignContent + { + get => alignContent; + set => alignContent = value; + } + + public StyleInt JustifyContent + { + get => justifyContent; + set => justifyContent = value; + } + + public StyleInt FlexWrap + { + get => flexWrap; + set => flexWrap = value; + } + + public StyleColor BorderLeftColor + { + get => borderLeftColor; + set => borderLeftColor = value; + } + + public StyleColor BorderTopColor + { + get => borderTopColor; + set => borderTopColor = value; + } + + public StyleColor BorderRightColor + { + get => borderRightColor; + set => borderRightColor = value; + } + + public StyleColor BorderBottomColor + { + get => borderBottomColor; + set => borderBottomColor = value; + } + + public StyleFloat BorderLeftWidth + { + get => borderLeftWidth; + set => borderLeftWidth = value; + } + + public StyleFloat BorderTopWidth + { + get => borderTopWidth; + set => borderTopWidth = value; + } + + public StyleFloat BorderRightWidth + { + get => borderRightWidth; + set => borderRightWidth = value; + } + + public StyleFloat BorderBottomWidth + { + get => borderBottomWidth; + set => borderBottomWidth = value; + } + + public StyleLength BorderTopLeftRadius + { + get => borderTopLeftRadius; + set => borderTopLeftRadius = value; + } + + public StyleLength BorderTopRightRadius + { + get => borderTopRightRadius; + set => borderTopRightRadius = value; + } + + public StyleLength BorderBottomRightRadius + { + get => borderBottomRightRadius; + set => borderBottomRightRadius = value; + } + + public StyleLength BorderBottomLeftRadius + { + get => borderBottomLeftRadius; + set => borderBottomLeftRadius = value; + } + + public StyleInt UnitySliceLeft + { + get => unitySliceLeft; + set => unitySliceLeft = value; + } + + public StyleInt UnitySliceTop + { + get => unitySliceTop; + set => unitySliceTop = value; + } + + public StyleInt UnitySliceRight + { + get => unitySliceRight; + set => unitySliceRight = value; + } + + public StyleInt UnitySliceBottom + { + get => unitySliceBottom; + set => unitySliceBottom = value; + } + + public StyleFloat Opacity + { + get => opacity; + set => opacity = value; + } + + public StyleCursor Cursor + { + get => cursor; + set => cursor = value; + } + + public StyleInt Visibility + { + get => visibility; + set => visibility = value; + } + + public StyleInt Display + { + get => display; + set => display = value; + } + } +} diff --git a/Runtime/Scripts/Extensions/DataTypes/VisualElementStyleStore.cs.meta b/Runtime/Scripts/Extensions/DataTypes/VisualElementStyleStore.cs.meta new file mode 100644 index 0000000..5335f16 --- /dev/null +++ b/Runtime/Scripts/Extensions/DataTypes/VisualElementStyleStore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b239b43ed0007977e8b49b9dd7290ce6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedFoldout.meta b/Runtime/Scripts/Extensions/Elements/AnimatedFoldout.meta deleted file mode 100644 index 69e90b0..0000000 --- a/Runtime/Scripts/Extensions/Elements/AnimatedFoldout.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: dcd165d3d08b4a219a8e91b00166b519 -timeCreated: 1604837748 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/Elements/AnimatedLabel.meta b/Runtime/Scripts/Extensions/Elements/AnimatedLabel.meta deleted file mode 100644 index 853e17f..0000000 --- a/Runtime/Scripts/Extensions/Elements/AnimatedLabel.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 3ffb7b752e0c445ca642070cfd31df72 -timeCreated: 1605150689 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/Elements/BetterTextField.meta b/Runtime/Scripts/Extensions/Elements/BetterTextField.meta deleted file mode 100644 index 1024b45..0000000 --- a/Runtime/Scripts/Extensions/Elements/BetterTextField.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 821abcdb090b40ff9721fe3aa592167a -timeCreated: 1605010294 \ No newline at end of file diff --git a/Runtime/Scripts/Extensions/JumpTarget.meta b/Runtime/Scripts/Extensions/JumpTarget.meta new file mode 100644 index 0000000..2e012c2 --- /dev/null +++ b/Runtime/Scripts/Extensions/JumpTarget.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 11633f6ef82c75c25bd06646b6dc1961 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/JumpTarget/JumpTarget.cs b/Runtime/Scripts/Extensions/JumpTarget/JumpTarget.cs new file mode 100644 index 0000000..0cae334 --- /dev/null +++ b/Runtime/Scripts/Extensions/JumpTarget/JumpTarget.cs @@ -0,0 +1,56 @@ +// ---------------------------------------------------------------------------- +// -- Project : https://github.com/instance-id/Extensions -- +// -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- +// ---------------------------------------------------------------------------- + +namespace instance.id.EATK.Extensions +{ + /// + /// Class containing data needed to perform the JumpToCode method from a VisualElement context menu. + /// + /// + public class JumpTarget + { + private string menuTitle; + private string locator; + private bool externalLocator; + private JumpType jumpType; + + /// + /// The title of the context menu for the JumpToCode entry + /// + public string MenuTitle + { + get => menuTitle; + set => menuTitle = value; + } + + /// + /// The line of code in which to jump to is found by locating the "locator" string. This is where in the code in which to jump + /// + public string Locator + { + get => locator; + set => locator = value; + } + + /// + /// Deprecated: Used to mark if the locator is on a different line than the calling method + /// + public bool ExternalLocator + { + get => externalLocator; + set => externalLocator = value; + } + + /// + /// Used to determine the proper AssetDatabase search string to locate the file in which to perform the JumpToCode() method. + /// + public JumpType JumpType + { + get => jumpType; + set => jumpType = value; + } + + } +} diff --git a/Runtime/Scripts/Extensions/JumpTarget/JumpTarget.cs.meta b/Runtime/Scripts/Extensions/JumpTarget/JumpTarget.cs.meta new file mode 100644 index 0000000..769d1e5 --- /dev/null +++ b/Runtime/Scripts/Extensions/JumpTarget/JumpTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6123da96616cc7bf9a7732fa37d01473 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/JumpTarget/JumpType.cs b/Runtime/Scripts/Extensions/JumpTarget/JumpType.cs new file mode 100644 index 0000000..3ee7baf --- /dev/null +++ b/Runtime/Scripts/Extensions/JumpTarget/JumpType.cs @@ -0,0 +1,18 @@ +// ---------------------------------------------------------------------------- +// -- Project : https://github.com/instance-id/Extensions -- +// -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- +// ---------------------------------------------------------------------------- + +namespace instance.id.EATK.Extensions +{ + /// + /// Used to determine the proper AssetDatabase search string to locate the file in which to perform the JumpToCode() method. + /// + /// + public enum JumpType + { + Element, + Animation, + USS + } +} diff --git a/Runtime/Scripts/Extensions/JumpTarget/JumpType.cs.meta b/Runtime/Scripts/Extensions/JumpTarget/JumpType.cs.meta new file mode 100644 index 0000000..64ad31f --- /dev/null +++ b/Runtime/Scripts/Extensions/JumpTarget/JumpType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f04bc7730888d2a239a210e95b68411a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/ParseElements.cs b/Runtime/Scripts/Extensions/ParseElements.cs new file mode 100644 index 0000000..e347e64 --- /dev/null +++ b/Runtime/Scripts/Extensions/ParseElements.cs @@ -0,0 +1,334 @@ + using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Xml; +using JetBrains.Annotations; +using UnityEditor; +using UnityEngine; +using UnityEngine.UIElements; +using VisualElement = UnityEngine.UIElements.VisualElement; + +#if UNITY_EDITOR + +namespace instance.id.EATK.Extensions +{ + // ReSharper disable once InconsistentNaming + public static class UIParser + { + /// + /// + [UsedImplicitly] + public static VisualElement CreateVisualElement(XmlNode node) + { + if (node == null) + throw new Exception("Node is null"); + + // Debug.Log($"Looking for type: {node.Name.Replace("ui:", "")}"); + Type elementType = Array.Find(typeof(VisualElement).Assembly.GetTypes(), x => + x.Name.Equals(node.Name.Replace("ui:", ""))); + if (elementType == null) + { + if (!node.Name.Replace("ui:", "").Equals("Style")) + { + Debug.Log($"Couldn't find type \"{node.Name.Replace("ui:", "")}\"\nSkipping..."); + } + + return null; + } + + VisualElement element = (VisualElement)typeof(VisualElement).GetMethod("CreateUnityType") + ?.MakeGenericMethod(elementType) + .Invoke(null, new object[] { new object[] { } }); + // Debug.Log("Creating element.."); + + if (node.Attributes != null) + foreach (XmlAttribute attr in node.Attributes) + { + // Debug.Log("Parsing Attribute"); + + var property = elementType.GetProperty(MapCssName(attr.Name)); + + if (attr.Name.Equals("class")) + { + //Debug.Log("Class found with value: " + attr.Value); + element?.AddToClassList(attr.Value); + } + + if (property == null) + { + if (!attr.Name.Equals("class")) + { + Debug.Log($"Skipping attribute \"{attr.Name}\""); + } + + // throw new Exception($"No property found with name \"{attr.Name}\""); + continue; + } + + if (property.PropertyType.IsEnum) + { + property.SetValue(element, Enum.Parse(property.PropertyType, attr.Value)); + continue; + } + + switch (property.PropertyType.Name) + { + case "Boolean": + // Debug.Log($"Parsing Boolean: {attr.Value}"); + property.SetValue(element, bool.Parse(attr.Value)); + break; + case "String": + // Debug.Log($"Parsing String: {attr.Value}"); + property.SetValue(element, attr.Value); + break; + case "IStyle": + // Debug.Log("Parsing IStyle"); + element = ParseStyle(attr.Value, element); + break; + default: + throw new Exception($"Found no matching type to {property.PropertyType.FullName}"); + } + } + + + VisualElement resultElement = element; + + foreach (XmlNode child in node.ChildNodes) + { + var parsedChild = CreateVisualElement(child); + } + + return resultElement; + } + + /// + /// + /// + /// WARNING: Make sure this type is or inherits + public static VisualElement ParseStyle(string data, VisualElement element) + { + var list = data.Replace("'", "\"").Split(';').ToList(); + foreach (string entry in list) + { + if (entry != " ") + { + element = ParseEntry(entry, element); + } + } + + return element; + } + + public static string MapCssName(string cssTag) => + (cssTag[0] == '-' ? char.ToLower(cssTag[1]) : char.ToLower(cssTag[0])) + cssTag.Split('-') + .Select(s => s != "" ? char.ToUpper(s[0]) + s.Substring(1) : "") + .Aggregate("", (s, s1) => s + s1).Substring(1); + + public static PropertyInfo MapProperty(string propertyStr) + { + string propertyName = MapCssName(propertyStr); + if (propertyName == "unityFontStyle") propertyName = "unityFontStyleAndWeight"; + if (propertyName == "textAlign") propertyName = "unityTextAlign"; + return typeof(IStyle).GetProperty(propertyName); + } + + public static object ParseProperty(PropertyInfo property, string value) + { + if (property.PropertyType.GenericTypeArguments.Length > 0) + { + var result = typeof(UIParser) + .GetMethod("ToStyleEnum", + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) + ?.MakeGenericMethod(property.PropertyType.GenericTypeArguments[0]) + .Invoke(null, new object[] { value }); + + return result; + } + + switch (property.PropertyType.Name) + { + case "StyleFloat": + return ToStyleFloat(value); + case "StyleInt": + return ToStyleInt(value); + case "StyleLength": + return ToStyleLength(value); + case "StyleFont": + return ToStyleFont(value); + case "StyleCursor": + return ToStyleCursor(value); + case "StyleColor": + return ToStyleColor(value); + case "StyleBackground": + return ToStyleBackground(value); + default: + Debug.Log("Unhandled type in USS parser"); + break; + } + + return null; + } + + public static VisualElement ParseEntry(string entry, VisualElement element) + { + if (element?.name is null) + { + Debug.Log($"Failed to parse entry, element was null"); + return null; + } + + var entrySplit = entry.Split(':'); + entrySplit[0] = entrySplit[0].Replace(" ", ""); + if (entrySplit[0] == "") return element; + + var property = MapProperty(entrySplit[0]); + if (property == null) + { + Debug.Log($"Failed to find property \"{MapCssName(entrySplit[0])}\""); + // Debug.Log($"Type of style: \"{typeof(element.style).FullName}\""); + } + + try + { + if (property != null) + { + var value = ParseProperty(property, entrySplit[1]); + if (value == null) + { + Debug.Log($"Failed to parse entry {property.Name}\n\"{entry}\""); + } + else + { + property.SetValue(element.style, value); + } + } + } + catch (Exception) + { + Debug.Log($"Failed to set property. Skipping {property?.Name}\n\"{entry}\""); + } + + return element; + } + + public static StyleFloat ToStyleFloat(string str) => new StyleFloat(float.Parse(str.Replace("px", ""))); + + public static StyleInt ToStyleInt(string str) => new StyleInt(int.Parse(str.Replace("px", ""))); + + public static StyleInt ToStyleInt(this T str) where T : struct, IConvertible + { + StyleEnum newOne = str; + return new StyleInt(newOne.value.ToInt32(CultureInfo.CurrentCulture)); + } + + public static StyleLength ToStyleLength(string str) + { + str = str.Replace(" ", ""); + if (str.Contains("auto")) + return new StyleLength(StyleKeyword.Auto); + + bool isPercent = str.Contains("%"); + LengthUnit unit; + if (isPercent) + unit = LengthUnit.Percent; + else + unit = LengthUnit.Pixel; + + // Debug.Log($"StyleInt from: \"{str}\""); + // Debug.Log($"Units: \"{unit}\""); + + return new StyleLength(new Length(float.Parse(str.Replace("%", "").Replace("px", "")), unit)); + } + + public static StyleFont ToStyleFont(string _) => new StyleFont(StyleKeyword.Null); + + public static StyleBackground ToStyleBackground(string str) + { + string path = str.Replace(" ", ""); + + if (path.StartsWith("url(\"") || path.StartsWith("url('")) + path = path.Remove(0, 5); + if (path.EndsWith("\")") || path.EndsWith("')")) + path = path.Remove(path.Length - 2, 2); + + try + { + Sprite asset = AssetDatabase.LoadAssetAtPath(path); + if (asset == null) + { + Debug.Log($"Can't find USS background image asset: {path}"); + return new StyleBackground(StyleKeyword.Null); + } + else + { + return new StyleBackground(asset.texture); + } + } + catch (Exception e) + { + // FAIL TO GET TEXTURE + Debug.Log($"Exception when parsing background texture\n{e}"); + return new StyleBackground(StyleKeyword.Null); + } + } + + public static StyleCursor ToStyleCursor(string _) => new StyleCursor(StyleKeyword.Null); + + public static StyleColor ToStyleColor(string str) + { + var color = new StyleColor(); + + var strTmp = str; + if (strTmp.StartsWith("#")) + return color.value = str.FromHex(); + + if (str[0] == ' ') + str = str.Substring(1); + + var numbers = new List(); + string start = str.Substring(str.IndexOf('(') + 1); + while (true) + { + if (start.IndexOf(',') >= 0) + { + numbers.Add(start.Substring(0, start.IndexOf(','))); + start = start.Substring(start.IndexOf(',') + 2); + } + else + { + numbers.Add(start.Substring(0, start.IndexOf(')'))); + break; + } + } + + switch (str.Substring(0, str.IndexOf('('))) + { + case "rgb": + color.value = new Color( + float.Parse(numbers[0]) / 255.0f, + float.Parse(numbers[1]) / 255.0f, + float.Parse(numbers[2]) / 255.0f); + break; + case "rgba": + color.value = new Color( + float.Parse(numbers[0]) / 255.0f, + float.Parse(numbers[1]) / 255.0f, + float.Parse(numbers[2]) / 255.0f, + float.Parse(numbers[3])); + break; + case "#": + color.value = str.FromHex(); + break; + } + + return color; + } + + public static StyleEnum ToStyleEnum(string str) where T : struct, IConvertible => new StyleEnum + { value = (T)Enum.Parse(typeof(T), MapCssName(str.Replace(" ", "")), true) }; + } +} + +#endif diff --git a/Runtime/Scripts/Extensions/ParseElements.cs.meta b/Runtime/Scripts/Extensions/ParseElements.cs.meta new file mode 100644 index 0000000..fa11990 --- /dev/null +++ b/Runtime/Scripts/Extensions/ParseElements.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5468da1d51365fe1ebcb10d099498376 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/Extensions/VisualElementExtension.cs b/Runtime/Scripts/Extensions/VisualElementExtension.cs new file mode 100644 index 0000000..3f0e599 --- /dev/null +++ b/Runtime/Scripts/Extensions/VisualElementExtension.cs @@ -0,0 +1,939 @@ +// ---------------------------------------------------------------------------- +// -- Project : https://github.com/instance-id/Extensions -- +// -- instance.id 2020 | http://github.com/instance-id | http://instance.id -- +// ---------------------------------------------------------------------------- +#if UNITY_EDITOR +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.UIElements; + + +using UnityEditor; +using UnityEditor.UIElements; + + +namespace instance.id.EATK.Extensions +{ + public static class VisualElementExtension + { +#pragma warning disable 67 + public static event Action onChangeProperty; +#pragma warning restore 67 + + // --|---------------------------------- Style variables + private static StyleEnum directionRow = new StyleEnum(FlexDirection.Row); + private static StyleEnum directionCol = new StyleEnum(FlexDirection.Column); + + #region General VisualElement + + public enum ContainerType + { + Row, + Column + } + + // @formatter:off ------------------------------------------------- Hierarchy Modifications + // ---------------------------------------------------------------------------------------- + + #region Hierarchical Modifications +#if UNITY_EDITOR + // --|---------------------------------- Custom elements + public static VisualElement CreateEnumField(this T enumField, Action onChange = null, string label = null) // @formatter:on + { + var e = new EnumField(label, Convert(enumField)); + if (onChange != null) e.RegisterValueChangedCallback(change => { onChange(Convert(change.newValue)); }); + return e; + } +#endif + public static TextField CreateTextField(this TextField textField, EventCallback> evt = null, string label = null) + { + textField = new TextField { label = label }; + if (evt != null) textField.RegisterCallback(evt); + return textField; + } + + // --|--------------------------------------- Containers + // --|-------------------------------------------------- + /// + /// Creates a row styled VisualElement and return it as an out variable which can be chained to .ToUSS() + /// new VisualElement().CreateRow(out var myElement); + /// + /// The target element to perform this action upon + /// Returns the element as an out variable to allow the user of the nameof() function in chained methods + /// If a name is specifically passed as a parameter, it will be used, otherwise the target variable name is used + /// VisualElement + public static T CreateRow(this T element, out T variable, string name = null) where T : VisualElement + { + if (name != null) element.name = name; + element.style.flexDirection = directionRow; + return variable = element; + } + + /// + /// Creates a column styled VisualElement and return it as an out variable which can be chained to .ToUSS() + /// new VisualElement().CreateColumn(out var myElement); + /// + /// The target element to perform this action upon + /// Returns the element as an out variable to allow the user of the nameof() function in chained methods + /// If a name is specifically passed as a parameter, it will be used, otherwise the target variable name is used + /// VisualElement + public static T CreateColumn(this T element, out T variable, string name = null) where T : VisualElement + { + if (name != null) element.name = name; + element.style.flexDirection = directionCol; + return variable = element; + } + + /// + /// Creates the VisualElement and return it as an out variable which can be chained to .ToUSS() + /// new VisualElement().Create(out var myElement); + /// + /// The target element to perform this action upon + /// Returns the element as an out variable to allow the user of the nameof() function in chained methods + /// If a name is specifically passed as a parameter, it will be used, otherwise the target variable name is used + /// VisualElement + public static T Create(this T element, out T variable, string name = null) where T : VisualElement + { + if (name != null) element.name = name; + return variable = element; + } + + public static T Create(this T element, string name = null) where T : VisualElement + { + if (name != null) element.name = name; + return element; + } + + /// + /// Creates the VisualElement and return it as an out variable which can be chained to .ToUSS() + /// new VisualElement().Create(out var myElement); + /// + /// The target element to perform this action upon + /// Returns the element as an out variable to allow the user of the nameof() function in chained methods + /// If a name is specifically passed as a parameter, it will be used, otherwise the target variable name is used + /// Whether this element should be a row or column + /// VisualElement + public static VisualElement CreateWithLabel(this T element, out VisualElement variable, string name = null, ContainerType containerType = ContainerType.Row, string labelText = default) where T : VisualElement + { + StyleEnum direction = containerType == ContainerType.Row + ? new StyleEnum(FlexDirection.Row) + : new StyleEnum(FlexDirection.Column); + + if (name != null) element.name = name; + + new VisualElement { style = { flexDirection = direction } }.Create(out var elementContainer).ToUSS($"{element.name}Container", (containerType == ContainerType.Row ? "containerRow" : "containerColumn"), labelText); + new Label { text = labelText }.Create().ToUSS($"{element.name}Label").SetParent(elementContainer); + + element.SetParent(elementContainer); + return variable = elementContainer; + } + + /// + /// Is elementName is passed, sets the target elements name and USS class to elementName. + /// If no parameter is passed, the element USS class is set to the targets current name. + /// If neither a parameter is passed, and the target element has no name, the type is used as both name and USS class. + /// (Make sure to either name the initial element, or pass a name) + /// + /// new VisualElement().Create(out var myElement).ToUSS(nameof(myElement)); + /// + /// The target element to perform this action upon + /// The name to be assigned to this element. + /// If multiple strings are passed and the element is not yet named, the first string parameter will be used as the the element name + /// VisualElement + public static T ToUSS(this T element, params string[] elementClassNames) where T : VisualElement + { + if (elementClassNames != null && element.name != null) + { + element.name = elementClassNames[0]; + for (var i = 0; i < elementClassNames.Length; i++) + element.AddToClassList(elementClassNames[i]); + } + else if (element.name != null) element.AddToClassList(element.name); + else element.name = $"{element.parent.name}sChild"; + + return element; + } + + /// + /// Sets the target elements variable name as it's Element name and USS class + /// + /// The target element to perform this action upon + /// If a name is specifically passed as a parameter, it will be used, otherwise the target variable name is used + /// VisualElement + public static void NameAsUSS(this T element, string name = null) where T : VisualElement + { + if (!string.IsNullOrEmpty(name)) + element.name = name; + element.AddToClassList(element.name); + } + + + public static T RegisterValueCallback(this T element, EventCallback changeEvent) where T : VisualElement where E : EventBase, new() + { + ((VisualElement)element).RegisterCallback(changeEvent); + return element; + } + + /// + /// Convert an object to another type + /// + /// The object in which to convert + /// VisualElement + static T Convert(object value) + { + return (T)System.Convert.ChangeType(value, typeof(T)); + } + + /// + /// Add multiple child elements to a parent VisualElement + /// + /// The target element to perform this action upon + /// The elements to add to this VisualElement as child elements + /// VisualElement + public static T AddAll(this T element, params VisualElement[] elements) where T : VisualElement + { + for (var i = 0; i < elements.Length; i++) element.Add(elements[i]); + return element; + } + + /// + /// Add multiple child elements to a parent VisualElement + /// + /// The target element to perform this action upon + /// The elements to add to this VisualElement as child elements + /// VisualElement + public static T SetParent(this T element, VisualElement[] elements) where T : VisualElement + { + for (var i = 0; i < elements.Length; i++) element.Add(elements[i]); + return element; + } + + /// + /// Add multiple child elements to a parent VisualElement + /// + /// The target element to perform this action upon + /// The elements to add to this VisualElement as child elements + /// If index parameter is included, this element will be added at that index to the parent + /// Must be of Type VisualElement + /// Must also be of Type VisualElement + public static V SetParent(this T element, V parent, int index = -1) where V : VisualElement + { + if (index != -1) parent.Insert(index, element as VisualElement); + else parent.Add(element as VisualElement); + + return parent; + } + + #endregion + + #endregion + + public static VisualElement GetFirstAncestorWithClass(this VisualElement element, string className) + { + if (element == null) + return null; + + if (element.ClassListContains(className)) + return element; + + return element.parent.GetFirstAncestorWithClass(className); + } + + // --------------------------------------- Locating parent objects + // --------------------------------------------------------------- + + public static VisualElement GetFirstAncestorOfType(VisualElement element) + { + throw new NotImplementedException(); + } + + + /// + /// Traverses up the hierarchy to find all of the parent instances of type T. + /// + /// Current element to search parents. + /// Type which you want to find + /// Collection of T instances found. + public static IEnumerable GetParentsOfType(this T element, T type = null) where T : VisualElement + { + Debug.Log($"Type {typeof(T).Name}"); + + var result = new List(); + + var parent = element; + while (parent != null) + { + if (parent is T selected) + result.Add(selected); + + parent = (T)parent.parent; + } + + return result; + } + + /// + /// Gets the sibling index. + /// Use this to return the sibling index of the VisualElement. + /// If a VisualElement shares a parent with other VisualElement and are on the same level (i.e. they share the same direct parent), + /// these VisualElements are known as siblings. The sibling index shows where each VisualElement sits in this sibling hierarchy. + /// Similar to + /// + /// + /// + public static int GetSiblingIndex(this VisualElement element) + { + return element.parent?.IndexOf(element) ?? 0; + } + + /// + /// Traverses up the hierarchy to find first parent instance of type T. + /// + /// Current element to search parent. + /// Type which you want to find + /// T instance found + public static T GetFirstParentOfType(this VisualElement element) where T : VisualElement + { + return GetParentsOfType((T)element).FirstOrDefault(); + } + + public static T GetFirstAncestorOfType(this VisualElement element, Type elementType) where T : VisualElement + { + for (VisualElement parent = element.hierarchy.parent; parent != null; parent = parent.hierarchy.parent) + { + if (parent.GetType() == elementType) + return parent as T; + } + + return default(T); + } + + public static T GetFirstAncestorOfType(this Type elementType, VisualElement element) where T : VisualElement + { + for (VisualElement parent = element.hierarchy.parent; parent != null; parent = parent.hierarchy.parent) + { + if (parent.GetType() == elementType) + return parent as T; + } + + return default(T); + } + + public static T GetFirstAncestorOfType(this Type elementType, VisualElement element, out VisualElement outElement) where T : VisualElement + { + VisualElement outVe = new VisualElement(); + if (elementType == null || element == null) + { + var elementTypeBool = elementType == null; + var elementBool = element == null; + Debug.LogWarning($"Element passed was null: elementType {elementTypeBool} : element {elementBool}"); + outElement = outVe; + return default(T); + } + + for (VisualElement parent = element.hierarchy.parent; parent != null; parent = parent.hierarchy.parent) + { + if (parent.GetType() == elementType) + outVe = parent as T; + } + + outElement = outVe; + return default(T); + } + + public static List GetChildElementsOfType(this Type elementType, VisualElement element, out List outElement) where T : List + { + List outVe = new List(); + if (elementType == null || element == null) + { + var elementTypeBool = elementType == null; + var elementBool = element == null; + Debug.LogWarning($"Element passed was null: elementType {elementTypeBool} : element {elementBool}"); + outElement = outVe; + return default(List); + } + + var elementItem = element.Query(null, "unity-inspector-editors-list").First(); + outVe = elementItem.Query() + .Children() + .Where(x => x.GetType() == elementType) + .ToList(); + + outElement = outVe; + return default(List); + } + + + // @formatter:off ------------------------------------------------------- Actions / Helpers + // ---------------------------------------------------------------------------------------- + + #region Actions / Helpers + + // @formatter:on + + /// + /// Registers a field for any possible change event type + /// + // EventCallback> callback, TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) + public static void RegisterAnyChangeEvent(this VisualElement field, Action callback) + { + field.RegisterCallback>(e => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + field.RegisterCallback((ChangeEvent e) => callback()); + } + + /// + /// Opens a web address in an external browser + /// + /// The target element to become the clickable link + /// The web address in which to open in external browser + /// VisualElement + public static T OpenURL(this T element, string url) where T : VisualElement + { + element.RegisterCallback(evt => + { + if (evt.button == 0) + { + Application.OpenURL(url); + evt.StopPropagation(); + } + }); + + return element; + } + + /// + /// Automatically set the value of a Toggle after N milliseconds of the cursor leaving the bounds of (this) target object + /// + /// The target element in which the bounds are used to activate the toggle countdown + /// The target toggle in which to set its value within N milliseconds of the mouse leaving this elements bounds + /// The value in which to set the Toggle after toggleTimer completes + /// The amount of time in which to wait before the toggles value is changed. + /// Default: 1000ms + /// Whether the automatic toggle should be interrupted if the cursor is placed back into the bounds of the target element + /// VisualElement + public static T AutoToggleAfter(this T element, Toggle toggleTarget, long toggleTimer = 1000, bool interruptible = false, bool autoToggleValue = false) + where T : VisualElement + { + bool interrupter = false; + IVisualElementScheduledItem menuCloser = element.schedule.Execute(() => + { + if (interrupter == false && toggleTarget.value) toggleTarget.value = autoToggleValue; + }); + + element.RegisterCallback(evt => + { + if (!interruptible) return; + + interrupter = true; + menuCloser?.Pause(); + evt.StopPropagation(); + }); + element.RegisterCallback(evt => + { + interrupter = false; + + if (toggleTarget.value) + menuCloser.ExecuteLater(toggleTimer); + evt.StopPropagation(); + }); + + return element; + } + + #endregion + + #region Text Related + + public static void SelectRangeDelayed(this TextField textField, int cursorIndex, int selectionIndex) + { + textField.schedule.Execute(() => + { + // textField.Q("unity-text-input").Focus(); + textField.SelectRange(cursorIndex, selectionIndex); + }); + } + + /// + /// Creates a privacy string in which characters at either the beginning or end are shown as asterisks ( * ) + /// Ex. 0123456 -> **2345* + /// + /// The string in which to apply the privacy mask + /// The number of characters are the beginning of the string to mask + /// The number of characters are the end of the string to mask. Defaults to 4 suffix characters. + /// Ex. 0123456789 -> 012345**** + /// Returns a Tuple value in which Item1 is the original string, Item2 is the privacy masked string + public static (string, string) ApplyPrivacyMask(this string exposedString, int prefixNum = 0, int suffixNum = 4) + { + if (exposedString.Length <= 0) return ("", ""); + var tmpString = new List(); + for (var i = 0; i < exposedString.Length; i++) + { + tmpString.Add((i < prefixNum || i > suffixNum) ? exposedString[i].ToString() : "*"); + } + + return (exposedString, tmpString.Aggregate((i, j) => i + j)); + } + + #endregion + + + #region Style Related + + // ---------------------------------------------------------------------------------------- Style Changes + + #region Style Changes + + // ------------------------------------------------ Value adjustments + /// + /// Sets a float value to 0.0001 instead of true 0 due to issues with opacity bugging out. + /// + /// The target number in which to adjust value + public static float Zero(this int num) + { + var tmpNum = (float)num; + tmpNum = 0.0001f; + return tmpNum; + } + + /// + /// Sets a float value to 0.0001 instead of true 0 due to issues with opacity bugging out. + /// + /// The target number in which to adjust value + public static float Zero(this float num) + { + num = 0.0001f; + return num; + } + + // ------------------------------------------------ Set Values + /// + /// Set primary the color of the element + /// + /// The target element to apply color + /// The color to apply to the primary element + /// VisualElement + public static bool SetColor(this T element, Color color = default) where T : VisualElement + { + if (element.style.color != color) element.style.color = color; + return true; + } + + /// + /// Set background the color of the element + /// + /// The target element to apply background color + /// The color to apply to the border + /// VisualElement + public static bool SetBackgroundColor(this T element, Color color = default) where T : VisualElement + { + if (element.style.backgroundColor != color) element.style.backgroundColor = color; + return true; + } + + /// + /// Adds a border to all sides of the VisualElement + /// + /// The target element to add a border + /// The value in which to set the border thickness + /// VisualElement + public static void SetBorderWidth(this T element, float borderThickness = 0) where T : VisualElement + { + element.style.borderBottomWidth = borderThickness; + element.style.borderLeftWidth = borderThickness; + element.style.borderRightWidth = borderThickness; + element.style.borderTopWidth = borderThickness; + } + + /// + /// Sets the margin to all sides of the VisualElement + /// + /// The target element to add a border + /// The value in which to set the border thickness + /// VisualElement + public static void SetMargin(this T element, int margin = 0) where T : VisualElement + { + element.style.marginBottom = margin; + element.style.marginLeft = margin; + element.style.marginRight = margin; + element.style.marginTop = margin; + } + + /// + /// Adds a border to all sides of the VisualElement + /// + /// The target element to add a border + /// The value in which to set the border thickness + /// VisualElement + public static void SetPadding(this T element, int padding = 0) where T : VisualElement + { + element.style.paddingBottom = padding; + element.style.paddingLeft = padding; + element.style.paddingRight = padding; + element.style.paddingTop = padding; + } + + /// + /// Adds a border to all sides of the VisualElement + /// + /// The target element to add a border + /// The color to apply to the border + /// VisualElement + public static bool SetBorderColor(this T element, Color color = default) where T : VisualElement + { + if (element.style.borderBottomColor != color) element.style.borderBottomColor = color; + if (element.style.borderLeftColor != color) element.style.borderLeftColor = color; + if (element.style.borderRightColor != color) element.style.borderRightColor = color; + if (element.style.borderTopColor != color) element.style.borderTopColor = color; + return true; + } + + public static Action SetBorderColorAction(this T element, Color color = default) where T : VisualElement + { + void DoSetBorderColor() + { + element.style.borderBottomColor = color; + element.style.borderLeftColor = color; + element.style.borderRightColor = color; + element.style.borderTopColor = color; + } + + return DoSetBorderColor; + } + + /// + /// Adds a border to all sides of the VisualElement + /// + /// The target element to add a border + /// The value in which to set the border thickness + /// VisualElement + public static void SetOpacity(this T element, float opacity = 0) where T : VisualElement + { + if (opacity == 0) opacity = opacity.Zero(); + element.style.opacity = opacity; + } + + #endregion + + + public static void SetStyleValue(this IStyle style, string propertyName, T value) + { + typeof(IStyle).GetProperty(propertyName)?.SetValue(style, value); + } + + public static T Set(this T v, + string name = null, + string _class = null, + FlexDirection? flexDirection = null, + Justify? justifyContent = null, + Align? alignItems = null, + string background_image = null, + float? flexGrow = null, + float? maxHeight = null, + float? maxWidth = null, + float? height = null, + float? width = null, + Color? color = null, + ScaleMode? unityBackgroundScaleMode = null, + DisplayStyle? display = null) where T : VisualElement + { + if (name != null) + v.name = name; + if (_class != null) + v.AddToClassList(_class); + if (flexDirection.HasValue) + v.style.flexDirection = new StyleEnum(flexDirection.Value); + if (alignItems.HasValue) + v.style.alignItems = new StyleEnum(alignItems.Value); + if (flexGrow.HasValue) + v.style.flexGrow = new StyleFloat(flexGrow.Value); +#if UNITY_EDITOR + if (background_image != null) + v.style.backgroundImage = new StyleBackground(AssetDatabase.LoadAssetAtPath(background_image)); +#endif + if (maxHeight.HasValue) + v.style.maxHeight = maxHeight.Value; + if (maxWidth.HasValue) + v.style.maxWidth = maxWidth.Value; + if (height.HasValue) + v.style.height = height.Value; + if (width.HasValue) + v.style.width = width.Value; + if (justifyContent.HasValue) + v.style.justifyContent = new StyleEnum(justifyContent.Value); + if (color.HasValue) + v.style.color = new StyleColor(color.Value); + if (unityBackgroundScaleMode.HasValue) + v.style.unityBackgroundScaleMode = new StyleEnum(unityBackgroundScaleMode.Value); + if (display.HasValue) + v.style.display = display.Value; + return v; + } + + public static T Set(this T v, string text = null) where T : TextElement + { + if (text != null) + v.text = text; + return v; + } + + public static T AssignTo(this T v, out T reference) where T : VisualElement + { + reference = v; + return v; + } + + public static VisualElement AddRange(this VisualElement v, params VisualElement[] elements) + { + foreach (var el in elements) + v.Add(el); + return v; + } + + // ---------------------------------------------------------------------------------------- Reusable Style Data + // -- Create Reusable Style Data --------------------------------- + public static VisualElementStyleStore CreateStyleData(this T source) where T : VisualElement + { + return new VisualElementStyleStore + { + Width = new StyleLength(StyleKeyword.Auto), + Height = new StyleLength(StyleKeyword.Auto), + // maxWidth = source.resolvedStyle.maxWidth.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.resolvedStyle.maxWidth.value, + // maxHeight = source.resolvedStyle.maxHeight.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.resolvedStyle.maxHeight.value, + // minWidth = source.resolvedStyle.minWidth.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.resolvedStyle.minWidth.value, + // minHeight = source.resolvedStyle.minHeight.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.resolvedStyle.minHeight.value, + // flexBasis = source.resolvedStyle.flexBasis.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.resolvedStyle.flexBasis.value, + FlexGrow = source.resolvedStyle.flexGrow, + FlexShrink = source.resolvedStyle.flexShrink, + FlexDirection = source.style.flexDirection.value.ToStyleInt(), + FlexWrap = source.style.flexWrap.value.ToStyleInt(), + // left = source.resolvedStyle.left, + // top = source.resolvedStyle.top, + // right = source.resolvedStyle.right, + // bottom = source.resolvedStyle.bottom, + MarginLeft = source.resolvedStyle.marginLeft, + MarginTop = source.resolvedStyle.marginTop, + MarginRight = source.resolvedStyle.marginRight, + MarginBottom = source.resolvedStyle.marginBottom, + PaddingLeft = source.resolvedStyle.paddingLeft, + PaddingTop = source.resolvedStyle.paddingTop, + PaddingRight = source.resolvedStyle.paddingRight, + PaddingBottom = source.resolvedStyle.paddingBottom, + // position = source.resolvedStyle.position, + AlignSelf = source.resolvedStyle.alignSelf.ToStyleInt(), + UnityTextAlign = source.resolvedStyle.unityTextAlign.ToStyleInt(), + UnityFontStyleAndWeight = source.style.unityFontStyleAndWeight.value.ToStyleInt(), + FontSize = source.resolvedStyle.fontSize, + WhiteSpace = source.style.whiteSpace.value.ToStyleInt(), + Color = source.resolvedStyle.color, + BackgroundColor = source.resolvedStyle.backgroundColor, + UnityFont = source.resolvedStyle.unityFont, + UnityBackgroundScaleMode = source.style.unityBackgroundScaleMode.value.ToStyleInt(), + UnityBackgroundImageTintColor = source.resolvedStyle.unityBackgroundImageTintColor, + AlignItems = source.style.alignItems.value.ToStyleInt(), + AlignContent = source.style.alignContent.value.ToStyleInt(), + JustifyContent = source.style.justifyContent.value.ToStyleInt(), + BorderLeftColor = source.resolvedStyle.borderLeftColor, + BorderRightColor = source.resolvedStyle.borderRightColor, + BorderTopColor = source.resolvedStyle.borderTopColor, + BorderBottomColor = source.resolvedStyle.borderBottomColor, + BorderLeftWidth = source.resolvedStyle.borderLeftWidth, + BorderRightWidth = source.resolvedStyle.borderRightWidth, + BorderTopWidth = source.resolvedStyle.borderTopWidth, + BorderBottomWidth = source.resolvedStyle.borderBottomWidth, + BorderTopLeftRadius = source.resolvedStyle.borderTopLeftRadius, + BorderTopRightRadius = source.resolvedStyle.borderTopRightRadius, + BorderBottomLeftRadius = source.resolvedStyle.borderBottomLeftRadius, + BorderBottomRightRadius = source.resolvedStyle.borderBottomRightRadius, + // unitySliceLeft = source.resolvedStyle.unitySliceLeft, + // unitySliceTop = source.resolvedStyle.unitySliceTop, + // unitySliceRight = source.resolvedStyle.unitySliceRight, + // unitySliceBottom = source.resolvedStyle.unitySliceBottom, + Opacity = source.resolvedStyle.opacity, + Visibility = source.style.visibility.value.ToStyleInt(), + Display = source.style.display.value.ToStyleInt() + }; + } + + // -- Apply Style data to element from StyleStore ---------------- + public static T FromStyleData(this VisualElementStyleStore source, T target) where T : VisualElement + { + var styleValues = new Dictionary + { + { nameof(target.style.width), target.style.width = source.Width }, + { nameof(target.style.height), target.style.height = source.Height }, + { + nameof(target.style.maxWidth), target.style.maxWidth = + (source.MaxWidth.value == 0 || source.MaxWidth == StyleKeyword.Null) ? new StyleLength(StyleKeyword.Auto) : source.MaxWidth.value + }, + { nameof(target.style.maxHeight), target.style.maxHeight = source.MaxHeight.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.MaxHeight.value }, + { nameof(target.style.minWidth), target.style.minWidth = source.MinWidth.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.MinWidth.value }, + { nameof(target.style.minHeight), target.style.minHeight = source.MinHeight.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.MinHeight.value }, + { nameof(target.style.flexBasis), target.style.flexBasis = source.FlexBasis.value == 0 ? new StyleLength(StyleKeyword.Auto) : source.FlexBasis.value }, + { nameof(target.style.flexGrow), target.style.flexGrow = source.FlexGrow }, + { nameof(target.style.flexShrink), target.style.flexShrink = source.FlexShrink }, + { nameof(target.style.flexDirection), target.style.flexDirection = (FlexDirection)source.FlexDirection.value }, + { nameof(target.style.flexWrap), target.style.flexWrap = (Wrap)source.FlexWrap.value }, + { nameof(target.style.marginLeft), target.style.marginLeft = source.MarginLeft }, + { nameof(target.style.marginTop), target.style.marginTop = source.MarginTop }, + { nameof(target.style.marginRight), target.style.marginRight = source.MarginRight }, + { nameof(target.style.marginBottom), target.style.marginBottom = source.MarginBottom }, + { nameof(target.style.paddingLeft), target.style.paddingLeft = source.PaddingLeft }, + { nameof(target.style.paddingTop), target.style.paddingTop = source.PaddingTop }, + { nameof(target.style.paddingRight), target.style.paddingRight = source.PaddingRight }, + { nameof(target.style.paddingBottom), target.style.paddingBottom = source.PaddingBottom }, + { nameof(target.style.alignSelf), target.style.alignSelf = (Align)source.AlignSelf.value }, + { nameof(target.style.unityTextAlign), target.style.unityTextAlign = (TextAnchor)source.UnityTextAlign.value }, + { nameof(target.style.unityFontStyleAndWeight), target.style.unityFontStyleAndWeight = (FontStyle)source.UnityFontStyleAndWeight.value }, + { nameof(target.style.fontSize), target.style.fontSize = source.FontSize }, + { nameof(target.style.whiteSpace), target.style.whiteSpace = (WhiteSpace)source.WhiteSpace.value }, + { nameof(target.style.color), target.style.color = source.Color }, + { nameof(target.style.backgroundColor), target.style.backgroundColor = source.BackgroundColor }, + { nameof(target.style.unityFont), target.style.unityFont = source.UnityFont }, + { nameof(target.style.unityBackgroundScaleMode), target.style.unityBackgroundScaleMode = (ScaleMode)source.UnityBackgroundScaleMode.value }, + { nameof(target.style.unityBackgroundImageTintColor), target.style.unityBackgroundImageTintColor = source.UnityBackgroundImageTintColor }, + { nameof(target.style.alignItems), target.style.alignItems = (Align)source.AlignItems.value }, + { nameof(target.style.alignContent), target.style.alignContent = (Align)source.AlignContent.value }, + { nameof(target.style.justifyContent), target.style.justifyContent = (Justify)source.JustifyContent.value }, + { nameof(target.style.borderLeftColor), target.style.borderLeftColor = source.BorderLeftColor }, + { nameof(target.style.borderRightColor), target.style.borderRightColor = source.BorderRightColor }, + { nameof(target.style.borderTopColor), target.style.borderTopColor = source.BorderTopColor }, + { nameof(target.style.borderBottomColor), target.style.borderBottomColor = source.BorderBottomColor }, + { nameof(target.style.borderLeftWidth), target.style.borderLeftWidth = source.BorderLeftWidth }, + { nameof(target.style.borderRightWidth), target.style.borderRightWidth = source.BorderRightWidth }, + { nameof(target.style.borderTopWidth), target.style.borderTopWidth = source.BorderTopWidth }, + { nameof(target.style.borderBottomWidth), target.style.borderBottomWidth = source.BorderBottomWidth }, + { nameof(target.style.borderTopLeftRadius), target.style.borderTopLeftRadius = source.BorderTopLeftRadius }, + { nameof(target.style.borderTopRightRadius), target.style.borderTopRightRadius = source.BorderTopRightRadius }, + { nameof(target.style.borderBottomLeftRadius), target.style.borderBottomLeftRadius = source.BorderBottomLeftRadius }, + { nameof(target.style.borderBottomRightRadius), target.style.borderBottomRightRadius = source.BorderBottomRightRadius }, + { nameof(target.style.opacity), target.style.opacity = source.Opacity.value }, + { nameof(target.style.visibility), target.style.visibility = (Visibility)source.Visibility.value }, + { nameof(target.style.display), target.style.display = (DisplayStyle)source.Display.value } + }; + //styleValues.Add(nameof(target.style. ),target.style.left = source.left); + //styleValues.Add(nameof(target.style. ),target.style.top = source.top); + //styleValues.Add(nameof(target.style. ),target.style.right = source.right); + //styleValues.Add(nameof(target.style. ),target.style.bottom = source.bottom); + //styleValues.Add(nameof(target.style. ),target.style.position = source.position); + //styleValues.Add(nameof(target.style. ),target.style.unitySliceLeft = source.unitySliceLeft); + //styleValues.Add(nameof(target.style. ),target.style.unitySliceTop = source.unitySliceTop); + //styleValues.Add(nameof(target.style. ),target.style.unitySliceRight = source.unitySliceRight); + //styleValues.Add(nameof(target.style. ),target.style.unitySliceBottom = source.unitySliceBottom); + + return target; + } + + //-------------------------------------------------------------------------------------------- + public static T CopyElement(this T source, T target) where T : VisualElement + { + var styleValues = new List(); + styleValues.Add(target.style.width = source.resolvedStyle.width == 0 + ? new StyleLength(StyleKeyword.Auto) + : source.resolvedStyle.width); + + styleValues.Add(target.style.height = source.resolvedStyle.height == 0 + ? new StyleLength(StyleKeyword.Auto) + : source.resolvedStyle.height); + + styleValues.Add(target.style.maxWidth = source.resolvedStyle.maxWidth.value == 0 + ? new StyleLength(StyleKeyword.Auto) + : source.resolvedStyle.maxWidth.value); + + styleValues.Add(target.style.maxHeight = source.resolvedStyle.maxHeight.value == 0 + ? new StyleLength(StyleKeyword.Auto) + : source.resolvedStyle.maxHeight.value); + + styleValues.Add(target.style.minWidth = source.resolvedStyle.minWidth.value == 0 + ? new StyleLength(StyleKeyword.Auto) + : source.resolvedStyle.minWidth.value); + + styleValues.Add(target.style.minHeight = source.resolvedStyle.minHeight.value == 0 + ? new StyleLength(StyleKeyword.Auto) + : source.resolvedStyle.minHeight.value); + + // styleValues.Add(target.style.flexBasis = source.resolvedStyle.flexBasis.keyword == StyleKeyword.Auto + // ? new StyleLength(StyleKeyword.Auto) + // : source.resolvedStyle.flexBasis.keyword == StyleKeyword.Undefined + // ? new StyleLength(StyleKeyword.Auto) + // : source.resolvedStyle.flexBasis.keyword); + // + // Debug.Log($"target flexBasis {target.style.flexBasis.value}"); + // Debug.Log($"source style flexBasis {source.style.flexBasis.value}"); + // Debug.Log($"source resolvedStyle flexBasis {source.resolvedStyle.flexBasis.value}"); + + styleValues.Add(target.style.flexGrow = source.resolvedStyle.flexGrow); + styleValues.Add(target.style.flexShrink = source.resolvedStyle.flexShrink); + styleValues.Add(target.style.flexDirection = source.resolvedStyle.flexDirection); + styleValues.Add(target.style.flexWrap = source.resolvedStyle.flexWrap); + // target.style.left = source.resolvedStyle.left; + // target.style.top = source.resolvedStyle.top; + // target.style.right = source.resolvedStyle.right; + // target.style.bottom = source.resolvedStyle.bottom; + styleValues.Add(target.style.marginLeft = source.resolvedStyle.marginLeft); + styleValues.Add(target.style.marginTop = source.resolvedStyle.marginTop); + styleValues.Add(target.style.marginRight = source.resolvedStyle.marginRight); + styleValues.Add(target.style.marginBottom = source.resolvedStyle.marginBottom); + styleValues.Add(target.style.paddingLeft = source.resolvedStyle.paddingLeft); + styleValues.Add(target.style.paddingTop = source.resolvedStyle.paddingTop); + styleValues.Add(target.style.paddingRight = source.resolvedStyle.paddingRight); + styleValues.Add(target.style.paddingBottom = source.resolvedStyle.paddingBottom); + // target.style.position = source.resolvedStyle.position; + styleValues.Add(target.style.alignSelf = source.resolvedStyle.alignSelf); + styleValues.Add(target.style.unityTextAlign = source.resolvedStyle.unityTextAlign); + styleValues.Add(target.style.unityFontStyleAndWeight = source.resolvedStyle.unityFontStyleAndWeight); + styleValues.Add(target.style.fontSize = source.resolvedStyle.fontSize); + styleValues.Add(target.style.whiteSpace = source.resolvedStyle.whiteSpace); + styleValues.Add(target.style.color = source.resolvedStyle.color); + styleValues.Add(target.style.backgroundColor = source.resolvedStyle.backgroundColor); + styleValues.Add(target.style.unityFont = source.resolvedStyle.unityFont); + styleValues.Add(target.style.unityBackgroundScaleMode = source.resolvedStyle.unityBackgroundScaleMode); + styleValues.Add(target.style.unityBackgroundImageTintColor = source.resolvedStyle.unityBackgroundImageTintColor); + styleValues.Add(target.style.alignItems = source.resolvedStyle.alignItems); + styleValues.Add(target.style.alignContent = source.resolvedStyle.alignContent); + styleValues.Add(target.style.justifyContent = source.resolvedStyle.justifyContent); + styleValues.Add(target.style.borderLeftColor = source.resolvedStyle.borderLeftColor); + styleValues.Add(target.style.borderRightColor = source.resolvedStyle.borderRightColor); + styleValues.Add(target.style.borderTopColor = source.resolvedStyle.borderTopColor); + styleValues.Add(target.style.borderBottomColor = source.resolvedStyle.borderBottomColor); + styleValues.Add(target.style.borderLeftWidth = source.resolvedStyle.borderLeftWidth); + styleValues.Add(target.style.borderRightWidth = source.resolvedStyle.borderRightWidth); + styleValues.Add(target.style.borderTopWidth = source.resolvedStyle.borderTopWidth); + styleValues.Add(target.style.borderBottomWidth = source.resolvedStyle.borderBottomWidth); + styleValues.Add(target.style.borderTopLeftRadius = source.resolvedStyle.borderTopLeftRadius); + styleValues.Add(target.style.borderTopRightRadius = source.resolvedStyle.borderTopRightRadius); + styleValues.Add(target.style.borderBottomLeftRadius = source.resolvedStyle.borderBottomLeftRadius); + styleValues.Add(target.style.borderBottomRightRadius = source.resolvedStyle.borderBottomRightRadius); + // styleValues.Add(target.style.unitySliceLeft = source.resolvedStyle.unitySliceLeft); + // styleValues.Add(target.style.unitySliceTop = source.resolvedStyle.unitySliceTop); + // styleValues.Add(target.style.unitySliceRight = source.resolvedStyle.unitySliceRight); + // styleValues.Add(target.style.unitySliceBottom = source.resolvedStyle.unitySliceBottom); + styleValues.Add(target.style.opacity = source.resolvedStyle.opacity); + styleValues.Add(target.style.visibility = source.resolvedStyle.visibility); + styleValues.Add(target.style.display = source.resolvedStyle.display); + + return target; + } + + #endregion + } +} +#endif diff --git a/Runtime/Scripts/Extensions/VisualElementExtension.cs.meta b/Runtime/Scripts/Extensions/VisualElementExtension.cs.meta new file mode 100644 index 0000000..15efc69 --- /dev/null +++ b/Runtime/Scripts/Extensions/VisualElementExtension.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 599aa1ad804924f629532af63a8fd9cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Util.meta b/Runtime/Util.meta new file mode 100644 index 0000000..bb3d9e8 --- /dev/null +++ b/Runtime/Util.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9c8fa3d1554e49eca18ea555364601fd +timeCreated: 1627082692 \ No newline at end of file diff --git a/Runtime/Util/ColorUtil.cs b/Runtime/Util/ColorUtil.cs new file mode 100644 index 0000000..bc40426 --- /dev/null +++ b/Runtime/Util/ColorUtil.cs @@ -0,0 +1,43 @@ +using System; +using System.Globalization; +using UnityEngine; + +namespace instance.id.EATK.Extensions +{ + public static class ColorUtil + { + public static string EnsureHex(this string color) + { + if (color.StartsWith("#")) color = color.Replace("#", ""); + if (Int32.TryParse(color, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out _)) + { + if (!color.StartsWith("#")) color = $"#{color}"; + } + else + { + Debug.LogWarning($"Color string: {color} no proper hexadecimal"); + return ""; + } + + return color; + } + + /// + /// Converts a hexadecimal color string to a Unity RGBA Color value + /// + /// var color = GetColor.FromHex("#CCCCCC"); + /// The string parameter must be a hexadecimal string, can beginning with # + /// Returns a Unity Color parameter converted from a HTML/hexadecimal color string + /// The string parameter must be a hexadecimal string beginning with # + public static Color FromHex(this string color) + { + if (color.StartsWith("#")) color = color.Replace("#", ""); + if (Int32.TryParse(color, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out _)) + if (!color.StartsWith("#")) + color = $"#{color}"; + + ColorUtility.TryParseHtmlString(color, out var outColor); + return outColor; + } + } +} diff --git a/Runtime/Util/ColorUtil.cs.meta b/Runtime/Util/ColorUtil.cs.meta new file mode 100644 index 0000000..6ae0632 --- /dev/null +++ b/Runtime/Util/ColorUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3748f65865ecc8906b3be74060a2f97e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples/Example_Scene.unity b/Samples/Example_Scene.unity index cb014bc..1c241c5 100644 --- a/Samples/Example_Scene.unity +++ b/Samples/Example_Scene.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} - m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_IndirectSpecularColor: {r: 0.37311956, g: 0.3807402, b: 0.3587274, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -213,7 +213,7 @@ Transform: m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} - m_RootOrder: 3 + m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &1422681869 GameObject: @@ -270,51 +270,8 @@ Transform: m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} - m_RootOrder: 1 - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!1 &1519831845 -GameObject: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - serializedVersion: 6 - m_Component: - - component: {fileID: 1519831846} - - component: {fileID: 1519831847} - m_Layer: 0 - m_Name: '--- GameObjects ' - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!4 &1519831846 -Transform: - m_ObjectHideFlags: 2 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1519831845} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: -144.9056, y: 279.31085, z: -33.603134} - m_LocalScale: {x: 1, y: 1, z: 1} - m_Children: [] - m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!114 &1519831847 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1519831845} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 84954765309f42545b586105e6165855, type: 3} - m_Name: - m_EditorClassIdentifier: --- !u!1 &2078427014 GameObject: m_ObjectHideFlags: 0 @@ -345,7 +302,7 @@ Transform: m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} - m_RootOrder: 2 + m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &2078427016 MonoBehaviour: @@ -399,72 +356,3 @@ MonoBehaviour: showHat: 0 containerBorders: {x: 0, y: 0, z: 0, w: 0} headerBorders: {x: 0, y: 0, z: 0, w: 0} ---- !u!1001 &6585872357801789431 -PrefabInstance: - m_ObjectHideFlags: 0 - serializedVersion: 2 - m_Modification: - m_TransformParent: {fileID: 0} - m_Modifications: - - target: {fileID: 895422604295798471, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_Name - value: OptimizedTree - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalPosition.x - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalPosition.y - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalPosition.z - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalRotation.x - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalRotation.y - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalRotation.z - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_RootOrder - value: 4 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalEulerAnglesHint.x - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalEulerAnglesHint.y - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 8666148472591186700, guid: 067d9f21617148e42959159f9134420d, - type: 3} - propertyPath: m_LocalEulerAnglesHint.z - value: 0 - objectReference: {fileID: 0} - m_RemovedComponents: [] - m_SourcePrefab: {fileID: 100100000, guid: 067d9f21617148e42959159f9134420d, type: 3} diff --git a/Samples/Scripts/Editor/ExampleComponentEditor.cs b/Samples/Scripts/Editor/ExampleComponentEditor.cs index 3282c93..b5111ae 100644 --- a/Samples/Scripts/Editor/ExampleComponentEditor.cs +++ b/Samples/Scripts/Editor/ExampleComponentEditor.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using instance.id.EATK.Editors; using instance.id.EATK.Extensions; -using instance.id.Extensions; using JetBrains.Annotations; using UnityEditor; using UnityEditor.UIElements; @@ -13,7 +11,7 @@ namespace instance.id.EATK.Examples { [CustomEditor(typeof(ExampleComponent))] - public class ExampleComponentEditor : DefaultUIElementsEditor + public class ExampleComponentEditor : Editor { private VisualElement root; private ExampleComponent exampleComponent; @@ -203,7 +201,7 @@ public override VisualElement CreateInspectorGUI() private void DeferredExecution(GeometryChangedEvent evt) { root.UnregisterCallback(DeferredExecution); - base.LoadingCompleted(root, target); + // base.LoadingCompleted(root, target); SetupHighlighter(); @@ -272,8 +270,8 @@ void Cleanup() } containerHighlighter = containerElement.AnimBorderPulse( - color1: GetColor.FromHex("#3A82E7"), - color2: GetColor.FromHex("#7F3B3A"), + color1: ColorUtil.FromHex("#3A82E7"), + color2: ColorUtil.FromHex("#7F3B3A"), original: default, color1DurationMs: color1Duration, color2DurationMs: color2Duration, @@ -304,8 +302,8 @@ void Cleanup() } headerHighlighter = headerContainer.AnimBorderPulse( - color1: GetColor.FromHex("#3A82E7"), - color2: GetColor.FromHex("#7F3B3A"), + color1: ColorUtil.FromHex("#3A82E7"), + color2: ColorUtil.FromHex("#7F3B3A"), original: default, color1DurationMs: color1Duration, color2DurationMs: color2Duration, diff --git a/package.json b/package.json index bb02ca3..4ccf695 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,11 @@ "name": "id.instance.elementanimationtoolkit", "displayName": "Element Animation Toolkit", "repositoryName": "Element Animation Toolkit", - "version": "0.1.6", + "version": "0.1.7", "description": "A collection of Unity UIElements standalone animations, new animated elements, and examples.", "type": "library", "unity": "2019.4", - "unityRelease": "20f1", + "unityRelease": "28f1", "keywords": [ "UI Elements", "UIElements", @@ -25,4 +25,4 @@ "dependencies": { "id.instance.extensions": "file:../../id.instance.packagerepo/Assets/instance.id/Extensions" } -} \ No newline at end of file +}