[go: up one dir, main page]

이 페이지의 번역은 오류가 있을 수 있습니다. 영어 원문 보기

문서

레이아웃

NSH는 Taffy로 모든 요소의 레이아웃을 계산합니다. Taffy는 CSS flexbox, grid, block 레이아웃을 Rust로 구현한 라이브러리이며, 기본적으로 자식을 세로로 쌓고 축소하지 않도록 설정되어 있습니다. 레이아웃은 코드의 각 턴이 끝난 뒤 코어에서 실행되고, 변경된 프레임만 네이티브 뷰로 전달됩니다. 텍스트는 같은 스레드에서 플랫폼의 텍스트 엔진이 측정하므로, 레이아웃이 메인 스레드를 기다리지 않습니다.

guide-layout.tsx
guide-layout.tsxLive
import { mount, Scroll, signal, Text, View } from "nsh";
import { Toggle, ToggleGroup } from "nsh/base";
import { Inspector, Segmented, tint, toggleLabel, toggleLook, ui, wide } from "./palette";

type Direction = "column" | "row";
type Justify = "flex-start" | "center" | "flex-end" | "space-between" | "space-evenly";
type Align = "stretch" | "flex-start" | "center" | "flex-end";

/** A choice's toggles: small, each its value, on a field's edge while off. */
const chip = { size: "small", variant: "outline", text: true } as const;

/**
 * One of values too long for a segmented control's single row (five of
 * CSS's `justifyContent`): a toggle group that wraps, exactly one pressed.
 * Shorter choices are a `Segmented`.
 */
function Choice<T extends string>(props: { label: string; options: readonly T[]; value: T; onChange: (v: T) => void }) {
  return (
    <View style={{ gap: 6 }}>
      <Text style={{ fontSize: 12, color: ui().muted }}>{props.label}</Text>
      <ToggleGroup style={{ flexDirection: "row", flexWrap: "wrap", gap: 6 }}>
        <Each of={props.options}>
          {(o) => {
            const on = () => props.value === o();
            return (
              // Exactly one: the pressed value stays pressed.
              <Toggle pressed={on()} onChange={({ pressed }) => pressed && props.onChange(o())} {...toggleLook(chip)}>
                <Text style={toggleLabel(on, chip)}>{o()}</Text>
              </Toggle>
            );
          }}
        </Each>
      </ToggleGroup>
    </View>
  );
}

