import { inheritedTextStyle } from '../import/flow' import type { DesignElement, DesignStyleDeclaration } from '../types' /** Input types that show what is typed, or their placeholder, as a line of text. */ const TEXT_INPUT_TYPES = new Set(['', 'text', 'email', 'search', 'url', 'tel', 'number']) /** The text a form field shows: what is typed into it, else its placeholder, and which. */ function shownText(field: HTMLInputElement | HTMLTextAreaElement) { if (field.value) return { text: field.value, placeholder: false } return field.placeholder ? { text: field.placeholder, placeholder: true } : null } /** * Shows the text a text field draws inside it, which no element of the page holds: what is typed * into it in its own style, or its placeholder in the `::placeholder` style, as a child named * `::value` or `::placeholder`, laid out in the field as a browser lays it out. A password's value * stays hidden. */ export function showFormText( pairs: readonly [DesignElement, Element][], view: Window & typeof globalThis, styleOf: (style: CSSStyleDeclaration) => DesignStyleDeclaration ): void { for (const [designElement, domElement] of pairs) { const isInput = domElement instanceof view.HTMLInputElement && TEXT_INPUT_TYPES.has(domElement.type) const field = isInput || domElement instanceof view.HTMLTextAreaElement ? domElement : null if (!field) continue const shown = shownText(field) const own = designElement.computedStyle // A field that is not rendered shows no text either. if (!shown || !own || own.display === 'none') continue const style = shown.placeholder ? styleOf(view.getComputedStyle(domElement, '::placeholder')) : own // A browser lays a field's text out inside it as a box of its own: a one-line field centers // its line however tall the field is, and a text area starts at the top. The field is that // box, which auto layout reproduces, inside the field's own padding. It stays in the line // it sits in, as an inline field does. designElement.computedStyle = { ...own, display: own.display === 'block' ? 'flex' : 'inline-flex', 'flex-direction': 'row', 'align-items': isInput ? 'center' : 'flex-start' } designElement.children = [ { type: 'element', tagName: shown.placeholder ? '::placeholder' : '::value', attrs: {}, children: [{ type: 'text', text: shown.text }], // Only the text's own styling, on the field's line: the field's padding, border, and // background stay on it. computedStyle: { ...inheritedTextStyle(style), 'line-height': own['line-height'] ?? 'normal', 'flex-grow': '1', 'white-space': isInput ? 'pre' : 'pre-wrap' } } ] } }