인라인 편집은 제목, 이름, 표의 셀처럼 평소에는 텍스트로 읽히다가 그 자리에서 필드로 바뀌는 값입니다. 기본 상태에서는 감싸는 요소의 글꼴을 그대로 따르는 일반 텍스트이고, 포인터를 올리면 텍스트 주위에 옅은 오목한 영역과 끝에 연필 아이콘이 나타납니다. 누르면 이 영역이 값 전체를 선택한 상태의 포커스된 필드로 바뀝니다. 미리 보기와 필드는 그리드 셀 하나와 글꼴, 안쪽 여백, 모서리를 공유하므로, 둘이 서로 바뀌어도 텍스트는 1픽셀도 움직이지 않습니다. editable동작은 둘을 전환하고 값을 저장합니다.
값은 자신이 놓인 열에 맞춰 정렬됩니다. 루트 요소가 양쪽으로 --editable-padding-x만큼 바깥으로 확장되므로, 오목한 영역은 텍스트를 안쪽으로 밀어내지 않고 텍스트 주위로 넓어집니다. 안쪽 여백은 em 단위이므로 제목의 오목한 영역은 제목 크기에 맞게, 셀의 오목한 영역은 셀 크기에 맞게 넉넉한 여백을 갖습니다.
기본 상태에서 미리 보기는 일반 텍스트입니다. 버튼이므로 포커스를 받을 수 있으며, 포커스를 받으면 텍스트 뒤에 둔 editable-pencil 아이콘인 연필이 포커스 링과 함께 표시됩니다.
포인터를 올리면 텍스트 주위에 오목한 영역의 색조와 0.5픽셀 윤곽선이 나타나고, 마지막 단어 뒤에 연필 아이콘이 표시됩니다. 호버할 수 있는 포인터가 없는 화면에서는 연필 아이콘이 조금 더 옅은 모습으로 항상 표시됩니다. 텍스트를 바꿀 수 있다는 것을 알려 주는 표시가 이것뿐이기 때문입니다.
편집 중에는 포커스된 입력 필드와 마찬가지로 필드가 표면 높이까지 올라온 오목한 영역이 되며, 잉크 색 윤곽선 하나와 헤일로가 표시됩니다. 숨겨진 미리 보기도 셀의 공간을 계속 차지하므로 아래쪽 요소는 움직이지 않습니다. field-sizing: content를 지원하는 브라우저에서는 값이 길어지는 만큼 필드가 미리 보기보다 넓어지고, 그 밖의 브라우저에서는 미리 보기 너비 안에서 텍스트가 스크롤됩니다.
대기 중. 값을 전송하는 동안 루트 요소에 aria-busy="true"를 설정하세요. 미리 보기가 흐리게 표시되고 누를 수 없게 됩니다.
필드로 <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>
editable 동작은 editable 클래스가 있는 루트 요소를 받아, 연결한 동작을 해제하는 함수를 반환합니다.
app.js
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()가 있습니다. 값을 설정하면 미리 보기와 필드에 작성되며, 이때는 이벤트가 발생하지 않습니다.
그 이후 값을 어디로 보낼지는 페이지에서 정합니다. 값을 전송하는 동안 루트 요소에 aria-busy="true"를 설정하세요. 서버가 값을 거부하면 값을 원래대로 되돌리고 그 옆에 이유를 표시하거나, edit()를 호출한 뒤 필드에 aria-invalid="true"를 설정해 위험 색상 테두리를 표시하세요. 이렇게 하면 입력한 내용이 남아 있어 사용자가 고칠 수 있습니다.
동작을 연결하지 않으면 미리 보기는 아무 일도 하지 않는 버튼이 되며, 값은 그대로 읽을 수 있습니다.
값과 필드에 그 값이 무엇인지 나타내는 이름을 지정하세요. 예시에서는 보이는 레이블이 필드의 이름이 되고, 미리 보기는 aria-labelledby로 레이블과 자기 자신을 참조하여 레이블과 현재 값을 이름으로 사용합니다. 따라서 "제목, 분기 보고서, 버튼"처럼 읽힙니다.
스크립트 없이도 저장된 값을 읽을 수 있게 하세요. 저장된 값은 미리 보기의 텍스트입니다.
editable 컴포넌트는 첫 렌더링에 초기 값을 그리고 동작을 연결하며, 그 이후에는 동작이 미리 보기를 작성합니다. 컴포넌트가 외부로 전달하는 값은 저장된 값이며, 입력 중인 값은 전달하지 않습니다. npx master-ui add editable 명령을 실행해 프로젝트에 복사하세요. 컴포넌트의 구성과 사용 방법은 React, Svelte, Vue에서 확인할 수 있습니다.
ui/editable.tsx
'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);}}