窗口和终端中的组件
组件并不局限于页面。每个可以绘制它的位置都有自己的 render,而每个位置的内容会表明它属于哪一种。
render 包含的内容 |
绘制位置 |
|---|---|
返回的 html 块 |
页面 |
KScript.UI 元素,例如 Column、Text 和 Button |
窗口 |
echo 或 KScript.Terminal 元素 |
终端 |
KScript.Document 元素(例如 Section 和 Paragraph),或返回的 md 或 latex 块 |
一份文档 |
一个组件在每个位置最多只能有一个 render。字段、construct 块和方法由所有这些位置共享。
samples/components 只有一张包含全部四项的配方卡:一个页面、一个桌面窗口、终端和一份文档。
<import package="KScript.UI" />
<type name="NoteCard" extends="Component">
<construct>
<field name="title" type="string" />
<field name="body" type="string" default="''" />
</construct>
<field name="open" type="bool" />
<fn name="render">
<Box padding="8" border="#334155">
<Row gap="8">
<Text weight="bold">{.title}</Text>
<Button toggle="$open">{ .open ? 'Hide' : 'Show' }</Button>
</Row>
<if .open>
<Text wrap="yes">{.body}</Text>
<slot />
</if>
</Box>
</fn>
<fn name="render" surface="terminal">
<echo>* {.title}: {.body}</echo>
<slot />
</fn>
</type>import KScript.UI
type NoteCard extends Component {
construct({ title: string, body: string = '' })
open: bool
fn render() {
Box(padding: 8, border: '#334155') {
Row(gap: 8) {
Text(weight: bold) "{.title}"
Button(toggle: $open) "{ .open ? 'Hide' : 'Show' }"
}
if .open {
Text(wrap) "{.body}"
slot
}
}
}
fn render(terminal) {
echo "* {.title}: {.body}"
slot
}
}脚本通过将组件写成一条语句来绘制该组件,并把其输入作为参数传入。请先导入该组件的文件。
<KScript.Window title="Notes" width="420" height="320">
<import path="components/note-card.kscript" />
<let name="notes">[
{ title: 'Milk', body: 'Two pints' },
{ title: 'Eggs', body: 'Six, free range' },
]</let>
<for each="note" in="$notes">
<NoteCard title="{$note.title}" body="{$note.body}" id="{$note.title}">
<Text color="#94a3b8">From the shopping list</Text>
</NoteCard>
</for>
</KScript.Window>import KScript.UI
import "components/note-card.kscript"
Window(title: 'Notes', width: 420, height: 320) {
$notes = [
{ title: 'Milk', body: 'Two pints' },
{ title: 'Eggs', body: 'Six, free range' },
]
for note in $notes {
NoteCard(title: $note.title, body: $note.body, id: $note.title) {
Text(color: '#94a3b8') "From the shopping list"
}
}
}- 在
Window内部,该组件使用其窗口render进行绘制。若单独写在脚本中,则使用其终端render进行绘制。kscript check会报告某个组件被绘制在没有render的位置。 slot中的render会绘制调用方写在组件内部的内容。- 在窗口中,每个组件在两次绘制之间都会保留自己的状态,因此上面的
$open归属于某一张卡片。调用方传入的内容会在每次绘制时跟随调用方更新,而其他字段则保持组件留下的状态。 - 在循环中绘制的组件通过其 turn 加以区分。当列表顺序改变或删除项目时,传入
id:可使组件的状态与其项目保持关联。 - 不再绘制的组件会被销毁。如果再次绘制,它会从初始状态重新开始。
- 当
render仅包含其他组件(if、for或slot)时,其内容不会显示在绘制位置。请指定位置:fn render(window)、fn render(terminal)或fn render(document)。
在 XML 中,位置由 surface 属性指定,即 <fn name="render" surface="terminal">;组件则是以其类型命名的元素,即 <NoteCard title="Milk" />。
编辑器会在你输入语句的位置提供语句可以调用的组件,每个组件都已填好输入参数,并在括号内补全输入项。它只在对应的界面中提供该界面自身的元素:窗口的元素只在窗口中提供render,文档的元素只在文档中提供。在fn render(之后,它会提供window、terminal和document。
kscript make component NoteCard --for window 在窗口旁边的components/中写入一个带有fn render(window)的组件。--for document在documents/components/中写入一个组件,--for terminal在scripts/components/中写入一个。