bezel README

README проекта с github.com/crabtalk/bezel. Одним файлом markdown: README.md.

bezel

crates.io license gpui discord

[!NOTE] Bezel is developing fast, with frequent releases and version bumps. APIs are still evolving, so expect changes as the library takes shape.

A gpui component library, SwiftUI-lean: style flows through the environment, never through parameters.

https://github.com/user-attachments/assets/34861f29-004f-47f0-89e6-42cc8772749f

use bezel::ui::widgets::{ButtonStyle, Buttons};
theme.button("Save", ButtonStyle::Prominent, None)

Built with Bezel

Cydonia is a desktop workspace for working with coding agents in a project directory. It's a real app built with Bezel — explore it to see the library in use beyond the component gallery.

Install

[dependencies]
bezel = "0.2"

An app also names the two crates the facade cannot cover — gpui because actions! expands to literal gpui:: paths, and gpui_platform because the facade re-exports gpui but not the platform. Both are our fork of gpui, published under bezel-gpui*; the package key keeps the gpui:: paths the macros and gpui's own docs expect:

gpui = { package = "bezel-gpui", version = "0.3" }
gpui_platform = { package = "bezel-gpui-platform", version = "0.3", features = ["font-kit"] }

Building on Windows needs the MSVC toolchain, and on Linux the fontconfig and wayland/x11 headers — see CONTRIBUTING.

Theme

Most apps want the shipped palette in their own hues. That is a Brand — one hue for the greys, one for the accent, one base radius:

use bezel::theme::AppExt as _;
use bezel::theme::{Brand, Tint};

// before ui::init
cx.set_brand(Brand {
        tint: Tint::new(257.417, 0.046),
        accent: Tint::new(276.935, 0.182),
        radius: 8.0,
    });

Lightness is not a knob, so a branded palette keeps the contrast ratios the shipped one was verified at. The gallery's Theme page is this struct with sliders on it, and prints the call back.

For colors a hue rotation cannot reach, register a palette builder instead — it runs first, and a brand rotates whatever it returns:

use bezel::theme::AppExt as _;
use bezel::theme::Theme;

cx.set_palette(|appearance| {
    let mut theme = Theme::for_appearance(appearance);
    theme.danger = my_red(appearance);
    theme
});

Build an app

apps/hello is the smallest consumer — one window, a button, a toggle. Every gpui type path goes through bezel::gpui, so a second gpui cannot creep into the graph. The bootstrap, which is the part no snippet can skip:

use bezel::gpui::{App, AppContext as _, Bounds, WindowBounds, WindowOptions, px, size};
use bezel::theme::{self, Theme};
use bezel::ui;

fn main() {
    gpui_platform::application()
        .run(|cx: &mut App| {
            // Fonts, the appearance, and every component's keys.
            if let Err(err) = ui::init(theme::appearance::AppearanceMode::System, cx) {
                eprintln!("FONT REGISTRATION FAILED: {err:?}");
            }
            let bounds = Bounds::centered(None, size(px(520.0), px(360.0)), cx);
            cx.open_window(
                WindowOptions {
                    window_bounds: Some(WindowBounds::Windowed(bounds)),
                    ..Theme::of(cx).window_options()
                },
                |window, cx| {
                    theme::appearance::observe_window(window, cx).detach();
                    cx.new(Hello::new)
                },
            )
            .unwrap();
            cx.activate(true);
        });
}

Hello is a struct implementing Render; its render reads the theme with Theme::of(cx) and builds elements through the widgets traits. Run cargo run -p hello and read apps/hello/src/main.rs for the rest.

On iOS, tools/ios/run.sh hello --launch builds the same app for the simulator (rustup target add aarch64-apple-ios-sim first), bundles it, and launches it in a simulator without opening Simulator.app. --device builds for a phone, signed with $IOS_SIGN_IDENTITY. Any app in apps/ builds the same way.

apps/phone puts bezel's iOS behaviours on one screen, and its simulator suite drives them with real touches through idb (idb_companion and fb-idb):