function App() {
  const direction = signal<Direction>("row");
  const justify = signal<Justify>("flex-start");
  const align = signal<Align>("stretch");
  const colors = () => [ui().down, ui().info, ui().up];

  const box = (height: number) => (
    <View
      style={{
        height,
        padding: 10,
        gap: 8,
        borderRadius: 12,
        ...ui().inset,
        flexDirection: direction(),
        justifyContent: justify(),
        alignItems: align(),
      }}
    >
      <Each of={colors()}>
        {(c, i) => (
          <View style={{ minWidth: 44, minHeight: 44, padding: 6, borderRadius: 8, backgroundColor: c() }}>
            <Text style={{ color: ui().page, fontWeight: "700" }}>{i() + 1}</Text>
          </View>
        )}
      </Each>
    </View>
  );
  const more = () => (
    <>
      <Text style={{ fontSize: 12, fontWeight: "600", color: ui().muted }}>flex: 1 / 2 / fixed, percentages, aspectRatio</Text>
      <View style={{ flexDirection: "row", gap: 8 }}>
        <View style={{ flex: 1, height: 36, borderRadius: 6, backgroundColor: tint(ui().info, 0.3) }} />
        <View style={{ flex: 2, height: 36, borderRadius: 6, backgroundColor: tint(ui().info, 0.6) }} />
        <View style={{ width: 36, height: 36, borderRadius: 6, backgroundColor: ui().info }} />
      </View>
      <View style={{ flexDirection: "row", gap: 8, alignItems: "flex-start" }}>
        <View style={{ width: "30%", aspectRatio: 1, borderRadius: 8, backgroundColor: tint(ui().warn, 0.35) }} />
        <View style={{ width: "40%", aspectRatio: 16 / 9, borderRadius: 8, backgroundColor: ui().warn }} />
      </View>

      <Text style={{ fontSize: 12, fontWeight: "600", color: ui().muted }}>grid</Text>
      <View style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
        <View style={{ gridColumn: "span 2", height: 40, borderRadius: 6, backgroundColor: tint(ui().violet, 0.3) }} />
        <View style={{ height: 40, borderRadius: 6, backgroundColor: tint(ui().violet, 0.6) }} />
        <View style={{ gridRow: "span 2", borderRadius: 6, backgroundColor: ui().violet }} />
        <View style={{ gridColumn: "1 / 4", height: 40, borderRadius: 6, backgroundColor: tint(ui().violet, 0.8) }} />
      </View>

      <Text style={{ fontSize: 12, fontWeight: "600", color: ui().muted }}>position: absolute</Text>
      <View style={{ ...ui().inset, height: 100, borderRadius: 12 }}>
        <View style={{ position: "absolute", top: 8, left: 8, width: 60, height: 40, borderRadius: 6, backgroundColor: ui().up }} />
        <View style={{ position: "absolute", right: 8, bottom: 8, width: "40%", height: 30, borderRadius: 6, backgroundColor: ui().down }} />
        <View style={{ position: "absolute", top: 0, bottom: 0, left: "50%", width: 2, backgroundColor: ui().border }} />
      </View>
    </>
  );
  const justifyChoice = () => (
    <Choice
      label="justifyContent"
      options={["flex-start", "center", "flex-end", "space-between", "space-evenly"] as const}
      value={justify()}
      onChange={(v) => justify.set(v)}
    />
  );
  const directionChoice = () => (
    <Segmented label="flexDirection" options={["row", "column"] as const} value={direction()} onChange={(v) => direction.set(v)} />
  );
  const alignChoice = () => (
    <Segmented label="alignItems" options={["stretch", "flex-start", "center", "flex-end"] as const} value={align()} onChange={(v) => align.set(v)} />
  );

  return (
    <>
      {() =>
        wide() ? (
          <View style={{ flex: 1, backgroundColor: ui().page, flexDirection: "row", padding: 20, paddingTop: 24, gap: 16 }}>
            <Scroll style={{ flex: 1, minWidth: 0 }}>
              <View style={{ gap: 14 }}>
                {box(260)}
                {more()}
              </View>
            </Scroll>
            <Inspector>
              {directionChoice()}
              {justifyChoice()}
              {alignChoice()}
            </Inspector>
          </View>
        ) : (
          <Scroll style={{ flex: 1, backgroundColor: ui().page }}>
            <View style={{ padding: 20, paddingTop: 24, gap: 14 }}>
              {directionChoice()}
              {justifyChoice()}
              {alignChoice()}
              {box(220)}
              {more()}
            </View>
          </Scroll>
        )
      }
    </>
  );
}

mount(App);

아래의 레이아웃 속성은 모두 스타일 속성입니다. Rust에서는 타입이 지정된 스타일 메서드(.flex_row(), .gap_4(), .grid_cols(3), .absolute().inset_0())로, TSX에서는 style prop의 키로 사용하며, 각 속성에는 Tailwind 클래스(flex-row, gap-4, grid-cols-3, absolute inset-0, …)가 있습니다. 둘 다 동일한 네이티브 스타일로 변환됩니다.

#Flexbox

뷰는 flexbox로 자식을 배치합니다. display 설정이 없는 뷰는 자식을 열(column)로 쌓습니다. 스타일에 display: "flex"가 있으면 flexDirection가 설정되지 않은 한 행(row)이 되며, 이는 CSS 및 Tailwind의 flex 클래스와 같습니다. 아무것도 설정하지 않은 경우 다음 기본값이 적용됩니다.

속성 NSH 기본값 웹 기본값
flexDirection "column" (display 설정이 없는 뷰); display: "flex" 설정 시 "row" row
flexShrink 0 1
alignContent "flex-start" (그리드: "normal") normal
alignItems "stretch" stretch
minWidth / minHeight 0 auto
position "relative" static
view()
    .flex_row()
    .items_center()
    .gap_3()
    .p_4()
    .child(image(avatar).size(px(40.0)).rounded(px(20.0)))
    .child(
        view()
            .flex_1()
            .gap_0p5()
            .child(text(name).font_weight(FontWeight::SEMIBOLD))
            .child(text(message).text_color(rgb(0x6e7781)).number_of_lines(1)),
    )
    .child(text(time).text_color(rgb(0x6e7781)))
