SvgStyleUnit.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. namespace PixiEditor.SVG.Units;
  2. public struct SvgStyleUnit : ISvgUnit
  3. {
  4. private Dictionary<string, string> inlineDefinedProperties;
  5. private string value;
  6. public SvgStyleUnit(string inlineStyle)
  7. {
  8. Value = inlineStyle;
  9. }
  10. public string Value
  11. {
  12. get => value;
  13. set
  14. {
  15. this.value = value;
  16. inlineDefinedProperties = new Dictionary<string, string>();
  17. if (string.IsNullOrEmpty(value))
  18. {
  19. return;
  20. }
  21. string[] properties = value.Split(';');
  22. foreach (string property in properties)
  23. {
  24. string[] keyValue = property.Split(':');
  25. if (keyValue.Length == 2)
  26. {
  27. inlineDefinedProperties.Add(keyValue[0].Trim(), keyValue[1].Trim());
  28. }
  29. }
  30. }
  31. }
  32. public string ToXml()
  33. {
  34. return Value;
  35. }
  36. public void ValuesFromXml(string readerValue)
  37. {
  38. Value = readerValue;
  39. }
  40. public TProp TryGetStyleFor<TProp, TUnit>(string property) where TProp : SvgProperty<TUnit> where TUnit : struct, ISvgUnit
  41. {
  42. if (inlineDefinedProperties.TryGetValue(property, out var definedProperty))
  43. {
  44. TProp prop = (TProp)Activator.CreateInstance(typeof(TProp), property);
  45. var unit = (TUnit)prop.CreateDefaultUnit();
  46. unit.ValuesFromXml(definedProperty);
  47. prop.Unit = unit;
  48. return prop;
  49. }
  50. return null;
  51. }
  52. public SvgStyleUnit MergeWith(SvgStyleUnit elementStyleUnit)
  53. {
  54. Dictionary<string, string> props = new(inlineDefinedProperties);
  55. foreach (var inlineDefined in elementStyleUnit.inlineDefinedProperties)
  56. {
  57. props[inlineDefined.Key] = inlineDefined.Value;
  58. }
  59. return new SvgStyleUnit(string.Join(";", props.Select(x => $"{x.Key}:{x.Value}")));
  60. }
  61. }