cargo test -p phone --test simulator -- --ignored --test-threads 1

Agents

The doc pages ship in the bezel crate under docs/, at the version a project builds against. Online, every page is served as markdown — append .md to any docs URL, or take the whole corpus from llms.txt and llms-full.txt.

skills/ holds two agent skills, plain SKILL.md files any agent that reads the format can load. skills/bezel teaches an agent to use the library — the bootstrap, the laws, and the traps that only bite at runtime. skills/bezel-contributing is for working on it.

Provenance

What From License
Initial components comet MIT
Thinking orbs gpui-thinking-orbs MIT
Blob avatars blobatar MIT
Syntax highlighting tree-sitter core and grammars MIT
Wasm grammar fixtures tree-sitter-json, tree-sitter-css MIT
TypeScript/TSX queries nvim-treesitter Apache-2.0
Icons Lucide, ported from a release ISC
Fonts Geist and Geist Mono © Vercel Inc. SIL OFL 1.1

bezel (crabtalk/bezel)

Ищем в базе…

Что это такое?Bezel — это библиотека компонентов для GPUI, UI-фреймворка на Rust. В ней набор нативных десктопных виджетов в духе SwiftUI (только самое нужное), а стили задаются через окружение, а не через параметры виджетов.
А что значит «в духе SwiftUI» на практике?Стилизация живёт в окружении, а не в параметрах виджетов, и все числа не выдуманы, а измерены: типографическая шкала взята из NSFont.preferredFont(forTextStyle:), а отступ между соседними элементами — из NSStackView().spacing.
Как запустить своё первое приложение?Выполните cargo run -p hello — apps/hello это самый маленький потребитель: одно окно с кнопкой и переключателем. Его render читает тему через Theme::of(cx) и собирает элементы с помощью трейтов widgets.
Нужно ли подключать какие-то крейты, кроме самого bezel?Да — кроме крейта-фасада, в приложении также указываются gpui и gpuiplatform, собственный форк gpui от авторов bezel, опубликованный под именем bezel-gpui. Благодаря этому пути вида gpui:: в макросах и документации продолжают работать как есть.
Насколько сильно я могу переработать тему под своё приложение?Brand задаёт один оттенок для серых цветов, один акцентный цвет и базовый радиус скругления. Яркость настроить нельзя — так фирменная палитра сохраняет те соотношения контрастности, при которых была проверена стандартная.
Это для десктопных приложений, мобильных или веба?Только десктоп: bezel нацелен на GPUI, нативный UI-фреймворк на Rust, а в репозитории в качестве платформ указаны macOS, Linux и Windows.
Есть ли визуальный способ поиграться с темами?Да — в репозиторий входит приложение-галерея, где страница Theme — это структура Brand с ползунками. Она печатает готовый вызов, который можно вставить в своё приложение. Если нужный цвет не получается получить поворотом оттенка, вместо этого регистрируется свой конструктор палитры.
Смогут ли с bezel работать ИИ-агенты для кодинга?Да — каждая страница документации отдаётся в виде markdown: допишите .md к любому адресу документации или заберите весь корпус целиком из llms.txt и llms-full.txt. В skills/ также лежат два скилла в формате SKILL.md: bezel для использования библиотеки и bezel-contributing для работы над ней.
Откуда взялись компоненты и ассеты?Таблица происхождения указывает источники: первые компоненты взяты из comet, плюс «орбы-загрузки», blob-аватары, подсветка синтаксиса на tree-sitter, иконки Lucide и шрифты Geist — почти всё под MIT, с отдельными исключениями Apache-2.0, ISC и SIL OFL.
Какие есть похожие проекты?gpui-kit, Ely-GPUI-Components, tabler, react-native-ui-kitten, Raven, ui-ux-pro-max-skill, mantine, ChunUI
Автор
crabtalk
Размер
7.2 MB
Звёзды
204
Возраст
3 мес
Коммиты · 90 дней