속성 값 Rust
flexDirection "column", "row", "column-reverse", "row-reverse" .flex_col(), .flex_row(), .flex_col_reverse(), .flex_row_reverse()
justifyContent 주축: "flex-start", "flex-end", "start", "end", "center", "space-between", "space-around", "space-evenly", "stretch" .justify_start(), .justify_center(), .justify_end(), .justify_between(), .justify_around(), .justify_evenly()
alignItems 교차축: "stretch", "flex-start", "flex-end", "start", "end", "self-start", "self-end", "center", "baseline" .items_stretch(), .items_start(), .items_center(), .items_end(), .items_baseline()
alignSelf 자식 하나의 교차축 정렬; "auto" 값은 부모의 alignItems 설정을 따름 .self_start(), .self_center(), .self_end(), .self_stretch()
alignContent 줄바꿈 컨테이너의 줄 정렬
flexWrap "nowrap", "wrap", "wrap-reverse" .flex_wrap()
flex 단일 숫자 단축 표기(아래 참조) .flex_1(), .flex_auto(), .flex_none()
flexGrow, flexShrink, flexBasis CSS와 동일 .flex_grow(n), .flex_shrink(n), .flex_shrink_0(), .basis(length)
gap, rowGap, columnGap 자식 사이의 간격 .gap(length), .gap_y(length), .gap_x(length) 및 단계 메서드 .gap_2(), .gap_x_4(), …

다음 속성은 flex 방향을 따릅니다: flex-start, flex-end. 다음 속성은 CSS와 마찬가지로 쓰기 방향을 따릅니다: start, end (오른쪽에서 왼쪽 방향일 때 start는 오른쪽입니다). self-start / self-end는 자식 자신의 설정을 나타냅니다.

flex는 Tailwind의 flex-* 클래스와 마찬가지로 CSS의 단축 속성입니다. 숫자 n는 n만큼 늘어나고, 1만큼 줄어들며, 기준값 0에서 시작한다는 뜻이므로, flex: 1인 형제 요소들(Rust에서는 .flex_1(), flex-1)은 내용과 관계없이 공간을 균등하게 나눕니다. "none"은 0 0 auto(뷰가 자신의 크기를 유지함)과 같고, "auto"는 1 1 auto, "initial"는 0 1 auto와 같으며, grow, shrink, basis를 각각 풀어서 쓸 수도 있습니다("2 0 50%", "1 1 120px"). 최소 크기의 기본값이 0이므로 flex: 0(0 1 0)은 minWidth: "auto" 설정으로 내용 크기를 유지하지 않는 한 뷰를 0까지 줄입니다.

view()
    .flex_row()
    .gap_2()
    // One share.
    .child(view().flex_1().h(px(36.0)).bg(rgb(0xc8e1ff)))
    // Two shares.
    .child(view().flex_grow(2.0).flex_shrink(1.0).basis(px(0.0)).h(px(36.0)).bg(rgb(0x79b8ff)))
    // Fixed.
    .child(view().size(px(36.0)).bg(rgb(0x0366d6)))

최소 크기의 기본값이 0이므로, 행 안의 flex: 1 텍스트는 형제 요소를 밀어내는 대신 줄어들고 줄바꿈됩니다. minWidth: "auto" / minHeight: "auto"(min-w-auto / min-h-auto, Rust에서는 .min_w(auto()))는 CSS의 자동 최소값입니다. 즉, 줄어드는 아이템은 웹에서와 마찬가지로 내용의 최소 크기, 곧 텍스트에서 가장 긴 단어의 크기에서 멈춥니다.

#크기

속성 값 Rust
width, height 포인트, 부모에 대한 백분율("50%"), 또는 "auto" .w(px(120.0)), .h(relative(0.5)), .w_full(), .size(px(44.0)), 단계 .w_10(), …
minWidth, maxWidth, minHeight, maxHeight 포인트 또는 백분율; minWidth / minHeight은 콘텐츠의 최소 크기인 "auto"도 가능 .min_w(..), .max_w(..), .min_h(..), .max_h(..)
aspectRatio 너비를 높이로 나눈 값: 1, 16 / 9 .aspect_ratio(16.0 / 9.0), .aspect_square()
padding, paddingHorizontal, paddingVertical, paddingTop, … 포인트 또는 백분율 .p(..), .px(..), .py(..), .pt(..), … 및 단계 .p_4(), .px_2(), …
margin, marginHorizontal, marginVertical, marginTop, … 포인트, 백분율, 또는 "auto" .m(..), .mx(..), .my(..), .mt(..), …, .mx(auto())

Rust에서 길이는 타입으로 지정합니다: px(16.0)는 16포인트, relative(0.5)는 부모의 50%, auto()는 auto입니다. 단계 메서드는 단계당 4포인트인 Tailwind의 간격 스케일을 따릅니다(.p_4()는 16포인트, .gap_0p5()는 2포인트).

크기를 지정하지 않으면 뷰는 내용(및 패딩)만큼의 크기가 되며, 기본값 alignItems: "stretch"에 의해 부모의 교차축 방향으로 늘어납니다. 백분율은 부모의 크기를 기준으로 합니다(패딩과 마진은 CSS와 마찬가지로 부모의 너비를 기준으로 합니다).

