refactor(monorepo): reorganización lógica + renames + SDDs + split CHANGELOG

Reorganización física de crates/:
- core/ (mezclaba 6 propósitos) se divide en protocol/, init/, runtime/, compat/
- shared/ (3 crates) se redistribuye en protocol/ e init/
- lapaloma (sub-módulo de ui_engine) se promueve a modules/pineal/

Renames de proyectos:
- shipote → shuma (runtime de sandboxes)
- nouser → akasha (explorador de Mónadas)
- yahweh → nahual (motor GPUI, antes ui_engine/)
- lapaloma → pineal (data-viz agnóstica)

Fraccionamiento UI → core agnóstico:
- vista-core (DeckState + snap, 175 LOC, 5 tests verdes)
- barra-core (Task + render_html + sanitize, 90 LOC, 5 tests verdes)
- vista-web y barra-web ahora son thin DOM bindings

Documentación nueva:
- 16 SDDs por subdirectorio (≤80 LOC c/u): protocol/init/runtime/compat
  + 10 módulos + apps/
- docs/STATUS.md con cifras reales por proyecto
- docs/ROADMAP.md con plan a finalización (6 hitos, ~6-8 semanas)
- CHANGELOG.md particionado en docs/changelog/<proyecto>.md (7 buckets)

Automatización:
- scripts/reorg.py — script idempotente que: git mv directorios, renombra
  package names, recomputa path = refs, reescribe imports rust, actualiza
  workspace Cargo.toml. Soporta --dry-run.
- scripts/split-changelog.py — particiona CHANGELOG por componente.

