KScript 문서
KO

언어

영어에서 자동 번역되었습니다. 원문은 영어입니다.

컴포넌트

작업과 브라우저 이벤트

핸들러에는 KScript 문장을 넣을 수 있고, 가져온 함수를 호출할 수도 있습니다. 핸들러는 함수 또는 컴포넌트 메서드 중 하나일 수도 있으며, 이 경우 호출됩니다. 따라서 @on-click($save)는 fn save()를 실행합니다. bool 필드를 뒤집으려면 toggle: 축약형을 사용하세요. @on-click(toggle: $open)는 @on-click($open = not $open)와 같습니다. @on-click($open)처럼 단독으로 쓴 bool은 오류이며, toggle:로 고치는 빠른 수정이 제공됩니다.

핸들러 축약형

핸들러는 문장 전체를 쓰는 대신 동작의 이름을 쓸 수 있습니다. 각 축약형은 선택 사항이며, 문장 형식도 계속 동작합니다. @on-click(add: $draft, to: $tags, set: $draft, to: '')처럼 여러 축약형을 한 핸들러에서 왼쪽에서 오른쪽으로 실행할 수 있습니다. 핸들러에는 축약형이나 문장 중 하나만 올 수 있으며, 둘을 함께 쓸 수는 없습니다.

축약형 같은 의미 필드
toggle: $open open = not $open bool
call: $save 컴포넌트의 fn save(), 또는 변수에 담긴 함수 fn 또는 method
call: $save, with: [$note.id] $this->save($note.id) fn 또는 method
increment: $count count = $count + 1 number
increment: $count, by: 5 count = $count + 5 number
decrement: $count, by: count = $count - 1 number
set: $tab, to: 'notes' tab = 'notes' any
add: $draft, to: $tags tags = $tags->push($draft) list
remove: $tag, from: $tags tags = $tags->remove($tag) list
reset: $draft, reset: [$title, $done] 각 필드를 시작 값(기본값, 또는 <state> 값)으로 되돌립니다 any
cycle: $view, through: ['list', 'grid'] 목록의 다음 값으로 넘어가며, 끝에서는 처음으로 돌아갑니다(through:이 없으면 필드 enum의 다음 값) any
save: $note $note->save() KScript.Data 레코드
delete: $note $note->delete() KScript.Data 레코드
emit: 'notes-changed' @emit_event('notes-changed') none
go: '/notes' @live_redirect('/notes') none

수정자는 동작과 함께 쓰이며, 동작이 언제 또는 어떻게 실행될지를 바꿉니다. 브라우저는 무엇인가를 보내기 전에 수정자를 적용합니다.

수정자 기능
confirm: 'Remove this note?' 사용자에게 먼저 묻고, 사용자가 동의한 경우에만 실행합니다.
key: enter, key: [ctrl, s] 해당 키가, 정확히 그 수정자 키(ctrl, alt, shift, meta)와 함께 눌렸을 때만 실행합니다. 키는 enter, escape, space, tab, up, down, left, right, 문자 또는 숫자입니다.
prevent: true 브라우저의 기본 동작(예: ctrl+s의 페이지 저장)을 막습니다.
debounce: 300ms 이벤트가 그 시간 동안 멈출 때까지 기다렸다가 한 번 실행합니다.
throttle: 1s 그 시간 안에서 최대 한 번만 실행합니다.
once: true 처음 한 번만 실행합니다.
self: true 이벤트가 요소 자체에서 시작된 경우에만 실행하며, 그 안의 하위 요소에서 시작되면 실행하지 않습니다.
disable: true 동작이 실행되는 동안 요소를 비활성화합니다.
HTML 페이지
<input @bind($query, debounce: 300ms) @on-keydown(reset: $query, key: escape)>
<button @on-click(delete: $note, confirm: 'Delete this note?', emit: 'notes-changed')>Delete</button>
<form @on-keydown(save: $note, key: [ctrl, s], prevent: true)>…</form>

윈도우에서는 동작을 버튼이나 상자에 바로 연결합니다. 예를 들어 Button(toggle: $open) "Details"과 Button(increment: $count, by: 5) "+5"입니다. 수정자는 브라우저가 있어야 동작하므로, 수정자가 있는 윈도우 핸들러는 그 사실을 알리는 오류와 함께 중단됩니다.

