util.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * <<
  3. * Davinci
  4. * ==
  5. * Copyright (C) 2016 - 2017 EDP
  6. * ==
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * >>
  19. */
  20. import produce from 'immer'
  21. import { LayerAlignmentTypes } from './types'
  22. import { ILayerFormed } from '../../types'
  23. export const setLayersAlignment = (
  24. layers: ILayerFormed[],
  25. alignmentType: LayerAlignmentTypes
  26. ) => {
  27. if (!layers.length) {
  28. return []
  29. }
  30. const [minPosX, minPosY, rightX, bottomY] = layers.reduce(
  31. (
  32. [minX, minY, rightX, bottomY],
  33. { params: { positionX, positionY, width, height } }
  34. ) => [
  35. Math.min(minX, positionX),
  36. Math.min(minY, positionY),
  37. Math.max(positionX + width, rightX),
  38. Math.max(positionY + height, bottomY)
  39. ],
  40. [Infinity, Infinity, 0, 0]
  41. )
  42. const updateLayers = produce(layers, (draft) => {
  43. switch (alignmentType) {
  44. case LayerAlignmentTypes.Top:
  45. layers.forEach((l) => {
  46. l.params.positionY = minPosY
  47. })
  48. break
  49. case LayerAlignmentTypes.Left:
  50. layers.forEach((l) => {
  51. l.params.positionX = minPosX
  52. })
  53. break
  54. case LayerAlignmentTypes.Bottom:
  55. layers.forEach((l) => {
  56. l.params.positionY = bottomY - l.params.height
  57. })
  58. break
  59. case LayerAlignmentTypes.Right:
  60. layers.forEach((l) => {
  61. l.params.positionX = rightX - l.params.width
  62. })
  63. break
  64. case LayerAlignmentTypes.HorizontalCenter:
  65. const midPosX = (minPosX + rightX) / 2
  66. layers.forEach((l) => {
  67. l.params.positionX = midPosX - l.params.width / 2
  68. })
  69. break
  70. case LayerAlignmentTypes.VerticalCenter:
  71. const midPosY = (minPosY + bottomY) / 2
  72. layers.forEach((l) => {
  73. l.params.positionY = minPosY - l.params.height / 2
  74. })
  75. break
  76. }
  77. })
  78. return updateLayers
  79. }