You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

text.tsx 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import { uniqueId } from 'utils/utils'
  2. import { TextShape, ShapeType, FontSize } from 'types'
  3. import { registerShapeUtils } from './index'
  4. import {
  5. defaultStyle,
  6. getFontSize,
  7. getFontStyle,
  8. getShapeStyle,
  9. } from 'lib/shape-styles'
  10. import styled from 'styles'
  11. import state from 'state'
  12. import React from 'react'
  13. if (document.getElementById('__textMeasure')) {
  14. document.getElementById('__textMeasure').remove()
  15. }
  16. // A div used for measurement
  17. const mdiv = document.createElement('pre')
  18. mdiv.id = '__textMeasure'
  19. mdiv.style.whiteSpace = 'pre'
  20. mdiv.style.width = 'auto'
  21. mdiv.style.border = '1px solid red'
  22. mdiv.style.padding = '4px'
  23. mdiv.style.margin = '0px'
  24. mdiv.style.opacity = '0'
  25. mdiv.style.position = 'absolute'
  26. mdiv.style.top = '-500px'
  27. mdiv.style.left = '0px'
  28. mdiv.style.zIndex = '9999'
  29. mdiv.tabIndex = -1
  30. mdiv.setAttribute('readonly', 'true')
  31. document.body.appendChild(mdiv)
  32. function normalizeText(text: string) {
  33. return text.replace(/\t/g, ' ').replace(/\r?\n|\r/g, '\n')
  34. }
  35. const text = registerShapeUtils<TextShape>({
  36. isForeignObject: true,
  37. canChangeAspectRatio: false,
  38. canEdit: true,
  39. boundsCache: new WeakMap([]),
  40. create(props) {
  41. return {
  42. id: uniqueId(),
  43. seed: Math.random(),
  44. type: ShapeType.Text,
  45. isGenerated: false,
  46. name: 'Text',
  47. parentId: 'page1',
  48. childIndex: 0,
  49. point: [0, 0],
  50. rotation: 0,
  51. isAspectRatioLocked: false,
  52. isLocked: false,
  53. isHidden: false,
  54. style: defaultStyle,
  55. text: '',
  56. scale: 1,
  57. size: 'auto',
  58. fontSize: FontSize.Medium,
  59. ...props,
  60. }
  61. },
  62. render(shape, { isEditing, ref }) {
  63. const { id, text, style } = shape
  64. const styles = getShapeStyle(style)
  65. const font = getFontStyle(shape.fontSize, shape.scale, shape.style)
  66. const bounds = this.getBounds(shape)
  67. function handleChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
  68. state.send('EDITED_SHAPE', {
  69. change: { text: normalizeText(e.currentTarget.value) },
  70. })
  71. }
  72. function handleKeyDown(e: React.KeyboardEvent) {
  73. e.stopPropagation()
  74. if (e.key === 'Tab') {
  75. e.preventDefault()
  76. }
  77. }
  78. function handleBlur() {
  79. state.send('BLURRED_EDITING_SHAPE')
  80. }
  81. function handleFocus(e: React.FocusEvent<HTMLTextAreaElement>) {
  82. e.currentTarget.select()
  83. state.send('FOCUSED_EDITING_SHAPE')
  84. }
  85. const lineHeight = getFontSize(shape.fontSize) * shape.scale
  86. const gap = lineHeight * 0.4
  87. if (!isEditing) {
  88. return (
  89. <g id={id} pointerEvents="none">
  90. {text.split('\n').map((str, i) => (
  91. <text
  92. key={i}
  93. x={4}
  94. y={4 + gap / 2 + i * (lineHeight + gap)}
  95. style={{ font }}
  96. width={bounds.width}
  97. height={bounds.height}
  98. dominant-baseline="hanging"
  99. >
  100. {str}
  101. </text>
  102. ))}
  103. </g>
  104. )
  105. }
  106. return (
  107. <foreignObject
  108. id={id}
  109. x={0}
  110. y={0}
  111. width={bounds.width}
  112. height={bounds.height}
  113. pointerEvents="none"
  114. >
  115. {isEditing ? (
  116. <StyledTextArea
  117. ref={ref}
  118. style={{
  119. font,
  120. color: styles.stroke,
  121. }}
  122. tabIndex={0}
  123. value={text}
  124. autoComplete="false"
  125. autoCapitalize="false"
  126. autoCorrect="false"
  127. spellCheck="false"
  128. onFocus={handleFocus}
  129. onBlur={handleBlur}
  130. onKeyDown={handleKeyDown}
  131. onChange={handleChange}
  132. dir="auto"
  133. />
  134. ) : (
  135. <StyledText
  136. style={{
  137. font,
  138. color: styles.stroke,
  139. }}
  140. >
  141. {text}
  142. </StyledText>
  143. )}
  144. </foreignObject>
  145. )
  146. },
  147. getBounds(shape) {
  148. if (!this.boundsCache.has(shape)) {
  149. mdiv.innerHTML = shape.text + '&zwj;'
  150. mdiv.style.font = getFontStyle(shape.fontSize, shape.scale, shape.style)
  151. const [minX, minY] = shape.point
  152. const [width, height] = [mdiv.offsetWidth, mdiv.offsetHeight]
  153. this.boundsCache.set(shape, {
  154. minX,
  155. maxX: minX + width,
  156. minY,
  157. maxY: minY + height,
  158. width,
  159. height,
  160. })
  161. }
  162. return this.boundsCache.get(shape)
  163. },
  164. hitTest(shape, test) {
  165. return true
  166. },
  167. transform(shape, bounds, { initialShape, transformOrigin, scaleX, scaleY }) {
  168. if (shape.rotation === 0 && !shape.isAspectRatioLocked) {
  169. shape.point = [bounds.minX, bounds.minY]
  170. shape.scale = initialShape.scale * Math.abs(scaleX)
  171. } else {
  172. shape.point = [bounds.minX, bounds.minY]
  173. shape.rotation =
  174. (scaleX < 0 && scaleY >= 0) || (scaleY < 0 && scaleX >= 0)
  175. ? -initialShape.rotation
  176. : initialShape.rotation
  177. shape.scale = initialShape.scale * Math.abs(Math.min(scaleX, scaleY))
  178. }
  179. return this
  180. },
  181. transformSingle(shape, bounds, { initialShape, scaleX }) {
  182. shape.point = [bounds.minX, bounds.minY]
  183. shape.scale = initialShape.scale * Math.abs(scaleX)
  184. return this
  185. },
  186. onBoundsReset(shape) {
  187. shape.size = 'auto'
  188. return this
  189. },
  190. shouldDelete(shape) {
  191. return shape.text.length === 0
  192. },
  193. })
  194. export default text
  195. const StyledText = styled('div', {
  196. width: '100%',
  197. height: '100%',
  198. border: 'none',
  199. padding: '4px',
  200. whiteSpace: 'pre',
  201. minHeight: 1,
  202. minWidth: 1,
  203. outline: 0,
  204. backgroundColor: 'transparent',
  205. overflow: 'hidden',
  206. pointerEvents: 'none',
  207. userSelect: 'none',
  208. backfaceVisibility: 'hidden',
  209. display: 'inline-block',
  210. position: 'relative',
  211. zIndex: 0,
  212. })
  213. const StyledTextArea = styled('textarea', {
  214. width: '100%',
  215. height: '100%',
  216. border: 'none',
  217. padding: '4px',
  218. whiteSpace: 'pre',
  219. resize: 'none',
  220. minHeight: 1,
  221. minWidth: 1,
  222. outline: 0,
  223. backgroundColor: '$boundsBg',
  224. overflow: 'hidden',
  225. pointerEvents: 'all',
  226. backfaceVisibility: 'hidden',
  227. display: 'inline-block',
  228. })