decrement:은 min:보다 작은 값을 필드에 주지 않습니다. stock: int(min: 0)와 함께 쓰면 decrement: $stock, by: 2가 1일 때 값은 0으로 남습니다.

kscript check과 편집기는 각 필드의 타입을 확인하고, 이름(그리고 해당 동작 뒤의 by:, to:, from: 또는 with:)을 완성해 주며, 마우스를 올리면 축약형이 나타내는 문장을 보여 줍니다. 동작 이름 뒤에서 자동 완성은 그 동작에 맞는 필드만 보여 줍니다. toggle:은 bool 필드를, increment:은 숫자 필드를, to: 뒤의 add:에서는 목록 필드를 보여 줍니다.

클래스 전환

@class(...)은 조건이 참인 동안 태그 자체의 class에 클래스를 추가합니다. 조건마다 클래스 하나를 쓰려면 클래스를 먼저 쓰고, 여러 클래스를 한꺼번에 전환하려면 조건을 먼저 쓰세요:

HTML 페이지
<li class="item" @class(done: $todo.done, 'is-late': $todo.due < @today())>{$todo.title}</li>
<li @class({
  $todo.done: ['done', 'struck'],
  [$todo.done, $open]: 'expanded',
  $todo.done or $open: 'highlight',
})>{$todo.title}</li>

조건은 bool이거나, 모두 참이어야 하는 bool 목록입니다. 조건을 먼저 쓰면 값은 클래스 이름 또는 그 목록이 됩니다. 브라우저 세부 정보는 $event로 확인할 수 있습니다. 키 이벤트에는 키, 코드, 수정자가 포함됩니다. 포인터 이벤트에는 좌표, 버튼, 포인터 ID, 해당하는 경우 포인터 타입이 포함됩니다. $event.x와 $event.y는 핸들러 자체 요소 안에서 포인터가 있는 위치이며, 그 요소가 스크롤된 만큼을 반영합니다. 따라서 스크롤되는 보드에서 @on-dblclick(call: $add, with: [$event.x, $event.y])는 보드 내용 안의 위치를 줍니다.

상호작용 속성
버튼과 폼 on-click, on-dblclick, on-submit
입력 변경 on-input, on-change
키보드와 포커스 on-keydown, on-keyup, on-enter, on-escape, on-focusin, on-focusout
대화상자 및 포인터 이벤트 on-cancel, on-close, on-pointerdown, on-pointerup, on-pointercancel
수명 주기 on-init, on-visible, on-tick과 every="1s"
다른 컴포넌트와 클라이언트 코드 on-event 및 이름이 지정된 on-action

Use prevent: true in a handler to cancel a browser default synchronously, and confirm: 'Remove this note?' to confirm a destructive action before posting it. @show($open) keeps a tag in the page and hides it while the value is false, so focus and scroll survive, and @live-disable(while: $saving) disables a control while a condition holds as well as while an action runs. An action can call @live_redirect('/notes') for a same-site redirect or @skip_render() to save state without updating the current HTML.

컴포넌트 간 이벤트

동작에서 @emit_event('notes-changed', data: $note.id, target: 'summary')로 이벤트를 발생시킵니다. 대상을 생략하면 모두에게 전달합니다. 각 수신 블록은 일치하는 첫 번째 리스너, 예를 들어 on-event="$latest = $event.data" event-name="notes-changed"를 실행합니다. 핸들러는 $event.name, $event.data, $event.source를 읽을 수 있습니다.

드래그, 드롭 및 정렬

To drag one element onto another, put @drag(copy: true, value: $item.id) on the source and on-drop on the destination (see the next section). The action reads $event.drag_value, and $event.x and $event.y give the drop point inside the destination. @drop-class('over') on the destination adds the class while something it takes is dragged over it.

@drag로 요소 이동하기

@drag()을 쓰면 방문자가 포인터로 절대 위치 요소를 옮길 수 있습니다. 드래그가 끝나면 요소의 on-dragend 핸들러가 놓인 위치와 함께 실행되므로, 동작에서 그 위치를 저장할 수 있습니다:

