使用 <textarea> 作為欄位時,就能容納多行的值。在其中按 Enter 會換行,因此要按 Control 或 Command 加 Enter 才會儲存。值為空時,預覽會在 editable-placeholder 中顯示欄位的 placeholder。
多行
<divclass="max-w(420)mx-autotext-smfg-text-body"><spanclass="blockmb-xstext-xsfg-text-muted"id="doc-summary-label">Summary</span><divclass="editable w-full"><buttontype="button"class="editable-preview"id="doc-summary-preview"aria-labelledby="doc-summary-label doc-summary-preview"><spanclass="editable-placeholder">Add a summary for the team</span><svgclass="icon editable-pencil"viewBox="0 0 16 16"fill="none"stroke="currentColor"stroke-width="1"stroke-linecap="round"stroke-linejoin="round"aria-hidden="true"><pathd="M2.6556 12.4849L3.2844 10.1793A0.7 0.7 0 0 1 3.4647 9.8686L10.505 2.8283A0.7 0.7 0 0 1 11.495 2.8283L13.1717 4.505A0.7 0.7 0 0 1 13.1717 5.495L6.1314 12.5353A0.7 0.7 0 0 1 5.8207 12.7156L3.5151 13.3444A0.7 0.7 0 0 1 2.6556 12.4849Z"/><pathd="M9.6667 3.6667L12.3333 6.3333"/></svg></button><textareaclass="editable-field"aria-labelledby="doc-summary-label"placeholder="Add a summary for the team"rows="3"hidden></textarea></div></div><scripttype="module">import{ attach }from'@master/ui/behaviors'attach()</script>
import{ useEffect, useRef }from'react'import{ attach }from'@master/ui/behaviors'import PencilIcon from'@master/icons-react/native/16/soft/pencil'exportfunctionExample(){const root =useRef<HTMLDivElement>(null)useEffect(()=>attach(root.current!),[])return(<divref={root}className="max-w(420)mx-autotext-smfg-text-body"><spanclassName="blockmb-xstext-xsfg-text-muted"id="doc-summary-label">Summary</span><divclassName="editable w-full"><buttontype="button"className="editable-preview"id="doc-summary-preview"aria-labelledby="doc-summary-label doc-summary-preview"><spanclassName="editable-placeholder">Add a summary for the team</span><PencilIconclassName="icon editable-pencil"/></button><textareaclassName="editable-field"aria-labelledby="doc-summary-label"placeholder="Add a summary for the team"rows={3}hidden>{``}</textarea></div></div>)}
<script>import{ attach }from'@master/ui/behaviors'import PencilIcon from'@master/icons-svelte/native/16/soft/pencil'</script><divclass="max-w(420)mx-autotext-smfg-text-body"{@attach attach}><spanclass="blockmb-xstext-xsfg-text-muted"id="doc-summary-label">Summary</span><divclass="editable w-full"><buttontype="button"class="editable-preview"id="doc-summary-preview"aria-labelledby="doc-summary-label doc-summary-preview"><spanclass="editable-placeholder">Add a summary for the team</span><PencilIconclass="icon editable-pencil"/></button><textareaclass="editable-field"aria-labelledby="doc-summary-label"placeholder="Add a summary for the team"rows="3"hidden></textarea></div></div>
<scriptsetup>import{ onMounted, onUnmounted, ref }from'vue'import{ attach }from'@master/ui/behaviors'import PencilIcon from'@master/icons-vue/native/16/soft/pencil'const root =ref(null)let detachonMounted(()=>{ detach =attach(root.value)})onUnmounted(()=>detach?.())</script><template><divref="root"class="max-w(420)mx-autotext-smfg-text-body"><spanclass="blockmb-xstext-xsfg-text-muted"id="doc-summary-label">Summary</span><divclass="editable w-full"><buttontype="button"class="editable-preview"id="doc-summary-preview"aria-labelledby="doc-summary-label doc-summary-preview"><spanclass="editable-placeholder">Add a summary for the team</span><PencilIconclass="icon editable-pencil"/></button><textareaclass="editable-field"aria-labelledby="doc-summary-label"placeholder="Add a summary for the team"rows="3"hidden></textarea></div></div></template>
import{ editable }from'@master/ui/behaviors/editable.js'const title =editable(document.querySelector('.editable'))title.edit()// open the fieldtitle.value// the saved value
開啟。 按下預覽時,預覽會隱藏,並顯示帶有已儲存值的欄位,同時選取其中的文字。
儲存。 按 Enter 會儲存,離開欄位時也會儲存。欄位本身的限制條件(required、maxlength、pattern)所拒絕的值不會儲存:按 Enter 時欄位會維持開啟,由瀏覽器說明原因;離開欄位時則會還原已儲存的值。若要讓離開欄位改為取消編輯,請傳入 blur: 'cancel'。
取消。 按 Escape 會還原已儲存的值。
焦點在按 Enter 或 Escape 後會回到預覽;若使用者已將焦點移到別處,則不會移回。
事件。 儲存與原本不同的值時,會將值寫入預覽,並由欄位派送 input 和 change。傳回的函式帶有 value(已儲存的值)和 edit();設定 value 會同時寫入預覽和欄位,但不會派送任何事件。
'use client'import{ useId, useState,type ComponentProps }from'react'import{ editable }from'@master/ui/behaviors/editable.js'import{ useBehavior }from'./use-behavior'typeField=Omit<ComponentProps<'input'>,'value'|'defaultValue'|'hidden'>&Omit<ComponentProps<'textarea'>,'value'|'defaultValue'|'hidden'>exportinterfaceEditablePropsextendsOmit<Field,'children'>{/** The saved value. */value?:stringdefaultValue?:stringonValueChange?:(value:string)=>void/** What the value is, read with it by assistive technology: the field's name. */label:string/** A textarea, for a value of several lines. */multiline?:boolean/** The value is on its way: the preview waits. */busy?:boolean/** What leaving the field does. `'save'` by default. */blur?:'save'|'cancel'}/** * An editable value. Every prop of a field goes to the field, so `required`, `maxLength` and `placeholder` * are its constraints and what the preview says while the value is empty. *//** The behavior finds its field as it attaches. One line and several are two elements, so it attaches again when `multiline` changes. */constfielded=(root:HTMLElement, options?:{blur?:'save'|'cancel',multiline?:boolean})=>editable(root,{blur: options?.blur})exportfunctionEditable({ value, defaultValue, onValueChange, label, multiline, busy, blur, disabled, className,...field }:EditableProps){const id =useId()// The first value is drawn into the first render; after that the behavior writes the preview and the field.const[first]=useState(()=> value ?? defaultValue ??'')const ref =useBehavior(fielded,{ blur, multiline },{ value, defaultValue, onValueChange })const shared ={className:'editable-field','aria-label': label, disabled,hidden:true}return(<divclassName={className ?`editable ${className}`:'editable'}ref={ref}aria-busy={busy ||undefined}><buttontype="button"className="editable-preview"id={`${id}preview`}aria-labelledby={`${id}name ${id}preview`}disabled={disabled}>{first ||(field.placeholder?<spanclassName="editable-placeholder">{field.placeholder}</span>:null)}<svgclassName="icon editable-pencil"viewBox="0 0 16 16"fill="none"stroke="currentColor"strokeWidth="1"strokeLinecap="round"strokeLinejoin="round"aria-hidden="true"><pathd="M2.6556 12.4849L3.2844 10.1793A0.7 0.7 0 0 1 3.4647 9.8686L10.505 2.8283A0.7 0.7 0 0 1 11.495 2.8283L13.1717 4.505A0.7 0.7 0 0 1 13.1717 5.495L6.1314 12.5353A0.7 0.7 0 0 1 5.8207 12.7156L3.5151 13.3444A0.7 0.7 0 0 1 2.6556 12.4849Z"/><pathd="M9.6667 3.6667L12.3333 6.3333"/></svg></button><spanid={`${id}name`}hidden>{label}</span>{multiline?<textarea{...(field asComponentProps<'textarea'>)}{...shared}defaultValue={first}/>:<input{...(field asComponentProps<'input'>)}{...shared}defaultValue={first}/>}</div>)}
ui/Editable.svelte
<scriptlang="ts"module>importtype{ HTMLInputAttributes }from'svelte/elements'exportinterfaceEditablePropsextendsOmit<HTMLInputAttributes,'value'|'hidden'|'children'>{/** The saved value. Bind it, or leave it out. */value?:stringonValueChange?:(value:string)=>void/** What the value is, read with it by assistive technology: the field's name. */label:string/** A textarea, for a value of several lines. */multiline?:boolean/** The value is on its way: the preview waits. */busy?:boolean/** What leaving the field does. `'save'` by default. */blur?:'save'|'cancel'}</script><scriptlang="ts">import{ untrack }from'svelte'import{ editable }from'@master/ui/behaviors/editable.js'import{ behavior }from'./behavior.svelte.js'let{ value =$bindable(), onValueChange, label, multiline, busy, blur, disabled,class: className,...field }:EditableProps=$props()const id =$props.id()// The first value is drawn into the first render; after that the behavior writes the preview and the field.const first =untrack(()=> value)??''// The behavior finds its field as it attaches. One line and several are two elements, so it attaches again when `multiline` changes.constfielded=(root:HTMLElement, options?:{blur?:'save'|'cancel',multiline?:boolean})=>editable(root,{blur: options?.blur})const attach =behavior(fielded,()=>({ blur, multiline }),{value:()=> value,change:(next)=>{ value = next;onValueChange?.(next)},})</script><!--@component An editable value. Every other prop of a field goes to the field, so `required`, `maxlength` and`placeholder` are its constraints and what the preview says while the value is empty.--><divclass={['editable', className]}aria-busy={busy ||undefined}{@attach attach}><buttontype="button"class="editable-preview"id="{id}preview"aria-labelledby="{id}name {id}preview"{disabled}>{#if first}{first}{:else if field.placeholder}<spanclass="editable-placeholder">{field.placeholder}</span>{/if}<svgclass="icon editable-pencil"viewBox="0 0 16 16"fill="none"stroke="currentColor"stroke-width="1"stroke-linecap="round"stroke-linejoin="round"aria-hidden="true"><pathd="M2.6556 12.4849L3.2844 10.1793A0.7 0.7 0 0 1 3.4647 9.8686L10.505 2.8283A0.7 0.7 0 0 1 11.495 2.8283L13.1717 4.505A0.7 0.7 0 0 1 13.1717 5.495L6.1314 12.5353A0.7 0.7 0 0 1 5.8207 12.7156L3.5151 13.3444A0.7 0.7 0 0 1 2.6556 12.4849Z"/><pathd="M9.6667 3.6667L12.3333 6.3333"/></svg></button><spanid="{id}name"hidden>{label}</span>{#if multiline}<textareaclass="editable-field"aria-label={label}{disabled}hidden{...field asRecord<string,unknown>}value={first}></textarea>{:else}<inputclass="editable-field"aria-label={label}{disabled}hidden{...field}value={first}/>{/if}</div>
ui/Editable.vue
<scriptsetuplang="ts">import{ useAttrs, useId, useTemplateRef }from'vue'import{ editable }from'@master/ui/behaviors/editable.js'import{ useBehavior }from'./use-behavior'defineOptions({inheritAttrs:false})const{ blur, multiline }=defineProps<{/** What the value is, read with it by assistive technology: the field's name. */label:string/** A textarea, for a value of several lines. */multiline?:boolean/** The value is on its way: the preview waits. */busy?:boolean/** What leaving the field does. `'save'` by default. */blur?:'save'|'cancel'disabled?:boolean}>()/** The saved value: `v-model`. */const model =defineModel<string>()/* * An editable value. Every attribute but the class goes to the field, so `required`, `maxlength` and * `placeholder` are its constraints and what the preview says while the value is empty. */const id =useId()const attrs =useAttrs()constfield=()=>{const{class: _,...rest }= attrsreturn rest}// The first value is drawn into the first render; after that the behavior writes the preview and the field.const first = model.value??''const placeholder = attrs.placeholderasstring|undefinedconst root =useTemplateRef<HTMLDivElement>('root')// The behavior finds its field as it attaches. One line and several are two elements, so it attaches again when `multiline` changes.constfielded=(element:HTMLElement, options?:{blur?:'save'|'cancel',multiline?:boolean})=>editable(element,{blur: options?.blur})useBehavior(root, fielded,()=>({ blur, multiline }), model)</script><template><divclass="editable":class="$attrs.class":aria-busy="busy ||undefined"ref="root"><buttontype="button"class="editable-preview":id="`${id}-preview`":aria-labelledby="`${id}-name ${id}-preview`":disabled="disabled"><templatev-if="first">{{ first }}</template><spanv-else-if="placeholder"class="editable-placeholder">{{ placeholder }}</span><svgclass="icon editable-pencil"viewBox="0 0 16 16"fill="none"stroke="currentColor"stroke-width="1"stroke-linecap="round"stroke-linejoin="round"aria-hidden="true"><pathd="M2.6556 12.4849L3.2844 10.1793A0.7 0.7 0 0 1 3.4647 9.8686L10.505 2.8283A0.7 0.7 0 0 1 11.495 2.8283L13.1717 4.505A0.7 0.7 0 0 1 13.1717 5.495L6.1314 12.5353A0.7 0.7 0 0 1 5.8207 12.7156L3.5151 13.3444A0.7 0.7 0 0 1 2.6556 12.4849Z"/><pathd="M9.6667 3.6667L12.3333 6.3333"/></svg></button><span:id="`${id}-name`"hidden>{{ label }}</span><textareav-if="multiline"class="editable-field":aria-label="label":disabled="disabled"hiddenv-bind="field()":value.attr="first" /><inputv-elseclass="editable-field":aria-label="label":disabled="disabled"hiddenv-bind="field()":value.attr="first"></div></template>
/* * Editable: a value read as text that becomes a field in place. * The preview and the field stand in one grid cell with the same font, padding and corner, so the text does * not move by a pixel when one replaces the other: the preview stays in the layout while it is hidden and * holds the cell open. At rest the value is plain text, set out from the column by the padding it bleeds * into; under the pointer a faint well appears around it with a pencil at its end, and while editing the * well is a focused field. Its type is whatever it stands in: a heading, a cell, a line of a form. * The editable behavior switches the two and saves; without it the preview is a button that does nothing. */@layer components.ui {.editable{--editable-padding-x:.375em;--editable-padding-y:.125em;--editable-radius:var(--radius-control-sm);position:relative;display:inline-grid;grid-template:auto/minmax(0,auto);max-width:calc(100%+var(--editable-padding-x)*2);/* The text lines up with the column; the well reaches out around it. */margin-inline:calc(-1*var(--editable-padding-x));vertical-align:baseline;/* * While the value is on its way, the preview waits: it reads as pending and takes no press. The pointer * passes through it to the root, so the root is what shows the progress cursor. */&[aria-busy="true"]{cursor:progress;}&[aria-busy="true"].editable-preview{color:var(--color-text-muted);pointer-events:none;.editable-pencil{opacity:0;}}}/* What the preview and the field share, so that one sits exactly where the other was. */.editable-preview,.editable-field{grid-area:1/1;box-sizing:border-box;min-width:0;margin:0;padding:var(--editable-padding-y)var(--editable-padding-x);border:0;border-radius:calc(var(--editable-radius)*var(--corner-scale));corner-shape:var(--corner-shape);font:inherit;font-feature-settings:inherit;letter-spacing:inherit;text-align:start;text-transform:inherit;}.editable-preview{position:relative;display:block;background:transparent;color:inherit;white-space:pre-wrap;overflow-wrap: anywhere;appearance:none;cursor:text;-webkit-tap-highlight-color:transparent;transition-property: background-color, box-shadow;transition-duration:var(--duration-quick);transition-timing-function:var(--easing-glide);/* The pencil: it follows the last word, so it says what the press will do where the eye already is. */.editable-pencil{display:inline-block;width:.8125em;height:.8125em;margin-inline-start:.375em;color:var(--color-text-muted);vertical-align:-.0625em;opacity:0;transition: opacity var(--duration-quick)var(--easing-glide);}@media(hover:hover){&:hover:not(:disabled){background:var(--color-surface-inset);box-shadow:inset000.5pxvar(--color-line-contour);.editable-pencil{opacity:1;}}}/* Without a pointer that hovers, the pencil is always there: the only sign the text can be changed. */@media(hover:none){&:not(:disabled).editable-pencil{opacity:.7;}}&:focus-visible{@apply--focus-ring;outline-offset:0;.editable-pencil{opacity:1;}}&:active:not(:disabled){background:var(--color-surface-inset-hover);}&:disabled{cursor:default;}/* Hidden, it still holds the cell open, so the field takes its place and nothing below moves. */&[hidden]{display:block;visibility:hidden;}/* A touch target reaches 44px tall without moving the text. */@media(pointer:coarse){&::before{@apply--touch-target-block;}}@media(forced-colors:active){.editable-pencil{color: ButtonText;}/* Heavier than the focus ring, so it steps aside on a focused preview instead of thinning its ring. */@media(hover:hover){&:hover:not(:disabled,:focus-visible){outline:1pxsolid ButtonText;}}}}/* The field: a well risen to the sheet with one ink contour and a halo, as a focused input is. */.editable-field{display:block;width:100%;outline:none;background:var(--color-surface-raised);color:inherit;box-shadow:inset000.5pxvar(--color-line-mark),000.5pxvar(--color-line-mark),0003.5pxvar(--color-focus-halo);caret-color:var(--color-text-strong);resize:none;appearance:none;&::placeholder{color:var(--color-text-muted);opacity:1;}/* Where the field can size itself, it grows past the preview as the value does. */@supports(field-sizing:content){field-sizing:content;min-width:100%;}&:is([aria-invalid="true"],:user-invalid){box-shadow:inset000.5pxvar(--color-danger),000.5pxvar(--color-danger),0003.5pxcolor-mix(in oklab,var(--color-danger)15%,transparent);}&[hidden]{display:none;}@media(forced-colors:active){outline:2pxsolid Highlight;outline-offset:-2px;/* The danger edge is a shadow, which forced colors drop: the outline says it instead. */&:is([aria-invalid="true"],:user-invalid){outline-color: Mark;}}}/* What the preview says while the value is empty: the field's placeholder, in the muted ink. */.editable-placeholder{color:var(--color-text-muted);}}