From 634e9ac890a1f31aa7fdd36ea69a30e0f2c5de69 Mon Sep 17 00:00:00 2001 From: Fabian Jakobs Date: Wed, 15 Dec 2010 14:13:44 +0100 Subject: [PATCH] optimize text size measurement code and fix ugly off by one error --- lib/ace/layer/text.js | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/lib/ace/layer/text.js b/lib/ace/layer/text.js index c8f60391..7af4c7aa 100644 --- a/lib/ace/layer/text.js +++ b/lib/ace/layer/text.js @@ -39,6 +39,7 @@ define(function(require, exports, module) { var oop = require("pilot/oop"); var dom = require("pilot/dom"); +var lang = require("pilot/lang"); var EventEmitter = require("pilot/event_emitter").EventEmitter; var Text = function(parentEl) { @@ -79,7 +80,7 @@ var Text = function(parentEl) { self.$characterSize = size; self._dispatchEvent("changeCharaterSize", {data: size}); } - }, 1000); + }, 500); }; this.$fontStyles = { @@ -91,32 +92,37 @@ var Text = function(parentEl) { }, this.$measureSizes = function() { - var measureNode = document.createElement("div"); - var style = measureNode.style; - - style.width = style.height = "auto"; - style.left = style.top = "-1000px"; - style.visibility = "hidden"; - style.position = "absolute"; - style.overflow = "visible"; + if (!this.$measureNode) { + var measureNode = this.$measureNode = document.createElement("div"); + var style = measureNode.style; + + style.width = style.height = "auto"; + style.left = style.top = "-1000px"; + + style.visibility = "hidden"; + style.position = "absolute"; + style.overflow = "visible"; + style.whiteSpace = "nowrap"; + + // in FF 3.6 monospace fonts can have a fixed sub pixel width. + // that's why we have to measure many characters + // Note: characterWidth can be a float! + var n = 1000; + measureNode.innerHTML = lang.stringRepeat("Xy", n); + document.body.insertBefore(measureNode, document.body.firstChild); + } + var style = this.$measureNode; for (var prop in this.$fontStyles) { var value = dom.computedStyle(this.element, prop); style[prop] = value; } - // in FF 3.6 monospace fonts can have a fixed sub pixel width. - // that's why we have to measure many characters - // Note: characterWidth can be a float! - measureNode.innerHTML = new Array(10000).join("Xy"); - document.body.insertBefore(measureNode, document.body.firstChild); - var size = { - height: measureNode.offsetHeight, - width: measureNode.offsetWidth / 20000 + height: this.$measureNode.offsetHeight, + width: this.$measureNode.offsetWidth / (n * 2) }; - document.body.removeChild(measureNode); return size; };