HTML 페이지
<article class="note" style="left: {$note.x}px; top: {$note.y}px; z-index: {$note.z}"
  @drag(front: true, skip: '.thumb')
  @on-dragend(call: $move, with: [$event.x, $event.y, $event.z, $event.vx])>
  …
</article>
$event 필드 값
x, y 위치 기준 부모 안에서 픽셀 단위로 표시되는 요소의 새 left과 top입니다.
vx, vy 놓을 때의 이동 속도이며, 프레임당 픽셀 단위입니다.
moved 누르기가 클릭이었을 때 false이 참입니다. 핸들러는 여전히 실행되므로, 클릭으로 요소를 맨 앞으로 가져올 수 있습니다.
z With front: true, the z-index it was raised to above its siblings.
옵션 기능
front: true 위치 기준 부모 안의 다른 @drag 요소보다 요소를 위로 올립니다.
scroll: '.surface' 포인터가 가장자리 근처에 올 때 스크롤되는 컨테이너입니다. 기본값은 가장 가까운 스크롤 가능 조상입니다.
skip: '.thumb' 이 요소들에 대한 누르기는 드래그가 아니라 각 요소의 것으로 처리됩니다. 필드, 버튼, 링크, 레이블은 항상 건너뜁니다.
threshold: 6 누르기가 드래그로 바뀌기 전까지 포인터가 이동해야 하는 거리입니다. 기본값은 4픽셀이므로, 클릭은 클릭으로 남습니다.
copy: true 요소 대신 고스트 복사본을 드래그하여 on-drop 대상으로 옮깁니다. 일반 클릭은 여전히 요소의 on-click를 실행합니다.
value: $color With copy:, what the drop handler reads as $event.drag_value.
ghost: 'note-ghost' With copy:, the classes of the ghost. Its top centre follows the pointer. Defaults to the element's own classes.

움직이는 동안 요소(또는 고스트)에는 dragging 클래스와 CSS 변수 --drag-vx, --drag-vy, --drag-speed가 붙어서, 스타일시트에서 움직임에 맞춰 기울일 수 있어요. 드롭한 뒤에는 애니메이션이 끝날 때까지 drag-settled 클래스가 붙어 있어요.

CSS
.note.dragging {
  --tilt-y: clamp(-28deg, calc(var(--drag-vx) * 1.6deg), 28deg);
  transform: perspective(900px) rotateY(var(--tilt-y));
}
.note.drag-settled { animation: settle 0.5s ease-out; }

A tray item that drops a new note on a board uses copy::

HTML 페이지
<button type="button" class="pad" @drag(copy: true, value: $color, ghost: "note-ghost c-$color") @on-click($this->add($color))></button>
<div class="surface" @on-drop(call: $add, with: [$event.drag_value, $event.x, $event.y]) @drop-class('over')>…</div>

요소에 드롭된 파일을 받으려면 @drop-files('upload')을 주고, 그 안에 이름이 upload인 live-upload 파일 입력을 넣으세요. 드롭된 파일은 이 입력과 그 on-change 액션을 거치며, 직접 고른 파일과 똑같이 처리돼요:

HTML 페이지
<article class="note" @drop-files('upload') @drop-class('file-over')>
  <label>Attach <input type="file" name="upload" multiple hidden live-upload @on-change($this->attach($event.files.upload))></label>
</article>

kscript check은 요소 안에 일치하는 live-upload 입력이 없는 @drop-files 이름을 알려줘요.

정렬 가능한 형제 요소들에는 각 항목마다 고유한 sort-item="{$item.id}"을 주고, 그 컨테이너에 on-sort를 설정하세요. 핸들러는 항목 ID, 이전과 새 0부터 시작하는 인덱스, 제안된 순서를 받아요. 사용자는 항목을 드래그하거나 포커스를 준 뒤 Alt+Up 또는 Alt+Down을 누를 수 있어요. 왼쪽에서 오른쪽으로 배열되는 목록에는 sort-axis="horizontal"을 설정하세요. 새 순서를 저장하기 전에 항목 ID를 검증하세요.

Edit this page on GitHub