viewports.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const {
  6. ADD_VIEWPORT,
  7. CHANGE_DEVICE,
  8. CHANGE_PIXEL_RATIO,
  9. REMOVE_DEVICE,
  10. RESIZE_VIEWPORT,
  11. ROTATE_VIEWPORT,
  12. } = require("../actions/index");
  13. let nextViewportId = 0;
  14. const INITIAL_VIEWPORTS = [];
  15. const INITIAL_VIEWPORT = {
  16. id: nextViewportId++,
  17. device: "",
  18. width: 320,
  19. height: 480,
  20. pixelRatio: {
  21. value: 0,
  22. },
  23. };
  24. let reducers = {
  25. [ADD_VIEWPORT](viewports) {
  26. // For the moment, there can be at most one viewport.
  27. if (viewports.length === 1) {
  28. return viewports;
  29. }
  30. return [...viewports, Object.assign({}, INITIAL_VIEWPORT)];
  31. },
  32. [CHANGE_DEVICE](viewports, { id, device }) {
  33. return viewports.map(viewport => {
  34. if (viewport.id !== id) {
  35. return viewport;
  36. }
  37. return Object.assign({}, viewport, {
  38. device,
  39. });
  40. });
  41. },
  42. [CHANGE_PIXEL_RATIO](viewports, { id, pixelRatio }) {
  43. return viewports.map(viewport => {
  44. if (viewport.id !== id) {
  45. return viewport;
  46. }
  47. return Object.assign({}, viewport, {
  48. pixelRatio: {
  49. value: pixelRatio
  50. },
  51. });
  52. });
  53. },
  54. [REMOVE_DEVICE](viewports, { id }) {
  55. return viewports.map(viewport => {
  56. if (viewport.id !== id) {
  57. return viewport;
  58. }
  59. return Object.assign({}, viewport, {
  60. device: "",
  61. });
  62. });
  63. },
  64. [RESIZE_VIEWPORT](viewports, { id, width, height }) {
  65. return viewports.map(viewport => {
  66. if (viewport.id !== id) {
  67. return viewport;
  68. }
  69. if (!width) {
  70. width = viewport.width;
  71. }
  72. if (!height) {
  73. height = viewport.height;
  74. }
  75. return Object.assign({}, viewport, {
  76. width,
  77. height,
  78. });
  79. });
  80. },
  81. [ROTATE_VIEWPORT](viewports, { id }) {
  82. return viewports.map(viewport => {
  83. if (viewport.id !== id) {
  84. return viewport;
  85. }
  86. return Object.assign({}, viewport, {
  87. width: viewport.height,
  88. height: viewport.width,
  89. });
  90. });
  91. },
  92. };
  93. module.exports = function (viewports = INITIAL_VIEWPORTS, action) {
  94. let reducer = reducers[action.type];
  95. if (!reducer) {
  96. return viewports;
  97. }
  98. return reducer(viewports, action);
  99. };