* 在指定位置创建一个输入框 * @param location 输入框的左上角位置(相对于窗口左上角的位置) * @param defaultValue 一开始的默认文本 * @param onChange 输入框文本改变函数 * @param style 输入框样式 * @returns
(
location: Vector,
defaultValue: string,
onChange: (value: string) => void = () => {},
style: Partial<CSSStyleDeclaration> = {},
)
| 21 | * @returns |
| 22 | */ |
| 23 | input( |
| 24 | location: Vector, |
| 25 | defaultValue: string, |
| 26 | onChange: (value: string) => void = () => {}, |
| 27 | style: Partial<CSSStyleDeclaration> = {}, |
| 28 | ): Promise<string> { |
| 29 | return new Promise((resolve) => { |
| 30 | const inputElement = document.createElement("input"); |
| 31 | inputElement.type = "text"; |
| 32 | inputElement.value = defaultValue; |
| 33 | |
| 34 | inputElement.style.position = "fixed"; |
| 35 | inputElement.style.top = `${location.y}px`; |
| 36 | inputElement.style.left = `${location.x}px`; |
| 37 | |
| 38 | inputElement.id = "pg-input"; |
| 39 | inputElement.autocomplete = "off"; |
| 40 | Object.assign(inputElement.style, style); |
| 41 | document.body.appendChild(inputElement); |
| 42 | inputElement.focus(); |
| 43 | inputElement.select(); |
| 44 | const removeElement = () => { |
| 45 | if (document.body.contains(inputElement)) { |
| 46 | try { |
| 47 | // 暂时关闭频繁弹窗报错。 |
| 48 | document.body.removeChild(inputElement); |
| 49 | } catch (error) { |
| 50 | console.error(error); |
| 51 | } |
| 52 | } |
| 53 | }; |
| 54 | const adjustSize = () => { |
| 55 | // inputElement.style.width = `${inputElement.scrollWidth + 2}px`; |
| 56 | }; |
| 57 | |
| 58 | const onOutsideClick = (event: Event) => { |
| 59 | if (!inputElement.contains(event.target as Node)) { |
| 60 | resolve(inputElement.value); |
| 61 | onChange(inputElement.value); |
| 62 | document.body.removeEventListener("mousedown", onOutsideClick); |
| 63 | removeElement(); |
| 64 | } |
| 65 | }; |
| 66 | const onOutsideWheel = () => { |
| 67 | resolve(inputElement.value); |
| 68 | onChange(inputElement.value); |
| 69 | document.body.removeEventListener("mousedown", onOutsideClick); |
| 70 | removeElement(); |
| 71 | }; |
| 72 | |
| 73 | // 初始化 |
| 74 | setTimeout(() => { |
| 75 | document.body.addEventListener("mousedown", onOutsideClick); |
| 76 | document.body.addEventListener("touchstart", onOutsideClick); |
| 77 | document.body.addEventListener("wheel", onOutsideWheel); |
| 78 | adjustSize(); // 初始化时调整大小 |
| 79 | }, 10); |
| 80 |
no test coverage detected