aspectRatio는 알려진 한 차원으로부터 다른 차원의 크기를 정합니다.

view().w_full().aspect_ratio(16.0 / 9.0).bg(black())

앱 에셋의 이미지는 고유 크기를 가지며, 크기를 지정하지 않으면 그 크기로 배치됩니다(이미지와 에셋). 원격 이미지는 로드되기 전까지 크기가 없으므로 크기를 지정해야 합니다.

#그리드

display: "grid"(Rust에서는 .grid())은 자식을 CSS 그리드 트랙에 배치합니다.

view()
    .grid()
    .grid_template_columns("repeat(3, 1fr)")
    .gap_2()
    .child(view().col_span(2).h(px(60.0)).bg(rgb(0xd8b9ff)))
    .child(view().h(px(60.0)).bg(rgb(0xb083f0)))
    .child(view().row_span(2).bg(rgb(0x8250df)))
    .child(view().col_start(2).col_end(4).h(px(60.0)).bg(rgb(0x6639ba)))
속성 값 Rust
gridTemplateColumns, gridTemplateRows CSS 트랙 목록: "repeat(3, 1fr)", "200px 1fr", minmax(), auto-fill / auto-fit, 라인 이름 .grid_cols(3), .grid_rows(2), .grid_template_columns("200px 1fr"), .grid_template_rows(..)
gridAutoColumns, gridAutoRows 암시적으로 생성되는 열과 행의 트랙
gridAutoFlow "row", "column", "dense", "row dense", "column dense" .grid_flow_col(), .grid_flow_dense()
gridColumn, gridRow "1 / 3", "span 2", 라인 번호 또는 이름: "content-start / content-end", "2 col"(col 이름의 두 번째 라인), "span col"(col 이름의 다음 라인까지) .col_span(2), .row_span(2), .col_span_full()
gridColumnStart, gridColumnEnd, gridRowStart, gridRowEnd 라인 번호 또는 이름 .col_start(1), .col_end(3), .row_start(..), .row_end(..) (라인 번호)
justifyItems, justifySelf 행 방향으로 아이템이 영역 안에 놓이는 방식: "start", "end", "center", "stretch", …
alignItems, alignSelf 열 방향으로 아이템이 영역 안에 놓이는 방식 .items_*(), .self_*()
justifyContent, alignContent 행과 열 방향으로 트랙이 그리드 안에 놓이는 방식 .justify_*()

템플릿에서는 대괄호로 라인에 이름을 붙이며(라인마다 이름은 하나 또는 여러 개), 아이템은 CSS와 마찬가지로 그 이름으로 배치됩니다(Rust에서는 라인 번호로 배치).

view()
    .grid()
    .grid_template_columns("[full-start] 16px [content-start] 1fr [content-end] 16px [full-end]")
    // content-start / content-end: lines 2 to 3.
    .child(view().col_start(2).col_end(3).h(px(60.0)).bg(rgb(0xb083f0)))
    // full-start / full-end: lines 1 to 4.
    .child(view().col_start(1).col_end(4).h(px(60.0)).bg(rgb(0x8250df)))

그리드에서 justifyContent와 alignContent의 기본값은 CSS의 "normal"입니다. 크기가 auto인 트랙은 컨테이너를 채우도록 늘어나므로, 높이가 있고 행 템플릿이 없는 그리드는 그 높이를 행들에 나눠 줍니다. 명시적으로 설정한 값("start", "center", "space-between", …)은 CSS에서와 같이 트랙을 배치합니다. 정렬 클래스는 Tailwind CSS가 설정하는 값을 그대로 설정합니다. content-start(align-content: flex-start)과 place-content-start는 트랙을 시작점에 모으고, content-normal과 justify-normal는 브라우저에서와 마찬가지로 트랙을 늘립니다.

display: "block"은 CSS block 레이아웃을 사용하며(자식이 쌓이고 각각 컨테이너 너비만큼 넓어짐), display: "none"(.hidden())은 뷰를 레이아웃에서 제거합니다.

#절대 위치 지정

position: "absolute"(.absolute())은 뷰를 흐름에서 꺼내 top, right, bottom, left로 부모를 기준으로 배치합니다.

view()
    .h(px(200.0))
    .child(image(cover).absolute().inset_0())
    .child(
        view()
            .absolute()
            .left_3()
            .right_3()
            .bottom_3()
            .child(text("Caption").text_color(white()).font_weight(FontWeight::BOLD)),
    )

