TimecodePanel: rows are TimecodeReadouts, each opening its own context menu

Each row is a read-only readout: the time in mono with tabular figures, centred, the first row in the accent ink, the
caption centred under it in muted caption type, with no hover, press or selection look. A readout is one Tab stop
and a click focuses it; a secondary click, the Menu key or Shift+F10 opens that row's menu through Menu::context.
The selecting List of ListRows and its selection memory go.
This commit is contained in:
aiongg
2026-11-12 14:32:42 +00:00
parent b8b46132b5
commit e67bb44406
3 changed files with 205 additions and 63 deletions
+21 -60
View File
@@ -1,23 +1,22 @@
//! The timecode field, its codec and the Timecode panel.
mod readout;
#[cfg(feature = "screen-testing")]
mod stories;
use craft_behavior::nav::LARGE_STEPS;
use craft_behavior::{Caret, Codec, DisplayOrder, IconId, ItemSource, NavMove, NotAValue, PartKey, Selection, Sense, ValueDrag};
use craft_behavior::{Caret, Codec, IconId, NavMove, NotAValue, PartKey, Sense, ValueDrag};
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Held, Input, MeasureCx, NoValue, Outcome, PartsCx, Props, Role, Scrub,
SelectMode, Show as _, ShowCollection as _, ShowContainer as _, clicked,
Show as _, ShowContainer as _, clicked,
};
use craft_ui::display::Divider;
use craft_ui::layout_components::Stack;
use craft_ui::list::{List, ListRow};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::primitives::{TextKey, TextOptions, TextRun};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::focus::KeyUse;
use craft_ui::runtime::memory::Remember as _;
use craft_ui::style::{Ink, StyleCx, TypeRole};
use craft_ui::text::FieldStyle;
use egui::{Rect, Response, Ui, Vec2};
@@ -26,6 +25,7 @@ use std::ops::Deref;
use crate::time::Tick;
use crate::timecode::{TimeDisplay, TimeFormat, TimecodeError, format_time, parse_time};
use readout::TimecodeReadout;
/// Frames the Up and Down keys step a field.
const STEP_FRAMES: i64 = 1;
@@ -430,33 +430,6 @@ struct RowText {
spoken: String,
}
/// The rows as a collection source, keyed by position.
struct Rows<'a> {
texts: &'a [RowText],
}
impl DisplayOrder<usize> for Rows<'_> {
fn len(&self) -> usize {
self.texts.len()
}
fn key(&self, at: usize) -> usize {
at
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
Some(Cow::Borrowed(self.texts[at].value.as_str()))
}
}
impl ItemSource<usize> for Rows<'_> {}
/// The panel's session state: the row the menu acts on.
#[derive(Clone, Debug, Default)]
struct PanelMemory {
selection: Selection<usize>,
}
/// A row's menu: its kind, its monitor, its display, and Remove Row while another row is left.
fn row_menu(ui: &mut Ui, words: &TimecodeWords, row: &TimecodeRow, removable: bool) -> Option<RowCommand> {
let mut ran = None;
@@ -490,10 +463,10 @@ fn row_menu(ui: &mut Ui, words: &TimecodeWords, row: &TimecodeRow, removable: bo
ran
}
/// Premiere's Timecode panel: each row's text with its caption ("Current Time \u{b7} Program"), the first row
/// emphasised. The app gives each row's text. A secondary click, the Menu key or Shift+F10 on a row opens its menu
/// (kind, source, display with "Sequence Display" to follow the sequence again, Remove Row); "+" adds a row. The rows
/// are one list: one Tab stop, the arrows move.
/// Premiere's Timecode panel: each row's time centred over its caption ("Current Time \u{b7} Program"), the first row
/// in the accent ink. The app gives each row's text. Rows are read-only readouts, each one Tab stop; a secondary click,
/// the Menu key or Shift+F10 on a row opens its menu (kind, source, display with "Sequence Display" to follow the
/// sequence again, Remove Row); "+" adds a row.
#[derive(craft_ui::contract::Pattern)]
pub struct TimecodePanel<'a> {
label: Label,
@@ -527,32 +500,20 @@ impl<'a> TimecodePanel<'a> {
RowText { value, caption, spoken }
})
.collect();
let mut selection = root.keep::<PanelMemory>().selection.clone();
let source = Rows { texts: &texts };
let out = List::<usize>::new(label.clone()).select(SelectMode::Single).selection(Bind::bound(&mut selection)).show_items(
ui,
&source,
&mut |key, _| {
let row = &texts[*key];
ListRow::new(row.value.clone()).detail(row.caption.clone()).strong(*key == 0).accessible_name(row.spoken.clone())
},
);
let target = selection.lead.or_else(|| selection.items.first().copied());
root.keep::<PanelMemory>().selection = selection;
let removable = before.rows.len() > 1;
let ran = Menu::context(words.menu.clone(), &out.response)
.show(ui, |ui, _| target.and_then(|at| before.rows.get(at)).and_then(|row| row_menu(ui, &words, row, removable)))
.inner
.flatten();
if let (Some(command), Some(at)) = (ran, target)
&& let Some(row) = next.rows.get_mut(at)
{
match command {
RowCommand::Kind(kind) => row.kind = kind,
RowCommand::Source(source) => row.source = source,
RowCommand::Display(display) => row.display = display,
RowCommand::Remove => {
next.rows.remove(at);
for (at, (row, shown)) in before.rows.iter().zip(&texts).enumerate() {
let readout = TimecodeReadout::new(shown.spoken.clone(), &shown.value, &shown.caption).accent(at == 0).show(ui);
let ran = Menu::context(words.menu.clone(), &readout).show(ui, |ui, _| row_menu(ui, &words, row, removable)).inner.flatten();
if let Some(command) = ran
&& let Some(row) = next.rows.get_mut(at)
{
match command {
RowCommand::Kind(kind) => row.kind = kind,
RowCommand::Source(source) => row.source = source,
RowCommand::Display(display) => row.display = display,
RowCommand::Remove => {
next.rows.remove(at);
}
}
}
}
+121
View File
@@ -0,0 +1,121 @@
//! `TimecodeReadout`: one row of the Timecode panel, a time over its caption.
use craft_behavior::{Axis, Sense};
use craft_theme::{Stateful, States};
use craft_ui::contract::{Common, Component, Cx, Input, MeasureCx, PaintUi, Props as _, Role, Styled as _};
use craft_ui::primitives::{Span, TextRun};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::focus::{ActivateKeys, KeyUse};
use craft_ui::style::{ComponentStyle, FocusLook, Metrics, StyleColor, StyleCx, TextLook, TypeRole};
use egui::{Pos2, Response, Vec2};
/// The look of a readout: the time in the timecode type, the caption under it.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub(crate) struct TimecodeReadoutStyle {
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The time: mono with tabular figures, in the accent ink on the panel's first row.
#[style(text)]
value: TextLook,
/// The caption: muted caption type.
#[style(text)]
caption: TextLook,
/// Between the time and the caption.
gap: f32,
}
/// A time centred over its caption ("Current Time \u{b7} Program"), read-only: no hover, press or selection look. It is
/// one Tab stop and a click focuses it, so the panel's context menu opens from it by a secondary click, the Menu key or
/// Shift+F10. AccessKit: a label named by the spoken text (the caption and the time).
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(sample = TimecodeReadout::sample)]
pub(crate) struct TimecodeReadout<'a> {
#[common]
common: Common,
value: &'a str,
caption: &'a str,
/// The panel's first row: the time in the accent ink.
#[style_key]
#[prop]
accent: bool,
}
impl<'a> TimecodeReadout<'a> {
/// `value` over `caption`, named `spoken` for a screen reader.
pub(crate) fn new(spoken: impl Into<Label>, value: &'a str, caption: &'a str) -> Self {
TimecodeReadout { common: Common::new(), value, caption, accent: false }.label(spoken)
}
fn value_run(&self, role: TypeRole) -> TextRun<'a> {
TextRun::spans(vec![Span::new(self.value).tabular()]).role(role)
}
fn caption_run(&self, role: TypeRole) -> TextRun<'a> {
TextRun::new(self.caption).role(role)
}
}
impl TimecodeReadout<'static> {
/// The first row of a panel, for the suite.
#[cfg(feature = "screen-testing")]
fn sample() -> Self {
TimecodeReadout::new("Current Time \u{b7} Program: 00:01:02:03", "00:01:02:03", "Current Time \u{b7} Program").accent(true)
}
}
impl Component for TimecodeReadout<'_> {
const ROLE: Role = Role::LABEL;
const PARTS: bool = false;
/// A focusable click target whose click does nothing: Space and Enter do not activate it.
const INPUT: Input = Input::Pointer;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_activate(ActivateKeys::Neither);
const OVERLAYS: bool = false;
type Style = TimecodeReadoutStyle;
type Output = Response;
fn style(cx: &StyleCx<'_>, key: TimecodeReadoutStyleKey) -> TimecodeReadoutStyle {
let colors = &cx.tokens.color;
let ink = |color: StyleColor| Stateful::new(color).off(States::new(color, color, color, cx.color(colors.text.disabled)));
let value = cx.color(if key.accent { colors.accent.text } else { colors.text.normal });
TimecodeReadoutStyle {
metrics: Metrics::new(),
focus: cx.focus_look(),
value: TextLook::new(TypeRole::Mono, ink(value)),
caption: TextLook::new(TypeRole::Caption, ink(cx.color(colors.text.muted))),
gap: cx.tokens.space.gap.stack,
}
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::CONTEXT_CLICK | Sense::FOCUS | Sense::TAKE_FOCUS
}
/// The readout spans its room, so the time and the caption centre in the panel.
fn fills(&self) -> Option<Axis> {
Some(Axis::X)
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let value = cx.layout(&self.value_run(cx.style.value.role)).size();
let caption = cx.layout(&self.caption_run(cx.style.caption.role)).size();
Vec2::new(value.x.max(caption.x), value.y + cx.style.gap + caption.y)
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let rect = cx.content_rect;
let draw = ui.draw();
let centred = |top: f32, size: Vec2| Pos2::new(rect.left() + (rect.width() - size.x).max(0.0) / 2.0, top);
let value = draw.layout(&self.value_run(cx.style.value.role).color(cx.resolve(&cx.style.value.color)), rect.width());
let caption = draw.layout(&self.caption_run(cx.style.caption.role).color(cx.resolve(&cx.style.caption.color)), rect.width());
let below = rect.top() + value.size().y + cx.style.gap;
draw.galley(centred(rect.top(), value.size()), &value);
draw.galley(centred(below, caption.size()), &caption);
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
+63 -3
View File
@@ -1,10 +1,10 @@
//! The timecode field: a drag scrubs a field that is not in edit, and the arrows on the selected text start from its
//! end.
//! end. The Timecode panel: each row's menu opens from that row and acts on it.
use craft_timeline::ui::TimecodeField;
use craft_timeline::ui::{TimecodeField, TimecodePanel, TimecodePanelSettings, TimecodeRow, TimecodeRowKind, TimecodeSource, TimecodeText};
use craft_timeline::{FrameRate, Tick, TimeFormat};
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial};
use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, pointer, trial};
use egui::{Key, Modifiers, Ui, Vec2};
/// One and a half seconds: "00:00:01:15" at 30 frames per second.
@@ -48,3 +48,63 @@ fn left_on_the_selected_timecode_starts_from_its_last_digit() {
let edited = time(&mut fixture);
assert!(edited != start() && edited > Tick::from_seconds_f64(1.0), "Backspace took a digit of the frames, not nothing at the start");
}
fn rows() -> TimecodePanelSettings {
TimecodePanelSettings::new(
[TimecodeRowKind::CurrentTime, TimecodeRowKind::Duration, TimecodeRowKind::Remaining]
.map(|kind| TimecodeRow::new(kind).source(TimecodeSource::Program))
.to_vec(),
)
}
fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let text = TimecodeText::new(|row| format!("{:?}", row.kind));
TimecodePanel::new("Timecode", Bind::bound(data.value("settings", rows())), text).show(ui).into()
}
fn kinds(fixture: &mut Fixture) -> Vec<TimecodeRowKind> {
fixture.data().value("settings", rows()).rows.iter().map(|row| row.kind).collect()
}
fn open_menu_by_key(fixture: &mut Fixture, readout: &str, key: Key, modifiers: Modifiers) {
let target = fixture.by_label(readout).expect("the readout");
fixture.click(&target);
fixture.settle();
fixture.key(key, modifiers);
fixture.settle();
}
#[trial]
fn a_rows_menu_opens_from_a_secondary_click_or_the_menu_keys_and_acts_on_that_row() {
use TimecodeRowKind::{CurrentTime, Duration, MediaTime, Remaining};
let mut fixture = Fixture::story(&Story::new("timecode panel", panel));
fixture.settle();
let second = "Duration \u{b7} Program: Duration";
let target = fixture.by_label(second).expect("the second readout");
fixture.click(&target);
fixture.settle();
assert!(fixture.by_label("Remove Row").is_none(), "a primary click opens no menu");
assert_eq!(kinds(&mut fixture), [CurrentTime, Duration, Remaining], "a primary click changes nothing");
let at = target.center();
fixture.frame(vec![pointer::moved(at)]);
fixture.frame(vec![pointer::secondary(at, true)]);
fixture.frame(vec![pointer::secondary(at, false)]);
fixture.settle();
let remove = fixture.by_label("Remove Row").expect("a secondary click on the row opens its menu");
fixture.click(&remove);
fixture.settle();
assert_eq!(kinds(&mut fixture), [CurrentTime, Remaining], "Remove Row removed the row the menu opened from");
open_menu_by_key(&mut fixture, "Remaining \u{b7} Program: Remaining", Key::F10, Modifiers::SHIFT);
let media = fixture.by_label("Media Time").expect("Shift+F10 on the focused row opens its menu");
fixture.click(&media);
fixture.settle();
assert_eq!(kinds(&mut fixture), [CurrentTime, MediaTime], "the menu Shift+F10 opened acted on its row");
open_menu_by_key(&mut fixture, "Current Time \u{b7} Program: CurrentTime", Key::Menu, Modifiers::NONE);
let duration = fixture.by_label("Duration").expect("the Menu key on the focused row opens its menu");
fixture.click(&duration);
fixture.settle();
assert_eq!(kinds(&mut fixture), [Duration, MediaTime], "the menu the Menu key opened acted on its row");
}