layout.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. var zrUtil = require("zrender/lib/core/util");
  20. var BoundingRect = require("zrender/lib/core/BoundingRect");
  21. var _number = require("./number");
  22. var parsePercent = _number.parsePercent;
  23. var formatUtil = require("./format");
  24. /*
  25. * Licensed to the Apache Software Foundation (ASF) under one
  26. * or more contributor license agreements. See the NOTICE file
  27. * distributed with this work for additional information
  28. * regarding copyright ownership. The ASF licenses this file
  29. * to you under the Apache License, Version 2.0 (the
  30. * "License"); you may not use this file except in compliance
  31. * with the License. You may obtain a copy of the License at
  32. *
  33. * http://www.apache.org/licenses/LICENSE-2.0
  34. *
  35. * Unless required by applicable law or agreed to in writing,
  36. * software distributed under the License is distributed on an
  37. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38. * KIND, either express or implied. See the License for the
  39. * specific language governing permissions and limitations
  40. * under the License.
  41. */
  42. // Layout helpers for each component positioning
  43. var each = zrUtil.each;
  44. /**
  45. * @public
  46. */
  47. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  48. /**
  49. * @public
  50. */
  51. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  52. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  53. var x = 0;
  54. var y = 0;
  55. if (maxWidth == null) {
  56. maxWidth = Infinity;
  57. }
  58. if (maxHeight == null) {
  59. maxHeight = Infinity;
  60. }
  61. var currentLineMaxSize = 0;
  62. group.eachChild(function (child, idx) {
  63. var position = child.position;
  64. var rect = child.getBoundingRect();
  65. var nextChild = group.childAt(idx + 1);
  66. var nextChildRect = nextChild && nextChild.getBoundingRect();
  67. var nextX;
  68. var nextY;
  69. if (orient === 'horizontal') {
  70. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  71. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  72. // FIXME compare before adding gap?
  73. if (nextX > maxWidth || child.newline) {
  74. x = 0;
  75. nextX = moveX;
  76. y += currentLineMaxSize + gap;
  77. currentLineMaxSize = rect.height;
  78. } else {
  79. // FIXME: consider rect.y is not `0`?
  80. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  81. }
  82. } else {
  83. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  84. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  85. if (nextY > maxHeight || child.newline) {
  86. x += currentLineMaxSize + gap;
  87. y = 0;
  88. nextY = moveY;
  89. currentLineMaxSize = rect.width;
  90. } else {
  91. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  92. }
  93. }
  94. if (child.newline) {
  95. return;
  96. }
  97. position[0] = x;
  98. position[1] = y;
  99. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  100. });
  101. }
  102. /**
  103. * VBox or HBox layouting
  104. * @param {string} orient
  105. * @param {module:zrender/container/Group} group
  106. * @param {number} gap
  107. * @param {number} [width=Infinity]
  108. * @param {number} [height=Infinity]
  109. */
  110. var box = boxLayout;
  111. /**
  112. * VBox layouting
  113. * @param {module:zrender/container/Group} group
  114. * @param {number} gap
  115. * @param {number} [width=Infinity]
  116. * @param {number} [height=Infinity]
  117. */
  118. var vbox = zrUtil.curry(boxLayout, 'vertical');
  119. /**
  120. * HBox layouting
  121. * @param {module:zrender/container/Group} group
  122. * @param {number} gap
  123. * @param {number} [width=Infinity]
  124. * @param {number} [height=Infinity]
  125. */
  126. var hbox = zrUtil.curry(boxLayout, 'horizontal');
  127. /**
  128. * If x or x2 is not specified or 'center' 'left' 'right',
  129. * the width would be as long as possible.
  130. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  131. * the height would be as long as possible.
  132. *
  133. * @param {Object} positionInfo
  134. * @param {number|string} [positionInfo.x]
  135. * @param {number|string} [positionInfo.y]
  136. * @param {number|string} [positionInfo.x2]
  137. * @param {number|string} [positionInfo.y2]
  138. * @param {Object} containerRect {width, height}
  139. * @param {string|number} margin
  140. * @return {Object} {width, height}
  141. */
  142. function getAvailableSize(positionInfo, containerRect, margin) {
  143. var containerWidth = containerRect.width;
  144. var containerHeight = containerRect.height;
  145. var x = parsePercent(positionInfo.x, containerWidth);
  146. var y = parsePercent(positionInfo.y, containerHeight);
  147. var x2 = parsePercent(positionInfo.x2, containerWidth);
  148. var y2 = parsePercent(positionInfo.y2, containerHeight);
  149. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  150. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  151. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  152. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  153. margin = formatUtil.normalizeCssArray(margin || 0);
  154. return {
  155. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  156. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  157. };
  158. }
  159. /**
  160. * Parse position info.
  161. *
  162. * @param {Object} positionInfo
  163. * @param {number|string} [positionInfo.left]
  164. * @param {number|string} [positionInfo.top]
  165. * @param {number|string} [positionInfo.right]
  166. * @param {number|string} [positionInfo.bottom]
  167. * @param {number|string} [positionInfo.width]
  168. * @param {number|string} [positionInfo.height]
  169. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  170. * @param {Object} containerRect
  171. * @param {string|number} [margin]
  172. *
  173. * @return {module:zrender/core/BoundingRect}
  174. */
  175. function getLayoutRect(positionInfo, containerRect, margin) {
  176. margin = formatUtil.normalizeCssArray(margin || 0);
  177. var containerWidth = containerRect.width;
  178. var containerHeight = containerRect.height;
  179. var left = parsePercent(positionInfo.left, containerWidth);
  180. var top = parsePercent(positionInfo.top, containerHeight);
  181. var right = parsePercent(positionInfo.right, containerWidth);
  182. var bottom = parsePercent(positionInfo.bottom, containerHeight);
  183. var width = parsePercent(positionInfo.width, containerWidth);
  184. var height = parsePercent(positionInfo.height, containerHeight);
  185. var verticalMargin = margin[2] + margin[0];
  186. var horizontalMargin = margin[1] + margin[3];
  187. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  188. if (isNaN(width)) {
  189. width = containerWidth - right - horizontalMargin - left;
  190. }
  191. if (isNaN(height)) {
  192. height = containerHeight - bottom - verticalMargin - top;
  193. }
  194. if (aspect != null) {
  195. // If width and height are not given
  196. // 1. Graph should not exceeds the container
  197. // 2. Aspect must be keeped
  198. // 3. Graph should take the space as more as possible
  199. // FIXME
  200. // Margin is not considered, because there is no case that both
  201. // using margin and aspect so far.
  202. if (isNaN(width) && isNaN(height)) {
  203. if (aspect > containerWidth / containerHeight) {
  204. width = containerWidth * 0.8;
  205. } else {
  206. height = containerHeight * 0.8;
  207. }
  208. } // Calculate width or height with given aspect
  209. if (isNaN(width)) {
  210. width = aspect * height;
  211. }
  212. if (isNaN(height)) {
  213. height = width / aspect;
  214. }
  215. } // If left is not specified, calculate left from right and width
  216. if (isNaN(left)) {
  217. left = containerWidth - right - width - horizontalMargin;
  218. }
  219. if (isNaN(top)) {
  220. top = containerHeight - bottom - height - verticalMargin;
  221. } // Align left and top
  222. switch (positionInfo.left || positionInfo.right) {
  223. case 'center':
  224. left = containerWidth / 2 - width / 2 - margin[3];
  225. break;
  226. case 'right':
  227. left = containerWidth - width - horizontalMargin;
  228. break;
  229. }
  230. switch (positionInfo.top || positionInfo.bottom) {
  231. case 'middle':
  232. case 'center':
  233. top = containerHeight / 2 - height / 2 - margin[0];
  234. break;
  235. case 'bottom':
  236. top = containerHeight - height - verticalMargin;
  237. break;
  238. } // If something is wrong and left, top, width, height are calculated as NaN
  239. left = left || 0;
  240. top = top || 0;
  241. if (isNaN(width)) {
  242. // Width may be NaN if only one value is given except width
  243. width = containerWidth - horizontalMargin - left - (right || 0);
  244. }
  245. if (isNaN(height)) {
  246. // Height may be NaN if only one value is given except height
  247. height = containerHeight - verticalMargin - top - (bottom || 0);
  248. }
  249. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  250. rect.margin = margin;
  251. return rect;
  252. }
  253. /**
  254. * Position a zr element in viewport
  255. * Group position is specified by either
  256. * {left, top}, {right, bottom}
  257. * If all properties exists, right and bottom will be igonred.
  258. *
  259. * Logic:
  260. * 1. Scale (against origin point in parent coord)
  261. * 2. Rotate (against origin point in parent coord)
  262. * 3. Traslate (with el.position by this method)
  263. * So this method only fixes the last step 'Traslate', which does not affect
  264. * scaling and rotating.
  265. *
  266. * If be called repeatly with the same input el, the same result will be gotten.
  267. *
  268. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  269. * @param {Object} positionInfo
  270. * @param {number|string} [positionInfo.left]
  271. * @param {number|string} [positionInfo.top]
  272. * @param {number|string} [positionInfo.right]
  273. * @param {number|string} [positionInfo.bottom]
  274. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  275. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  276. * @param {Object} containerRect
  277. * @param {string|number} margin
  278. * @param {Object} [opt]
  279. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  280. * @param {Array.<number>} [opt.boundingMode='all']
  281. * Specify how to calculate boundingRect when locating.
  282. * 'all': Position the boundingRect that is transformed and uioned
  283. * both itself and its descendants.
  284. * This mode simplies confine the elements in the bounding
  285. * of their container (e.g., using 'right: 0').
  286. * 'raw': Position the boundingRect that is not transformed and only itself.
  287. * This mode is useful when you want a element can overflow its
  288. * container. (Consider a rotated circle needs to be located in a corner.)
  289. * In this mode positionInfo.width/height can only be number.
  290. */
  291. function positionElement(el, positionInfo, containerRect, margin, opt) {
  292. var h = !opt || !opt.hv || opt.hv[0];
  293. var v = !opt || !opt.hv || opt.hv[1];
  294. var boundingMode = opt && opt.boundingMode || 'all';
  295. if (!h && !v) {
  296. return;
  297. }
  298. var rect;
  299. if (boundingMode === 'raw') {
  300. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  301. } else {
  302. rect = el.getBoundingRect();
  303. if (el.needLocalTransform()) {
  304. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  305. // which should not be modified.
  306. rect = rect.clone();
  307. rect.applyTransform(transform);
  308. }
  309. } // The real width and height can not be specified but calculated by the given el.
  310. positionInfo = getLayoutRect(zrUtil.defaults({
  311. width: rect.width,
  312. height: rect.height
  313. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  314. // (see zrender/core/Transformable#getLocalTransform),
  315. // we can just only modify el.position to get final result.
  316. var elPos = el.position;
  317. var dx = h ? positionInfo.x - rect.x : 0;
  318. var dy = v ? positionInfo.y - rect.y : 0;
  319. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  320. }
  321. /**
  322. * @param {Object} option Contains some of the properties in HV_NAMES.
  323. * @param {number} hvIdx 0: horizontal; 1: vertical.
  324. */
  325. function sizeCalculable(option, hvIdx) {
  326. return option[HV_NAMES[hvIdx][0]] != null || option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null;
  327. }
  328. /**
  329. * Consider Case:
  330. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  331. * through setOption or media query, using normal zrUtil.merge will cause
  332. * {right: 0} does not take effect.
  333. *
  334. * @example
  335. * ComponentModel.extend({
  336. * init: function () {
  337. * ...
  338. * var inputPositionParams = layout.getLayoutParams(option);
  339. * this.mergeOption(inputPositionParams);
  340. * },
  341. * mergeOption: function (newOption) {
  342. * newOption && zrUtil.merge(thisOption, newOption, true);
  343. * layout.mergeLayoutParam(thisOption, newOption);
  344. * }
  345. * });
  346. *
  347. * @param {Object} targetOption
  348. * @param {Object} newOption
  349. * @param {Object|string} [opt]
  350. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  351. * that width (or height) should not be calculated by left and right (or top and bottom).
  352. */
  353. function mergeLayoutParam(targetOption, newOption, opt) {
  354. !zrUtil.isObject(opt) && (opt = {});
  355. var ignoreSize = opt.ignoreSize;
  356. !zrUtil.isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  357. var hResult = merge(HV_NAMES[0], 0);
  358. var vResult = merge(HV_NAMES[1], 1);
  359. copy(HV_NAMES[0], targetOption, hResult);
  360. copy(HV_NAMES[1], targetOption, vResult);
  361. function merge(names, hvIdx) {
  362. var newParams = {};
  363. var newValueCount = 0;
  364. var merged = {};
  365. var mergedValueCount = 0;
  366. var enoughParamNumber = 2;
  367. each(names, function (name) {
  368. merged[name] = targetOption[name];
  369. });
  370. each(names, function (name) {
  371. // Consider case: newOption.width is null, which is
  372. // set by user for removing width setting.
  373. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  374. hasValue(newParams, name) && newValueCount++;
  375. hasValue(merged, name) && mergedValueCount++;
  376. });
  377. if (ignoreSize[hvIdx]) {
  378. // Only one of left/right is premitted to exist.
  379. if (hasValue(newOption, names[1])) {
  380. merged[names[2]] = null;
  381. } else if (hasValue(newOption, names[2])) {
  382. merged[names[1]] = null;
  383. }
  384. return merged;
  385. } // Case: newOption: {width: ..., right: ...},
  386. // or targetOption: {right: ...} and newOption: {width: ...},
  387. // There is no conflict when merged only has params count
  388. // little than enoughParamNumber.
  389. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  390. return merged;
  391. } // Case: newOption: {width: ..., right: ...},
  392. // Than we can make sure user only want those two, and ignore
  393. // all origin params in targetOption.
  394. else if (newValueCount >= enoughParamNumber) {
  395. return newParams;
  396. } else {
  397. // Chose another param from targetOption by priority.
  398. for (var i = 0; i < names.length; i++) {
  399. var name = names[i];
  400. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  401. newParams[name] = targetOption[name];
  402. break;
  403. }
  404. }
  405. return newParams;
  406. }
  407. }
  408. function hasProp(obj, name) {
  409. return obj.hasOwnProperty(name);
  410. }
  411. function hasValue(obj, name) {
  412. return obj[name] != null && obj[name] !== 'auto';
  413. }
  414. function copy(names, target, source) {
  415. each(names, function (name) {
  416. target[name] = source[name];
  417. });
  418. }
  419. }
  420. /**
  421. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  422. * @param {Object} source
  423. * @return {Object} Result contains those props.
  424. */
  425. function getLayoutParams(source) {
  426. return copyLayoutParams({}, source);
  427. }
  428. /**
  429. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  430. * @param {Object} source
  431. * @return {Object} Result contains those props.
  432. */
  433. function copyLayoutParams(target, source) {
  434. source && target && each(LOCATION_PARAMS, function (name) {
  435. source.hasOwnProperty(name) && (target[name] = source[name]);
  436. });
  437. return target;
  438. }
  439. exports.LOCATION_PARAMS = LOCATION_PARAMS;
  440. exports.HV_NAMES = HV_NAMES;
  441. exports.box = box;
  442. exports.vbox = vbox;
  443. exports.hbox = hbox;
  444. exports.getAvailableSize = getAvailableSize;
  445. exports.getLayoutRect = getLayoutRect;
  446. exports.positionElement = positionElement;
  447. exports.sizeCalculable = sizeCalculable;
  448. exports.mergeLayoutParam = mergeLayoutParam;
  449. exports.getLayoutParams = getLayoutParams;
  450. exports.copyLayoutParams = copyLayoutParams;