Validación:
- cargo check --workspace pasa (124 crates + 2 nuevos cores).
- 10 tests adicionales (5 en vista-core + 5 en barra-core) verdes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
sergio
2026-05-19 14:48:34 +00:00
parent 86fb6ae20b
commit 550c98f275
375 changed files with 8512 additions and 7155 deletions
+40
View File
@@ -0,0 +1,40 @@
# modules/vista/ — Deck horizontal swipe (PageView)
**Propósito.** Carousel/PageView estilo Flutter: gesto horizontal con
snap a página, distinción horizontal vs vertical, soporte mouse +
touch + pointer events. Lógica separada del binding DOM.
## Crates
| crate | tipo | rol |
| ------------- | ---- | --------------------------------------------------------- |
| `vista-core` | lib | `DeckState` agnóstico: pointer_down/move/end → outcomes |
| `vista-web` | lib | Binding DOM sobre `<strip>`: traduce eventos + aplica CSS |
## Dependencias
- `vista-core`: sin deps externas. Pura state machine.
- `vista-web``vista-core`, `wasm-bindgen`, `web-sys` (PointerEvent).
## API agnóstica (vista-core)
```rust
let mut deck = DeckState::new();
deck.pointer_down(x, y, pointer_id, viewport_width);
match deck.pointer_move(x, y) {
DragOutcome::StartHorizontal { pointer_id } => capture_pointer(),
DragOutcome::DragOffset(px) => apply_translate(px),
DragOutcome::CancelVertical => yield_to_scroll(),
DragOutcome::Idle => {}
}
if let Some(r) = deck.pointer_end(offset, width, n_pages) {
apply_translate(r.offset_px);
if r.changed { notify(r.target_index); }
}
```
## Estado
vista-core: 5 tests verdes (drag decision + snap + clamp + goto).
vista-web: binding DOM intacto, ahora delega toda la lógica a core.
LOC 530 (core 175 + web 355). Reutilizable en backends no-web.
@@ -0,0 +1,8 @@
[package]
name = "vista-core"
description = "Vista — máquina de estados agnóstica para deck horizontal con snap. Sin dependencias web/DOM."
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
publish.workspace = true
+177
View File
@@ -0,0 +1,177 @@
//! Vista core — máquina de estados agnóstica del deck horizontal.
//!
//! Lógica pura: dados los eventos crudos de pointer (coords + viewport width
//! + n_pages) decide cuándo arrancar drag horizontal, cuánto trasladar el
//! strip y a qué página snapear al soltar. Sin DOM, sin wasm-bindgen.
/// Umbral en pixels para confirmar gesto horizontal vs vertical.
pub const DRAG_DECISION_PX: f64 = 8.0;
/// Cuán más horizontal que vertical debe ser el delta para considerarse "swipe".
pub const HORIZONTAL_BIAS: f64 = 1.3;
#[derive(Clone, Debug, Default)]
pub struct DeckState {
pub current_index: usize,
pointer_start: Option<(f64, f64, i32)>,
drag_active: bool,
drag_start_offset: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub enum DragOutcome {
/// Aún no hay decisión — esperar más movimiento.
Idle,
/// Empezar drag horizontal: el host debe capturar el pointer.
StartHorizontal { pointer_id: i32 },
/// Movimiento vertical predominante — host debe ceder al scroll nativo.
CancelVertical,
/// Drag en curso — host debe trasladar el strip a este offset.
DragOffset(f64),
}
#[derive(Clone, Debug, PartialEq)]
pub struct SnapResult {
pub target_index: usize,
pub offset_px: f64,
pub changed: bool,
}
impl DeckState {
pub fn new() -> Self { Self::default() }
/// Marca el inicio de un gesto. `viewport_width` se usa para anclar el
/// drag_start_offset a la página visible actual.
pub fn pointer_down(&mut self, x: f64, y: f64, pointer_id: i32, viewport_width: f64) {
self.pointer_start = Some((x, y, pointer_id));
self.drag_active = false;
self.drag_start_offset = -(self.current_index as f64) * viewport_width;
}
/// Procesa un movimiento. Devuelve la acción que el host debe ejecutar.
pub fn pointer_move(&mut self, x: f64, y: f64) -> DragOutcome {
let Some((sx, sy, pid)) = self.pointer_start else {
return DragOutcome::Idle;
};
let dx = x - sx;
let dy = y - sy;
if !self.drag_active {
let abs_dx = dx.abs();
let abs_dy = dy.abs();
if abs_dx > DRAG_DECISION_PX && abs_dx > abs_dy * HORIZONTAL_BIAS {
self.drag_active = true;
return DragOutcome::StartHorizontal { pointer_id: pid };
} else if abs_dy > DRAG_DECISION_PX {
self.pointer_start = None;
return DragOutcome::CancelVertical;
} else {
return DragOutcome::Idle;
}
}
DragOutcome::DragOffset(self.drag_start_offset + dx)
}
/// Finaliza el gesto. Si había drag activo, calcula la página snap y
/// actualiza `current_index`. `current_offset` viene del estado real
/// del strip (el host lee CSS transform / variable).
pub fn pointer_end(
&mut self,
current_offset: f64,
viewport_width: f64,
n_pages: usize,
) -> Option<SnapResult> {
let was_active = self.drag_active;
self.drag_active = false;
self.pointer_start = None;
if !was_active || viewport_width <= 0.0 || n_pages == 0 {
return None;
}
let raw = -current_offset / viewport_width;
let target = (raw.round().max(0.0) as usize).min(n_pages - 1);
let offset_px = -(target as f64) * viewport_width;
let changed = self.current_index != target;
self.current_index = target;
Some(SnapResult { target_index: target, offset_px, changed })
}
/// Salto programático (click en tabs externos). Devuelve el offset
/// resultante para que el host lo aplique al strip.
pub fn goto(&mut self, index: usize, viewport_width: f64) -> SnapResult {
let offset_px = -(index as f64) * viewport_width;
let changed = self.current_index != index;
self.current_index = index;
SnapResult { target_index: index, offset_px, changed }
}
/// Reposiciona tras un resize. Devuelve el offset que el host debe
/// aplicar sin animación.
pub fn reposition(&self, viewport_width: f64) -> f64 {
-(self.current_index as f64) * viewport_width
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vertical_drag_is_cancelled() {
let mut s = DeckState::new();
s.pointer_down(100.0, 100.0, 1, 800.0);
// Movimiento vertical mayor que el umbral.
let r = s.pointer_move(100.0, 120.0);
assert_eq!(r, DragOutcome::CancelVertical);
}
#[test]
fn horizontal_drag_starts_after_threshold() {
let mut s = DeckState::new();
s.pointer_down(100.0, 100.0, 7, 800.0);
// Justo por debajo del umbral → Idle.
assert_eq!(s.pointer_move(105.0, 100.0), DragOutcome::Idle);
// Sobre el umbral con bias horizontal → Start.
let r = s.pointer_move(120.0, 100.0);
assert_eq!(r, DragOutcome::StartHorizontal { pointer_id: 7 });
}
#[test]
fn snap_rounds_to_nearest_page() {
let mut s = DeckState::new();
s.current_index = 1;
s.pointer_down(0.0, 0.0, 1, 1000.0); // drag_start_offset = -1000
// Forzar drag activo
s.pointer_move(20.0, 0.0);
// Offset actual = -1000 + 20 = -980 → target round(980/1000) = 1, sin cambio
let r = s.pointer_end(-980.0, 1000.0, 3).unwrap();
assert_eq!(r.target_index, 1);
assert!(!r.changed);
// Mover lo suficiente para snapear a página 0
s.pointer_down(0.0, 0.0, 1, 1000.0);
s.pointer_move(600.0, 0.0);
let r = s.pointer_end(-400.0, 1000.0, 3).unwrap();
assert_eq!(r.target_index, 0);
assert!(r.changed);
}
#[test]
fn snap_clamps_to_bounds() {
let mut s = DeckState::new();
s.current_index = 2;
s.pointer_down(0.0, 0.0, 1, 500.0);
s.pointer_move(50.0, 0.0);
// Offset muy a la izquierda → debería clamp a n_pages-1
let r = s.pointer_end(-9999.0, 500.0, 3).unwrap();
assert_eq!(r.target_index, 2);
}
#[test]
fn goto_updates_index_and_offset() {
let mut s = DeckState::new();
let r = s.goto(2, 800.0);
assert_eq!(r.target_index, 2);
assert_eq!(r.offset_px, -1600.0);
assert!(r.changed);
// segundo goto al mismo índice → changed=false
let r = s.goto(2, 800.0);
assert!(!r.changed);
}
}
@@ -7,6 +7,7 @@ authors.workspace = true
publish.workspace = true
[dependencies]
vista-core = { path = "../vista-core" }
wasm-bindgen.workspace = true
js-sys.workspace = true
+70 -152
View File
@@ -1,18 +1,8 @@
//! Vista — deck horizontal de páginas con swipe estilo Flutter `PageView`.
//! Vista-web — binding DOM del deck horizontal. Toda la lógica de
//! decisión de gesto/snap vive en `vista-core`; este crate sólo traduce
//! `PointerEvent`s en eventos de `DeckState` y aplica el offset al DOM.
//!
//! Agnóstico del dominio: opera sobre un elemento DOM "strip" cuyos hijos
//! son las páginas. Cada hijo debe tener `flex: 0 0 100%` o equivalente
//! para que el deck pueda calcular el offset correcto.
//!
//! Comportamiento:
//! - Drag horizontal (mouse o touch) → strip se traslada con el dedo.
//! - Release → snap a la página más cercana, animación CSS.
//! - `goto(idx)` → scrolla programáticamente (click en tabs externos).
//! - Diferencia entre gesto vertical y horizontal: si el primer movimiento
//! es vertical, cede al native scroll del contenido (cada página puede
//! tener su propio overflow-y).
//!
//! No inyecta CSS — el caller provee:
//! Contrato CSS (el caller provee):
//! ```css
//! .vista-deck { overflow: hidden; touch-action: pan-y; }
//! .vista-strip {
@@ -30,15 +20,11 @@
use std::cell::RefCell;
use std::rc::Rc;
use vista_core::{DeckState, DragOutcome};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{Event, HtmlElement, PointerEvent};
/// Umbral en pixels para confirmar gesto horizontal vs vertical.
const DRAG_DECISION_PX: f64 = 8.0;
/// Cuán más horizontal que vertical debe ser el delta para considerarse "swipe".
const HORIZONTAL_BIAS: f64 = 1.3;
#[derive(Clone)]
pub struct Deck {
strip: HtmlElement,
@@ -46,82 +32,53 @@ pub struct Deck {
}
struct Inner {
current_index: usize,
pointer_start: Option<(f64, f64, i32)>, // (x, y, pointer_id)
drag_active: bool,
drag_start_offset: f64,
state: DeckState,
on_change: Option<Box<dyn FnMut(usize)>>,
}
impl Deck {
/// Monta el deck sobre el `strip`. El strip debe tener
/// `display: flex; transform: translate3d(var(--vista-offset, 0px), ...);`
/// y children con `flex: 0 0 100%`.
pub fn mount(strip: HtmlElement) -> Result<Self, JsValue> {
let inner = Rc::new(RefCell::new(Inner {
current_index: 0,
pointer_start: None,
drag_active: false,
drag_start_offset: 0.0,
state: DeckState::new(),
on_change: None,
}));
install_pointerdown(&strip, &inner)?;
install_pointermove(&strip, &inner)?;
install_pointerend(&strip, &inner, "pointerup")?;
install_pointerend(&strip, &inner, "pointercancel")?;
install_pointerend(&strip, &inner, "pointerleave")?;
install_resize(&strip, &inner)?;
Ok(Self { strip, inner })
}
/// Navega a la página por índice. Con `smooth=false` se aplica
/// `.vista-instant` un frame para saltar sin transición.
pub fn goto(&self, index: usize, smooth: bool) {
let width = self.strip.client_width() as f64;
let offset = -(index as f64) * width;
let mut i = self.inner.borrow_mut();
let r = i.state.goto(index, width);
drop(i);
if !smooth {
let _ = self.strip.class_list().add_1("vista-instant");
}
let _ = self
.strip
.style()
.set_property("--vista-offset", &format!("{}px", offset));
set_offset(&self.strip, r.offset_px);
if !smooth {
// Quitamos `vista-instant` en el siguiente frame para restaurar la
// transición ordinaria.
let strip = self.strip.clone();
let cb = Closure::once(Box::new(move || {
let _ = strip.class_list().remove_1("vista-instant");
}) as Box<dyn FnOnce()>);
if let Some(w) = web_sys::window() {
let _ = w.request_animation_frame(cb.as_ref().unchecked_ref());
}
cb.forget();
clear_instant_next_frame(&self.strip);
}
let mut i = self.inner.borrow_mut();
let changed = i.current_index != index;
i.current_index = index;
if changed {
if r.changed {
let mut i = self.inner.borrow_mut();
if let Some(cb) = i.on_change.as_mut() {
cb(index);
cb(r.target_index);
}
}
}
/// Índice de página actualmente visible.
pub fn current_index(&self) -> usize {
self.inner.borrow().current_index
self.inner.borrow().state.current_index
}
/// Cantidad de páginas hijas del strip (live: lee el DOM).
pub fn page_count(&self) -> u32 {
self.strip.child_element_count()
}
/// Registra (o reemplaza) el callback de cambio de página. Se dispara
/// tras el snap de un swipe, o tras un `goto()` que cambie de índice.
pub fn on_change<F: FnMut(usize) + 'static>(&self, cb: F) {
self.inner.borrow_mut().on_change = Some(Box::new(cb));
}
@@ -131,71 +88,43 @@ impl Deck {
}
}
fn install_pointerdown(
strip: &HtmlElement,
inner: &Rc<RefCell<Inner>>,
) -> Result<(), JsValue> {
fn install_pointerdown(strip: &HtmlElement, inner: &Rc<RefCell<Inner>>) -> Result<(), JsValue> {
let strip2 = strip.clone();
let inner2 = inner.clone();
let cb = Closure::<dyn FnMut(PointerEvent)>::new(move |e: PointerEvent| {
let mut i = inner2.borrow_mut();
let width = strip2.client_width() as f64;
i.pointer_start = Some((
inner2.borrow_mut().state.pointer_down(
e.client_x() as f64,
e.client_y() as f64,
e.pointer_id(),
));
i.drag_active = false;
i.drag_start_offset = -(i.current_index as f64) * width;
width,
);
});
strip.add_event_listener_with_callback("pointerdown", cb.as_ref().unchecked_ref())?;
cb.forget();
Ok(())
}
fn install_pointermove(
strip: &HtmlElement,
inner: &Rc<RefCell<Inner>>,
) -> Result<(), JsValue> {
fn install_pointermove(strip: &HtmlElement, inner: &Rc<RefCell<Inner>>) -> Result<(), JsValue> {
let strip2 = strip.clone();
let inner2 = inner.clone();
let cb = Closure::<dyn FnMut(PointerEvent)>::new(move |e: PointerEvent| {
let mut i = inner2.borrow_mut();
let Some((sx, sy, pid)) = i.pointer_start else {
return;
};
let dx = e.client_x() as f64 - sx;
let dy = e.client_y() as f64 - sy;
if !i.drag_active {
let abs_dx = dx.abs();
let abs_dy = dy.abs();
if abs_dx > DRAG_DECISION_PX && abs_dx > abs_dy * HORIZONTAL_BIAS {
// Empieza drag horizontal.
i.drag_active = true;
let outcome = inner2
.borrow_mut()
.state
.pointer_move(e.client_x() as f64, e.client_y() as f64);
match outcome {
DragOutcome::StartHorizontal { pointer_id } => {
let _ = strip2.class_list().add_1("vista-dragging");
// Capturar pointer para que los `move` sigan llegando aunque
// el cursor se vaya del strip.
let _ = strip2.set_pointer_capture(pid);
} else if abs_dy > DRAG_DECISION_PX {
// Movimiento vertical predominante — cancelar este drag.
i.pointer_start = None;
return;
} else {
return;
let _ = strip2.set_pointer_capture(pointer_id);
}
}
if i.drag_active {
let offset = i.drag_start_offset + dx;
let _ = strip2
.style()
.set_property("--vista-offset", &format!("{}px", offset));
// CRÍTICO en móvil: con listener passive el preventDefault sería
// un no-op y el browser se llevaría el gesto como pan/scroll.
e.prevent_default();
DragOutcome::DragOffset(offset) => {
set_offset(&strip2, offset);
e.prevent_default();
}
DragOutcome::Idle | DragOutcome::CancelVertical => {}
}
});
// `passive: false` es la diferencia entre que el swipe funcione o no en
// navegadores móviles. Default = passive, donde preventDefault no aplica.
let opts = web_sys::AddEventListenerOptions::new();
opts.set_passive(false);
strip.add_event_listener_with_callback_and_add_event_listener_options(
@@ -215,34 +144,19 @@ fn install_pointerend(
let strip2 = strip.clone();
let inner2 = inner.clone();
let cb = Closure::<dyn FnMut(PointerEvent)>::new(move |e: PointerEvent| {
let mut i = inner2.borrow_mut();
let was_active = i.drag_active;
i.drag_active = false;
i.pointer_start = None;
if !was_active {
return;
}
let _ = strip2.class_list().remove_1("vista-dragging");
let _ = strip2.release_pointer_capture(e.pointer_id());
let width = strip2.client_width() as f64;
let offset = current_offset_px(&strip2);
let n_pages = strip2.child_element_count() as usize;
if width <= 0.0 || n_pages == 0 {
return;
}
// Snap a la página más cercana (clamp a [0, n-1]).
let raw = -offset / width;
let target = raw.round().max(0.0) as usize;
let target = target.min(n_pages - 1);
let snapped_offset = -(target as f64) * width;
let _ = strip2
.style()
.set_property("--vista-offset", &format!("{}px", snapped_offset));
let changed = i.current_index != target;
i.current_index = target;
if changed {
if let Some(cb) = i.on_change.as_mut() {
cb(target);
let res = inner2.borrow_mut().state.pointer_end(offset, width, n_pages);
let _ = strip2.class_list().remove_1("vista-dragging");
let _ = strip2.release_pointer_capture(e.pointer_id());
if let Some(r) = res {
set_offset(&strip2, r.offset_px);
if r.changed {
let mut i = inner2.borrow_mut();
if let Some(cb) = i.on_change.as_mut() {
cb(r.target_index);
}
}
}
});
@@ -252,41 +166,45 @@ fn install_pointerend(
}
fn install_resize(strip: &HtmlElement, inner: &Rc<RefCell<Inner>>) -> Result<(), JsValue> {
let Some(window) = web_sys::window() else {
return Ok(());
};
let Some(window) = web_sys::window() else { return Ok(()) };
let strip2 = strip.clone();
let inner2 = inner.clone();
let cb = Closure::<dyn FnMut()>::new(move || {
// Reposicionar sin animación para que un resize no cause un slide.
let idx = inner2.borrow().current_index;
let _ = strip2.class_list().add_1("vista-instant");
let width = strip2.client_width() as f64;
let offset = -(idx as f64) * width;
let _ = strip2
.style()
.set_property("--vista-offset", &format!("{}px", offset));
let strip_for_clear = strip2.clone();
let cb2 = Closure::once(Box::new(move || {
let _ = strip_for_clear.class_list().remove_1("vista-instant");
}) as Box<dyn FnOnce()>);
if let Some(w) = web_sys::window() {
let _ = w.request_animation_frame(cb2.as_ref().unchecked_ref());
}
cb2.forget();
let offset = inner2.borrow().state.reposition(width);
let _ = strip2.class_list().add_1("vista-instant");
set_offset(&strip2, offset);
clear_instant_next_frame(&strip2);
});
window.add_event_listener_with_callback("resize", cb.as_ref().unchecked_ref())?;
cb.forget();
Ok(())
}
/// Lee `--vista-offset` del strip como número de pixels (default 0).
fn set_offset(strip: &HtmlElement, offset_px: f64) {
let _ = strip
.style()
.set_property("--vista-offset", &format!("{}px", offset_px));
}
fn current_offset_px(strip: &HtmlElement) -> f64 {
let s = strip.style().get_property_value("--vista-offset").unwrap_or_default();
let trimmed = s.trim().trim_end_matches("px");
trimmed.parse::<f64>().unwrap_or(0.0)
let s = strip
.style()
.get_property_value("--vista-offset")
.unwrap_or_default();
s.trim().trim_end_matches("px").parse::<f64>().unwrap_or(0.0)
}
fn clear_instant_next_frame(strip: &HtmlElement) {
let strip2 = strip.clone();
let cb = Closure::once(Box::new(move || {
let _ = strip2.class_list().remove_1("vista-instant");
}) as Box<dyn FnOnce()>);
if let Some(w) = web_sys::window() {
let _ = w.request_animation_frame(cb.as_ref().unchecked_ref());
}
cb.forget();
}
/// Suprime warnings de uso no-utilizado durante compilación host (no-WASM).
#[doc(hidden)]
pub fn __unused_event_marker(_e: &Event) {}