ViewBox.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/CharacterTypes.h>
  7. #include <AK/GenericLexer.h>
  8. #include <AK/Optional.h>
  9. #include <AK/StringView.h>
  10. #include <LibWeb/SVG/ViewBox.h>
  11. namespace Web::SVG {
  12. Optional<ViewBox> try_parse_view_box(StringView string)
  13. {
  14. // FIXME: This should handle all valid viewBox values.
  15. GenericLexer lexer(string);
  16. enum State {
  17. MinX,
  18. MinY,
  19. Width,
  20. Height,
  21. };
  22. int state { State::MinX };
  23. ViewBox view_box;
  24. while (!lexer.is_eof()) {
  25. lexer.consume_while([](auto ch) { return is_ascii_space(ch); });
  26. auto token = lexer.consume_until([](auto ch) { return is_ascii_space(ch) && ch != ','; });
  27. auto maybe_number = token.to_int();
  28. if (!maybe_number.has_value())
  29. return {};
  30. switch (state) {
  31. case State::MinX:
  32. view_box.min_x = maybe_number.value();
  33. break;
  34. case State::MinY:
  35. view_box.min_y = maybe_number.value();
  36. break;
  37. case State::Width:
  38. view_box.width = maybe_number.value();
  39. break;
  40. case State::Height:
  41. view_box.height = maybe_number.value();
  42. break;
  43. default:
  44. return {};
  45. }
  46. state += 1;
  47. }
  48. return view_box;
  49. }
  50. }