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.4KB

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