오프셋에는 포인트와 백분율을 사용할 수 있습니다(Rust에서는 .top(..), .right(..), .bottom(..), .left(..), .inset(..)). left와 right(또는 top과 bottom)가 있고 크기가 없는 뷰는 그 사이로 늘어납니다. 나중에 오는 형제 요소가 앞선 요소 위에 그려지며, zIndex(.z_index(n))으로 순서를 바꿀 수 있습니다.

#측정

onLayout(.on_layout(..))는 레이아웃이 바뀔 때마다 그 이후에 부모를 기준으로 한 뷰의 프레임을 알려 줍니다.

let width = signal(0.0_f32);

view()
    .on_layout(move |frame: &Bounds<Points>| width.set(frame.size.width.0))
    .child(text(move || format!("{} points wide", width.get())))

프레임의 단위는 포인트입니다: Rust에서는 Bounds<Points>, TSX에서는 { bounds }, 즉 Bounds({ origin: { x, y }, size: { width, height } })입니다. 창 전체의 크기는 Rust에서는 window()을, TSX에서는 nsh의 windowSize()를 읽으면 됩니다. 둘 다 회전과 창 크기 조절을 따르며, 이를 읽는 스타일은 창에 따라 변경됩니다.

view().style_when(|| window().width > px(600.0), |s| s.flex_row())

Tailwind의 브레이크포인트(sm:, md:, …)와 portrait: / landscape:를 사용하면 코드 없이 같은 결과를 얻을 수 있습니다.

#안전 영역

루트 뷰는 상태 표시줄과 홈 인디케이터 아래까지 화면 전체를 덮습니다. 화면에 안전 영역 인셋만큼 패딩을 주려면 CSS의 env()(paddingTop: "env(safe-area-inset-top)", Tailwind에서는 pt-[env(safe-area-inset-top)], Rust에서는 .p_safe_area(); Safe area 참조)을 사용하거나, Rust에서는 safe_area()로, TSX에서는 safeArea() / safeAreaInsets()로 인셋을 읽어 직접 적용하세요. navigation stack의 페이지는 이미 헤더 아래에 놓입니다.

#오른쪽에서 왼쪽(RTL)

앱의 레이아웃 방향은 시스템 언어를 따르며, 뷰의 direction 스타일("ltr", "rtl", "inherit"; Rust에서는 .direction(LayoutDirection::Rtl))은 그 하위 트리의 방향을 정합니다. 앱이 오른쪽에서 왼쪽으로 레이아웃될 때는 다음과 같습니다.

  • 행은 오른쪽에서부터 배치됩니다.
  • left과 right은 브라우저에서와 마찬가지로 각자의 쪽을 유지하며, 이는 스타일 키와 클래스 모두에 해당합니다: paddingLeft, marginLeft, left, borderLeftWidth, borderTopLeftRadius, textAlign: "left" 및 pl-4, ml-2, left-0, border-l, rounded-tl-lg, text-left는 왼쪽에 유지됩니다.
  • 논리 속성은 방향을 따르며, 인라인 시작은 오른쪽입니다: marginStart, marginEnd, paddingStart, paddingEnd, start, end, borderStartWidth, borderEndColor, borderTopStartRadius, …, textAlign: "start" / "end"(클래스로는 ps-4, ms-2, start-0, border-s, rounded-ss-lg, text-start; Rust에서는 .ms(..), .me(..), .ps(..), .pe(..), .border_s(..), .rounded_ss(..), …). marginHorizontal와 paddingHorizontal은 양쪽을 모두 설정합니다.
  • textAlign: "auto"이 지정된 텍스트는 오른쪽으로 정렬되고, 네이티브 컨트롤은 좌우가 반전됩니다.
view()
    .flex_row()
    .gap_2()
    .child(view().ms_4().rounded_ss(px(12.0)).size(px(44.0)).bg(rgb(0x54aeff)))

let rtl = signal(false);
view()
    .direction(move || if rtl.get() { LayoutDirection::Rtl } else { LayoutDirection::Ltr })
    .on_press(move |_: &()| rtl.set(!rtl.get()))
    .child(text(move || if rtl.get() { "Right to left" } else { "Left to right" }))

언어나 뷰의 방향이 바뀌면 재시작 없이 즉시 적용됩니다. direction 스타일을 사용하면 하나의 뷰와 그 자식을 독립된 방향으로 유지할 수도 있습니다. 예를 들어 전화번호를 왼쪽에서 오른쪽으로 표시할 수 있습니다. Android에서 NSH를 임베드하는 앱은 네이티브 컨트롤이 반전되도록 매니페스트에 android:supportsRtl="true"을 추가해야 합니다.