Skip to content

Commit

Permalink
🐛 fix: input line-height
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Nov 27, 2020
1 parent 2293872 commit 87063af
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
16 changes: 16 additions & 0 deletions docs/e2e/basic/demos/Text/InputVerticalAligin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React from 'react';
import { useElements, TestLayout } from '@docs-utils';

export default () => {
const { elements, ref } = useElements();

return (
<TestLayout elements={elements}>
<div ref={ref}>
<div>
<input type="text" placeholder="垂直居中" style={{ lineHeight: 3 }} />
</div>
</div>
</TestLayout>
);
};
8 changes: 8 additions & 0 deletions docs/e2e/basic/text.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,11 @@ placeholder 和输入的值都在伪类里
### Input 文本居中

<code src="./demos/Text/InputAligin.tsx" />

### Input 文本垂直居中

#### Case1: line-height 超过 input 高度

目前这种垂直居中是因为 `line-height` 值超过了 input 的高度使得文本默认在垂直轴上是居中的

<code src="./demos/Text/InputVerticalAligin.tsx" />
25 changes: 24 additions & 1 deletion src/parser/inputText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const parseInputTextToText = (
pseudoText = placeholder;
}

const pseudoNode = node.cloneNode(true);
const pseudoNode = document.createElement('text');

const {
paddingLeft,
Expand All @@ -41,6 +41,8 @@ export const parseInputTextToText = (

const { rangeBCR } = getTextLinesAndRange(pseudoNode);

// 默认情况下的 y 采用 input 节点的 y 值
// 特殊情况在下面处理
let { y } = nodeBCR;

y = y + parseFloat(paddingTop) + parseFloat(borderTopWidth);
Expand Down Expand Up @@ -76,10 +78,31 @@ export const parseInputTextToText = (
});
});
}

textStyle.color = textColor;

textStyle.lineHeight = rangeBCR.height;

// 针对line-height 做单独处理:

// 如果 input 的 line-height 超过 rangeBCR 的 line-height
// 那么意味着 input 节点会被撑开,然后文本应该处于 input 的垂直居中位置
// 相关问题: https://github.com/ant-design/html2sketch/issues/50
// 问题 demo: https://codesandbox.io/s/optimistic-firefly-f7dy8?file=/src/Demo.tsx

const { lineHeight } = inputTextStyle;

// TODO: 还有什么时候需要垂直居中呢?
if (parseFloat(lineHeight) > rangeBCR.height) {
// 需要垂直居中的地方
console.log(y, nodeBCR.y);
console.log(nodeBCR.height, rangeBCR.height);
// 计算公式:
// 偏差值 = (input 的高度 - text 的高度 )/2 - 目前已有的offsetY
const offsetY = (nodeBCR.height - rangeBCR.height) / 2 - (y - nodeBCR.y);
y += offsetY;
}

const text = new Text({
x: 0,
y,
Expand Down

0 comments on commit 87063af

Please sign in to comment.