object-panels-w21: net change of 1 commits

- object-panels-w21: written by an agent
This commit is contained in:
bflatastic
2026-11-21 23:37:13 +07:00
parent 6cac82b36c
commit ebcada48b6
4 changed files with 576 additions and 462 deletions
+238 -140
View File
@@ -1,70 +1,168 @@
//! JavaScript Files (the SVG Interactivity panel's Link JavaScript Files…): the JavaScript files
//! the active document links, in a list. Add links the path or URL in File or URL
//! (`svgInteractivity.addFile`; Choose… puts a picked file's `file:///` URL there where the host
//! has an open dialog), and Remove unlinks the file selected in the list
//! (`svgInteractivity.removeFile`). SVG export writes a `<script xlink:href>` element for each
//! linked file. Add and Remove act at once. The dialog has only Close.
//! (`svgInteractivity.addFile`; Choose… puts a picked file's `file:///` URL there), and Remove
//! unlinks the file selected in the list (`svgInteractivity.removeFile`). SVG export writes a
//! `<script xlink:href>` element for each linked file. Add and Remove act at once. The dialog has
//! only Close.
//!
//! Fields: `file` (the path or URL to link), `selected` (a linked file).
//!
//! The dialog lives on the window's dialog host. Its body has no app, so it records the one
//! action a click asked for and [`pump`] runs it, and pushes the document's files in each frame.
//!
//! In a frame automation drives with read roots in force, the list names a file outside them by
//! its file name alone, as `svgInteractivity.info` does; `selected` keeps the file as linked.
use craft::behavior::{Selection, keyed};
use craft::host::PickRequest;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft::ui::form::Field;
use craft::ui::layout_components::Row;
use craft::ui::list::{List, ListRow};
use craft::ui::patterns::form_dialogs::PathRow;
use craft::ui::sections::{DialogRole, FooterButton};
use egui::{Context, Ui};
use serde_json::{Value, json};
use vectorcraft_engine::cmd::links::shown_script;
use super::DialogSpec;
use crate::picks::PickRequest;
use crate::state::Dialog;
use crate::{FilePick, VectorcraftApp, widgets};
use crate::VectorcraftApp;
use crate::panels::svg_interactivity::caption;
/// The dialog kind of JavaScript Files.
pub const KIND: &str = "javascriptFiles";
/// The key the dialog is known by: its id on the dialog stack, and the name `ui.javascriptFilesDialog`
/// documents.
const KEY: &str = "javascriptFiles";
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("JavaScript Files").into(),
body,
confirm: |app, _| {
app.ui.dialog = None;
Ok(Value::Null)
},
ok: None,
min_width: 420.0,
..DialogSpec::FORM
};
/// What the body asks [`pump`] to do with the app.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Pending {
Add,
Remove,
}
/// Open JavaScript Files for the active document.
/// The values the body edits.
#[derive(Debug, Default)]
struct Form {
/// The path or URL to link.
file: String,
/// The linked file selected in the list, as linked or as the list shows it.
selected: String,
pending: Option<Pending>,
}
impl Form {
/// The form once `action` ran: an added file is the selected one, a removed one leaves none.
fn finished(&mut self, action: Pending, file: String) {
match action {
Pending::Add => {
self.selected = file;
self.file.clear();
}
Pending::Remove => self.selected.clear(),
}
}
}
/// The JavaScript Files dialog on the window's dialog host; at most one is open.
#[derive(Debug)]
pub(crate) struct JavaScriptFiles {
open: bool,
/// The active document's linked files ([`listed`]), pushed by [`pump`].
files: Vec<(String, String)>,
form: Form,
}
impl JavaScriptFiles {
fn new(files: Vec<(String, String)>) -> Self {
JavaScriptFiles { open: true, files, form: Form::default() }
}
/// `selected` as the list shows it.
// PLAN: `json_fields` has no document, so `shown_script` cannot run when automation reads the dialog; it
// reports the form `pump` pushed in the last frame, which is the read-root form only when that frame ran under
// the roots. Needs the rule by document path from the engine (links.rs `shown_script`), or hub-w2's inspect to
// pump under the roots.
fn shown_selected(&self) -> &str {
let selected = self.form.selected.as_str();
self.files.iter().find(|(linked, _)| linked == selected).map_or(selected, |(_, shown)| shown.as_str())
}
}
impl StackDialog for JavaScriptFiles {
type Result = ();
fn id(&self) -> DialogId {
dialog_id(KEY)
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let Self { open, files, form } = self;
let shown = Dialog::new(tl!("JavaScript Files"))
.buttons(vec![FooterButton::new(tl!("Close"), DialogRole::Cancel)])
.opened(Bind::bound(open))
.show(ui, |ui, _| body(ui, files, form));
shown.output.closed.map(|_| DialogResult::Ok(()))
}
fn json_fields(&self) -> Option<Value> {
Some(json!({ "file": self.form.file, "selected": self.shown_selected() }))
}
fn set_json_field(&mut self, _ctx: &Context, field: &str, value: Value) -> Result<(), String> {
let target = match field {
"file" => &mut self.form.file,
"selected" => &mut self.form.selected,
_ => return Err(format!("JavaScript Files has no field `{field}`")),
};
*target = value.as_str().ok_or_else(|| format!("`{field}` takes a string"))?.to_string();
Ok(())
}
}
/// Open JavaScript Files for the active document; an open one stays as it is.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
if app.session.active().is_none() {
return Err("no document open".into());
}
app.ui.dialog = Some(Dialog::new(KIND, json!({ "file": "", "selected": "" })));
let files = listed(app);
let dialogs = app.dialogs().ok_or("the dialog host isn't available")?;
// An open dialog keeps its input: the refused one is dropped.
let _ = dialogs.with(|host| host.open_unless_open(JavaScriptFiles::new(files)));
Ok(Value::Null)
}
/// The extension of JavaScript files.
const JS_EXTS: &[&str] = &["js"];
/// The open dialog for a JavaScript file.
fn pick() -> FilePick {
FilePick { filters: vec![FilePick::filter("JavaScript", JS_EXTS)], ..Default::default() }
}
/// Choose…: the file picked in the open dialog into File or URL, as a `file:///` URL
/// ([`crate::io::file_url`]).
fn choose(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
if let Some(path) = crate::picks::open(app, &pick()) {
d.fields.insert("file".into(), json!(crate::io::file_url(&path)));
/// Pushes the document's linked files into the open dialog and runs the Add or Remove its body asked
/// for. A dialog that closed leaves only an empty answer, which is dropped.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let Some(dialogs) = app.dialogs() else { return };
let open = dialogs.with(|host| {
let _ = host.take::<JavaScriptFiles>();
host.is_open::<JavaScriptFiles>()
});
if !open {
return;
}
let files = listed(app);
let asked = dialogs.with(|host| {
let dialog = host.get_mut::<JavaScriptFiles>()?;
dialog.files = files;
let form = &mut dialog.form;
form.pending.take().map(|action| (action, form.file.trim().to_string(), form.selected.clone()))
});
let Some((action, file, selected)) = asked else { return };
let result = match action {
Pending::Add => app.run("svgInteractivity.addFile", json!({ "file": file })),
Pending::Remove => app.run("svgInteractivity.removeFile", json!({ "file": selected })),
};
match result {
Ok(_) => dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<JavaScriptFiles>() {
dialog.form.finished(action, file);
}
}),
Err(e) => app.status(e),
}
Ok(())
}
/// What a button asked for, done once the dialog is drawn.
enum Action {
Select(String),
Choose,
Add,
Remove,
}
/// The active document's linked files, each as it is linked and as the list shows it
@@ -84,89 +182,70 @@ fn selected_row(files: &[(String, String)], selected: &str) -> Option<usize> {
}
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let files = listed(app);
let selected = d.str("selected");
let row = selected_row(&files, &selected);
let mut act = None;
widgets::list_box(ui, |ui| {
egui::ScrollArea::vertical().id_salt("javascript-files").min_scrolled_height(140.0).max_height(140.0).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.set_min_height(140.0);
fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) {
let source = keyed(files, |(linked, _): &(String, String)| linked.clone());
let selection = selected_row(files, &form.selected).and_then(|i| files.get(i)).map(|(linked, _)| Selection::single(linked.clone())).unwrap_or_default();
let list = List::<String>::options(tl!("Linked files"))
.selection(Bind::given(selection))
.sizing(Sizing::FillWidth)
.empty(tl!("No JavaScript files linked"))
.show_items(ui, &source, &mut |key, _| {
// Paths and URLs are data: shown as they are.
for (i, (linked, shown)) in files.iter().enumerate() {
if ui.selectable_label(row == Some(i), shown.as_str()).clicked() {
act = Some(Action::Select(linked.clone()));
}
}
ListRow::new(files.iter().find(|(linked, _)| linked == key).map_or_else(String::new, |(_, shown)| shown.clone()))
});
});
ui.add_space(8.0);
widgets::label_row(ui, tl!("File or URL:"), 84.0, |ui| {
if let Some(v) = widgets::exact_text_field(ui, "javascript-file", &d.str("file"), 240.0) {
d.fields.insert("file".into(), json!(v));
for event in list.events {
if let CollectionEvent::Activate(key) = event {
form.selected = key;
}
if crate::picks::can(app, &PickRequest::Open(pick())) && widgets::flat_button(ui, tl!("Choose…"), 64.0).clicked() {
act = Some(Action::Choose);
}
});
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
if ui.add_enabled_ui(!d.str("file").trim().is_empty(), |ui| widgets::flat_button(ui, tl!("Add"), 64.0)).inner.clicked() {
act = Some(Action::Add);
}
if ui.add_enabled_ui(row.is_some(), |ui| widgets::flat_button(ui, tl!("Remove"), 64.0)).inner.clicked() {
act = Some(Action::Remove);
}
});
let r = match act {
None => Ok(()),
Some(Action::Select(f)) => {
d.fields.insert("selected".into(), json!(f));
Ok(())
}
// The open dialog, shown off the UI thread, fills the dialog as it is then.
Some(Action::Choose) => crate::picks::in_dialog(app, d, choose),
Some(Action::Add) => {
let file = d.str("file").trim().to_string();
app.run("svgInteractivity.addFile", json!({ "file": file })).map(|_| {
d.fields.insert("selected".into(), json!(file));
d.fields.insert("file".into(), json!(""));
})
}
Some(Action::Remove) => app.run("svgInteractivity.removeFile", json!({ "file": selected })).map(|_| {
d.fields.insert("selected".into(), json!(""));
}),
};
if let Err(e) = r {
app.status(e);
}
false
Field::new(caption("File or URL:")).show(ui, |ui, _| {
let request = PickRequest::open("javascript").filter("JavaScript", &["js"]);
let out = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).pick(request).show(ui);
// The answer is a path; the dialog links a `file:///` URL ([`crate::io::file_url`]).
if let Some(path) = out.picked {
form.file = crate::io::file_url(&path);
}
});
let chosen = selected_row(files, &form.selected);
Row::new().show(ui, |ui, _| {
if clicked(&Button::new(tl!("Add")).enabled(!form.file.trim().is_empty()).show(ui)) {
form.pending = Some(Pending::Add);
}
if clicked(&Button::new(tl!("Remove")).enabled(chosen.is_some()).show(ui)) {
form.pending = Some(Pending::Remove);
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use craft::host::{AppInfo, Host, Picked, ScriptedFiles};
use craft::ui::testing::Fixture;
use vectorcraft_engine::Session;
/// One headless frame of the dialog's body: the texts drawn.
fn frame(app: &mut VectorcraftApp, d: &mut Dialog) -> Vec<String> {
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
match s {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
use super::*;
use crate::tests::panel_harness::Panel;
/// The window's dialog host and the pump, as a frame of the app runs them.
fn draw(app: &mut VectorcraftApp, ui: &mut Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
body(app, ui, d);
});
out.textures_delta.clear();
let mut v = vec![];
out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));
v
pump(app, ui.ctx());
}
fn set_field(panel: &Panel, field: &str, value: &str) {
let dialogs = panel.app().dialogs().unwrap();
dialogs.with(|host| host.set_json_field(&panel.ctx(), dialog_id(KEY), field, json!(value))).unwrap();
}
fn json_selected(panel: &Panel) -> Value {
let dialogs = panel.app().dialogs().unwrap();
dialogs.with(|host| host.get::<JavaScriptFiles>().and_then(StackDialog::json_fields)).unwrap()["selected"].clone()
}
#[test]
@@ -175,15 +254,20 @@ mod tests {
assert!(open(&mut app).is_err(), "no document");
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("svgInteractivity.addFile", &json!({"file": "scripts/menu.js"})).unwrap();
crate::menus::invoke(&mut app, "ui.javascriptFilesDialog", json!({}));
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND));
let mut d = app.ui.dialog.clone().unwrap();
// (Only paths are checked: tests running alongside change the language labels are drawn in.)
let texts = frame(&mut app, &mut d);
assert!(texts.iter().any(|t| t == "scripts/menu.js"), "{texts:?}");
d.fields.insert("file".into(), json!("https://example.com/b.js"));
let texts = frame(&mut app, &mut d);
assert!(texts.iter().any(|t| t == "https://example.com/b.js"), "the field shows `file`: {texts:?}");
let mut panel = Panel::new(app, draw);
panel.app().run("ui.javascriptFilesDialog", json!({})).unwrap();
panel.frame();
panel.frame();
assert!(panel.shows("scripts/menu.js"), "the list names the linked file");
set_field(&panel, "file", "https://example.com/b.js");
panel.frame();
assert_eq!(panel.value(caption("File or URL:")).as_deref(), Some("https://example.com/b.js"), "the field shows `file`");
// Add acts at once and selects what it linked.
panel.click(tl!("Add"));
panel.frame();
let linked = panel.app().session.active().map(|st| st.doc.svg_scripts.clone()).unwrap_or_default();
assert!(linked.iter().any(|f| f == "https://example.com/b.js"), "{linked:?}");
assert_eq!(json_selected(&panel), json!("https://example.com/b.js"));
}
/// In a frame drawn with read roots in force, the list names a linked file outside them by its
@@ -197,14 +281,20 @@ mod tests {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("svgInteractivity.addFile", &json!({ "file": outside })).unwrap();
let mut d = Dialog::new(KIND, json!({ "file": "", "selected": "" }));
let texts = frame(&mut app, &mut d);
assert!(texts.contains(&outside), "{texts:?}");
let mut panel = Panel::new(app, draw);
panel.app().run("ui.javascriptFilesDialog", json!({})).unwrap();
set_field(&panel, "selected", &outside);
panel.frame();
panel.frame();
assert!(panel.shows(&outside), "the person's list");
assert_eq!(json_selected(&panel), json!(outside), "the person's");
let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&base.join("in")], &[]).unwrap();
let texts = vectorcraft_engine::file_access::confine(roots.as_ref(), || frame(&mut app, &mut d));
assert!(texts.iter().any(|t| t == "menu.js") && !texts.iter().any(|t| t.contains("vc-js-dialog")), "{texts:?}");
vectorcraft_engine::file_access::confine(roots.as_ref(), || panel.frame());
assert!(panel.shows("menu.js") && !panel.shows(&outside), "the list names the file alone");
assert_eq!(json_selected(&panel), json!("menu.js"), "`selected` as the request may name it");
// A row keeps the file as linked, so a click selects it by its whole path, which stays
// selected in the person's list; a name a request gives selects it too.
let app = panel.app();
let rows = vectorcraft_engine::file_access::confine(roots.as_ref(), || listed(&app));
assert_eq!(rows, [(outside.clone(), "menu.js".to_string())]);
assert_eq!((selected_row(&rows, &outside), selected_row(&rows, "menu.js")), (Some(0), Some(0)));
@@ -212,10 +302,12 @@ mod tests {
let twins = [rows[0].clone(), ("/elsewhere/menu.js".to_string(), "menu.js".to_string())];
assert_eq!((selected_row(&twins, "menu.js"), selected_row(&twins, "/elsewhere/menu.js")), (None, Some(1)));
assert_eq!(listed(&app), [(outside.clone(), outside.clone())], "the person's");
drop(app);
// Remove sends the selected name.
let removed = vectorcraft_engine::file_access::confine(roots.as_ref(), || app.run("svgInteractivity.removeFile", json!({"file": "menu.js"})));
let removed =
vectorcraft_engine::file_access::confine(roots.as_ref(), || panel.app().run("svgInteractivity.removeFile", json!({"file": "menu.js"})));
assert!(removed.is_ok(), "{removed:?}");
assert!(app.session.active().is_some_and(|st| st.doc.svg_scripts.is_empty()));
assert!(panel.app().session.active().is_some_and(|st| st.doc.svg_scripts.is_empty()));
let _ = std::fs::remove_dir_all(base);
}
@@ -223,13 +315,19 @@ mod tests {
/// spaces percent-encoded.
#[test]
fn choose_puts_the_picked_file_in_as_a_file_url() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let picked = std::env::temp_dir().join("my menu.js").to_string_lossy().into_owned();
app.services.pick_open = Some(Box::new(move |_: &FilePick| Some(picked.clone())));
let mut d = Dialog::new(KIND, json!({ "file": "", "selected": "" }));
choose(&mut app, &mut d).unwrap();
let file = d.str("file");
let files = Arc::new(ScriptedFiles::held());
let form = Rc::new(RefCell::new(Form::default()));
let shown = Rc::clone(&form);
let mut fixture = Fixture::new(move |ui| body(ui, &[], &mut shown.borrow_mut()));
fixture.host(Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build()));
fixture.settle();
let choose = fixture.by_label(tl!("Choose…")).expect("the Choose button");
fixture.click(&choose);
fixture.settle();
let picked = std::env::temp_dir().join("my menu.js");
assert!(files.answer(Picked::Paths(vec![picked])).is_some(), "Choose… filed a pick");
fixture.idle(3);
let file = form.borrow().file.clone();
assert!(file.starts_with("file:///") && file.ends_with("/my%20menu.js") && !file.contains('\\'), "{file}");
}
}
+184 -141
View File
@@ -7,36 +7,47 @@
use std::sync::Arc;
use egui::text::{LayoutJob, TextFormat};
use egui::{FontId, Ui};
use craft::behavior::IconId;
use craft::keymap::CommandRef;
use craft::theme::variant::Tone;
use craft::ui::contract::{Scroll, Show as _, ShowContainer as _};
use craft::ui::display::{Shade, Text};
use craft::ui::layout_components::Stack;
use craft::ui::menu::PanelRow;
use craft::ui::notices::{Notice, NoticeIcon, NoticeLayout};
use craft::ui::primitives::{IconSpec, Span};
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::sections::{FooterAction, FooterBar};
use craft::ui::style::{SurfaceKind, TypeRole};
use craft::ui::text::SelectableText;
use egui::Ui;
use serde_json::{Value, json};
use vectorcraft_svg::{CssOptions, CssUnits};
use super::{pstate, set_pstate};
use crate::theme::Tokens;
use crate::widgets::{self, menu_item};
use crate::{VectorcraftApp, io};
pub const ID: &str = "cssProperties";
/// Panel state: the export options.
pub(super) const OPTIONS: &str = "css-options";
/// Panel state: Generate CSS is on (the document's CSS shows while nothing is selected).
pub(super) const ALL: &str = "css-all";
/// The most rules the code view shows (Export All writes every one).
const MAX_SHOWN: usize = 300;
/// The CSS shown, and what it was made for: (document uid, revision, whole document, options,
/// dark theme).
#[derive(Clone, Default)]
struct Cache {
key: Option<(u64, u64, bool, CssOptions, bool)>,
shown: Arc<Shown>,
}
const COPY_SELECTED: &str = "ui.cssProperties.copySelected";
const EXPORT_SELECTED: &str = "ui.cssProperties.exportSelected";
const EXPORT_ALL: &str = "ui.cssProperties.exportAll";
const GENERATE: &str = "ui.cssProperties.generate";
const UNITS: &str = "ui.cssProperties.units";
const OPTION: &str = "ui.cssProperties.option";
/// The export options the panel menu switches, as `ui.cssProperties.option` names them.
const FLAGS: [&str; 4] = ["position", "dimensions", "unnamed", "rasterize"];
#[derive(Default)]
struct Shown {
/// The rules shown, highlighted.
job: Option<Arc<LayoutJob>>,
/// What [`shown`] was made for: (document uid, revision, whole document, options).
pub(crate) type CssKey = (u64, u64, bool, CssOptions);
/// The CSS the code view shows.
#[derive(Debug, Default)]
pub(crate) struct Shown {
/// The rules shown (at most [`MAX_SHOWN`]), as the command wrote them.
// PLAN: the sheet drops `job` and lists no field for the rules' text, which the spans are made from.
text: Vec<String>,
rules: usize,
/// Rules beyond [`MAX_SHOWN`].
more: usize,
@@ -51,49 +62,51 @@ fn params(opts: &CssOptions, scope: &str) -> Value {
p
}
/// The CSS rules as a code view: selectors and braces strong, property names dim.
fn highlight(rules: &[&str], t: &Tokens, font: FontId) -> LayoutJob {
let fmt = |color| TextFormat { font_id: font.clone(), color, ..Default::default() };
let mut job = LayoutJob::default();
/// The CSS rules as a code view: selectors and braces strong, property names muted, one blank line between rules.
fn spans(rules: &[String]) -> Vec<Span<'_>> {
let mut out = Vec::new();
for (i, rule) in rules.iter().enumerate() {
if i > 0 {
job.append("\n\n", 0.0, fmt(t.text));
out.push(Span::new("\n\n"));
}
for (j, line) in rule.lines().enumerate() {
if j > 0 {
job.append("\n", 0.0, fmt(t.text));
out.push(Span::new("\n"));
}
match line.split_once(": ") {
Some((k, v)) if line.starts_with(" ") => {
job.append(k, 0.0, fmt(t.text_dim));
job.append(": ", 0.0, fmt(t.text_dim));
job.append(v, 0.0, fmt(t.text));
out.push(Span::new(k).muted());
out.push(Span::new(": ").muted());
out.push(Span::new(v));
}
_ => job.append(line, 0.0, fmt(t.text_strong)),
_ => out.push(Span::new(line).strong()),
}
}
}
job
out
}
/// The CSS for the panel, made again only when the document, the scope or the options change.
fn shown(app: &mut VectorcraftApp, ui: &Ui, opts: &CssOptions, all: bool) -> Option<Arc<Shown>> {
fn shown(app: &mut VectorcraftApp, opts: &CssOptions, all: bool) -> Option<Arc<Shown>> {
let st = app.session.active()?;
let t = Tokens::get(ui.ctx());
let key = Some((st.uid, st.revision, all, opts.clone(), t.dark));
let mut c: Cache = pstate(ui.ctx(), "css-cache");
if c.key != key {
let (id, scope) = if all { ("css.generate", "all") } else { ("css.selection", "selection") };
let out = app.session.execute(id, &params(opts, scope)).unwrap_or_default();
let rules: Vec<&str> = out["rules"].as_array().into_iter().flatten().filter_map(|r| r["css"].as_str()).collect();
let warnings = io::notes_of(&out);
let job = (!rules.is_empty())
.then(|| Arc::new(highlight(rules.get(..MAX_SHOWN).unwrap_or(&rules), &t, egui::TextStyle::Monospace.resolve(ui.style()))));
let skipped = out["skipped"].as_u64().unwrap_or(0);
c = Cache { key, shown: Arc::new(Shown { job, rules: rules.len(), more: rules.len().saturating_sub(MAX_SHOWN), skipped, warnings }) };
set_pstate(ui.ctx(), "css-cache", c.clone());
let key: CssKey = (st.uid, st.revision, all, opts.clone());
if let Some((k, v)) = &app.canvas.css_shown
&& *k == key
{
return Some(Arc::clone(v));
}
Some(c.shown)
let (id, scope) = if all { ("css.generate", "all") } else { ("css.selection", "selection") };
let out = app.session.execute(id, &params(opts, scope)).unwrap_or_default();
let rules: Vec<&str> = out["rules"].as_array().into_iter().flatten().filter_map(|r| r["css"].as_str()).collect();
let shown = Arc::new(Shown {
text: rules.iter().take(MAX_SHOWN).map(|r| (*r).to_string()).collect(),
rules: rules.len(),
more: rules.len().saturating_sub(MAX_SHOWN),
skipped: out["skipped"].as_u64().unwrap_or(0),
warnings: io::notes_of(&out),
});
app.canvas.css_shown = Some((key, Arc::clone(&shown)));
Some(shown)
}
/// `w` as a sentence: capitalised, with a full stop.
@@ -103,30 +116,24 @@ fn sentence(w: &str) -> String {
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
let Some(selected) = app.session.active().map(|st| !st.selection.is_empty()) else {
widgets::dim_label(ui, tl!("No document"));
Text::new(tl!("No document")).shade(Shade::Muted).show(ui);
return;
};
let opts: CssOptions = pstate(&ctx, OPTIONS);
let all = !selected && pstate::<bool>(&ctx, ALL);
let Some(shown) = shown(app, ui, &opts, all) else { return };
widgets::list_box(ui, |ui| {
egui::ScrollArea::both().id_salt("css-properties-scroll").max_height(300.0).auto_shrink([false, true]).show(ui, |ui| {
ui.set_min_height(120.0);
match &shown.job {
Some(job) => {
ui.add(egui::Label::new(egui::WidgetText::LayoutJob(job.clone())).selectable(true).extend());
}
None if selected => super::empty_state(ui, "globe", tl!("No CSS"), tl!("The selected objects have no CSS of their own (see below).")),
None => super::empty_state(
ui,
"globe",
tl!("No selection"),
tl!("Select objects to see their CSS, or Generate CSS for the whole document."),
),
}
});
let opts = app.ui.css_properties_panel.options.clone();
let all = !selected && app.ui.css_properties_panel.all;
let Some(shown) = shown(app, &opts, all) else { return };
Stack::new().fill().surface(SurfaceKind::Well).scroll(Scroll::both()).show(ui, |ui, _| {
let globe = NoticeIcon::Custom(IconSpec::svg(IconId::new("globe")));
if shown.rules > 0 {
SelectableText::spans(tl!("CSS code"), spans(&shown.text)).mono().multiline().show(ui);
} else if selected {
let hint = tl!("The selected objects have no CSS of their own (see below).");
Notice::new(Tone::Neutral, hint).title(tl!("No CSS")).layout(NoticeLayout::Centred).icon(globe).show(ui);
} else {
let hint = tl!("Select objects to see their CSS, or Generate CSS for the whole document.");
Notice::new(Tone::Neutral, hint).title(tl!("No selection")).layout(NoticeLayout::Centred).icon(globe).show(ui);
}
});
let notes = (shown.more > 0)
.then(|| crate::i18n::tn(shown.more as u64, "{n} more rule: Export writes it.", "{n} more rules: Export writes every one."))
@@ -139,38 +146,30 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
)
}))
.chain(shown.warnings.iter().map(|w| sentence(w)));
let dim = Tokens::get(&ctx).text_dim;
for n in notes {
ui.add(egui::Label::new(egui::RichText::new(n).size(11.0).color(dim)).wrap());
Text::new(n).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
}
let has_css = shown.rules > 0;
let scope = if all { "all" } else { "selection" };
let (mut generate, mut copy, mut export) = (false, false, false);
widgets::bottom_bar(ui, |ui| {
generate = widgets::icon_button_enabled(
ui,
"sparkles",
tl!("Generate CSS: the whole document's CSS while nothing is selected"),
all,
!selected,
24.0,
)
.clicked();
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let tip = if all { tl!("Export All…") } else { tl!("Export Selected CSS…") };
export = widgets::icon_button_enabled(ui, "save", tip, false, has_css, 24.0).clicked();
let tip = if all { tl!("Copy All Styles") } else { tl!("Copy Selected Style") };
copy = widgets::icon_button_enabled(ui, "copy", tip, false, has_css, 24.0).clicked();
});
});
if generate {
set_pstate(&ctx, ALL, !all);
}
if copy {
crate::menus::invoke(app, "css.copy", params(&opts, scope));
}
if export {
crate::menus::invoke(app, "css.exportFile", params(&opts, scope));
// Generate at the start edge; Export at the end edge with Copy before it.
let footer = FooterBar::actions([
FooterAction::new(IconId::new("sparkles"), tl!("Generate CSS: the whole document's CSS while nothing is selected")).pressed(all).enabled(!selected),
FooterAction::new(IconId::new("save"), if all { tl!("Export All…") } else { tl!("Export Selected CSS…") }).enabled(has_css),
FooterAction::new(IconId::new("copy"), if all { tl!("Copy All Styles") } else { tl!("Copy Selected Style") }).enabled(has_css),
])
.at_start(1)
.show_footer(ui);
match footer.picked {
Some(0) => {
crate::menus::invoke(app, GENERATE, json!({}));
}
Some(1) => {
crate::menus::invoke(app, "css.exportFile", params(&opts, scope));
}
Some(2) => {
crate::menus::invoke(app, "css.copy", params(&opts, scope));
}
_ => {}
}
}
@@ -193,9 +192,14 @@ pub(crate) fn export_file(app: &mut VectorcraftApp, p: &Value) -> Result<Value,
let mut q = p.clone();
let path = q.as_object_mut().and_then(|o| o.remove("path")).and_then(|v| v.as_str().map(str::to_string));
let r = app.session.execute("css.export", &q).map_err(|e| e.to_string())?;
let path = io::target_path(app, path, "css")?;
io::write_to(&mut app.services, &path, r["data"].as_str().unwrap_or_default().as_bytes())?;
let folder = std::path::Path::new(&path).parent().map(std::path::Path::to_path_buf);
// PLAN: assumed `io::target_path(app, path, ext, then)` as files-w9 (decide files-2) gives it.
io::target_path(app, path, "css", move |app, path| write_export(app, &r, &path))
}
/// The sheet and the pictures of `css.export`'s reply `r`, written at `path` and beside it.
fn write_export(app: &mut VectorcraftApp, r: &Value, path: &str) -> Result<Value, String> {
io::write_to(&mut app.services, path, r["data"].as_str().unwrap_or_default().as_bytes())?;
let folder = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf);
let mut images = Vec::new();
for im in r["images"].as_array().into_iter().flatten() {
let (Some(name), Some(data)) = (im["name"].as_str(), im["dataBase64"].as_str()) else { continue };
@@ -205,55 +209,94 @@ pub(crate) fn export_file(app: &mut VectorcraftApp, p: &Value) -> Result<Value,
images.push(at);
}
// The status bar shows the warnings as Export As shows them.
let warnings = io::notes_of(&r);
let what = &path;
let warnings = io::notes_of(r);
let status = match warnings.first() {
Some(first) => io::exported_with_notes(what, warnings.len(), first),
Some(first) => io::exported_with_notes(path, warnings.len(), first),
None => format!("Exported {path}"),
};
io::show_with_notes(app, status, warnings);
Ok(json!({ "path": path, "rules": r["rules"], "images": images, "warnings": r["warnings"] }))
}
/// The panel (≡) menu: copy and export, Generate CSS and the export options.
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
let Some(selected) = app.session.active().map(|st| !st.selection.is_empty()) else { return };
let mut opts: CssOptions = pstate(&ctx, OPTIONS);
let all: bool = pstate(&ctx, ALL);
if menu_item(ui, tl!("Copy Selected Style"), selected, false) {
crate::menus::invoke(app, "css.copy", params(&opts, "selection"));
}
if menu_item(ui, tl!("Export Selected CSS…"), selected, false) {
crate::menus::invoke(app, "css.exportFile", params(&opts, "selection"));
}
if menu_item(ui, tl!("Export All…"), true, false) {
crate::menus::invoke(app, "css.exportFile", params(&opts, "all"));
}
ui.separator();
if menu_item(ui, tl!("Generate CSS"), true, all) {
set_pstate(&ctx, ALL, !all);
}
ui.separator();
let before = opts.clone();
ui.menu_button(format!(" {}", crate::i18n::fmt(tl!("Units: {units}"), &[("units", opts.units.name())])), |ui| {
for u in CssUnits::ALL {
if menu_item(ui, u.name(), true, opts.units == u) {
opts.units = u;
}
}
});
for (label, on) in [
(tl!("Absolute Position"), &mut opts.position),
(tl!("Width and Height"), &mut opts.dimensions),
(tl!("Unnamed Objects"), &mut opts.unnamed),
(tl!("Rasterize Unsupported Art"), &mut opts.rasterize),
] {
if menu_item(ui, label, true, *on) {
*on = !*on;
}
}
if opts != before {
set_pstate(&ctx, OPTIONS, opts);
/// The option `name` of `opts`, as `ui.cssProperties.option` names them.
fn flag_mut<'a>(opts: &'a mut CssOptions, name: &str) -> Option<&'a mut bool> {
match name {
"position" => Some(&mut opts.position),
"dimensions" => Some(&mut opts.dimensions),
"unnamed" => Some(&mut opts.unnamed),
"rasterize" => Some(&mut opts.rasterize),
_ => None,
}
}
fn units_ref(units: CssUnits) -> CommandRef {
CommandRef::with_params(UNITS, json!({ "units": units }))
}
fn option_ref(name: &str) -> CommandRef {
CommandRef::with_params(OPTION, json!({ "option": name }))
}
/// The panel (≡) menu's rows: copy and export, Generate CSS and the export options.
pub(crate) fn menu_rows(app: &VectorcraftApp) -> Vec<PanelRow> {
let units = crate::i18n::fmt(tl!("Units: {units}"), &[("units", app.ui.css_properties_panel.options.units.name())]);
let mut rows = vec![
PanelRow::Command(CommandRef::new(COPY_SELECTED)),
PanelRow::Command(CommandRef::new(EXPORT_SELECTED)),
PanelRow::Command(CommandRef::new(EXPORT_ALL)),
PanelRow::Separator,
PanelRow::Command(CommandRef::new(GENERATE)),
PanelRow::Separator,
PanelRow::Submenu(units.into(), CssUnits::ALL.iter().map(|u| PanelRow::Command(units_ref(*u))).collect()),
];
rows.extend(FLAGS.iter().map(|name| PanelRow::Command(option_ref(name))));
rows
}
/// The rows' states: the copy and export of the selection need a selection, Export All and Generate CSS a
/// document; Generate CSS, the units and the options show what is set.
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let panel = &app.ui.css_properties_panel;
let selection = app.session.active().map(|st| !st.selection.is_empty());
let (has_doc, selected) = (selection.is_some(), selection == Some(true));
states.set(CommandRef::new(COPY_SELECTED), CommandState::new().enabled(selected));
states.set(CommandRef::new(EXPORT_SELECTED), CommandState::new().enabled(selected));
states.set(CommandRef::new(EXPORT_ALL), CommandState::new().enabled(has_doc));
states.set(CommandRef::new(GENERATE), CommandState::new().enabled(has_doc).checked(panel.all));
for units in CssUnits::ALL {
states.set(units_ref(units), CommandState::new().checked(panel.options.units == units));
}
let mut options = panel.options.clone();
for name in FLAGS {
let on = flag_mut(&mut options, name).is_some_and(|on| *on);
states.set(option_ref(name), CommandState::new().checked(on));
}
}
/// The panel menu's `ui.cssProperties.*` commands; `None` for any other id.
pub(crate) fn run(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
let name = id.strip_prefix("ui.cssProperties.")?;
let opts = app.ui.css_properties_panel.options.clone();
Some(match name {
"copySelected" => copy(app, &params(&opts, "selection")),
"exportSelected" => export_file(app, &params(&opts, "selection")),
"exportAll" => export_file(app, &params(&opts, "all")),
"generate" => {
let panel = &mut app.ui.css_properties_panel;
panel.all = !panel.all;
Ok(json!({ "all": panel.all }))
}
"units" => serde_json::from_value::<CssUnits>(p["units"].clone()).map_err(|_| "units: px, pt, mm, cm or in".to_string()).map(|units| {
app.ui.css_properties_panel.options.units = units;
json!({ "units": units })
}),
"option" => match p["option"].as_str().and_then(|n| flag_mut(&mut app.ui.css_properties_panel.options, n)) {
Some(on) => {
*on = !*on;
Ok(json!({ "on": *on }))
}
None => Err(format!("option: one of {}", FLAGS.join(", "))),
},
_ => return None,
})
}
+134 -117
View File
@@ -6,116 +6,156 @@
//! remove them; Link JavaScript Files… opens the JavaScript Files dialog (`ui.javascriptFilesDialog`).
//! Everything reads `svgInteractivity.info`.
use craft::behavior::{IconId, Selection, keyed};
use craft::keymap::CommandRef;
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing};
use craft::ui::display::{Shade, Text};
use craft::ui::form::Field;
use craft::ui::list::{List, ListRow};
use craft::ui::menu::PanelRow;
use craft::ui::pickers::Select;
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::sections::{FooterAction, FooterBar};
use craft::ui::text::TextField;
use egui::Ui;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, SVG_EVENTS};
use super::{pstate, selection_len, set_pstate};
use super::selection_len;
use crate::VectorcraftApp;
use crate::widgets::{self, menu_item};
pub const ID: &str = "svgInteractivity";
/// Panel state: the event picked (an entry of [`SVG_EVENTS`]).
const EVENT: &str = "svgi-event";
const LABEL_W: f32 = 70.0;
/// The engine command of the panel menu's one row.
const CLEAR_EVENTS: &str = "svgInteractivity.clearEvents";
/// The panel's values: whether there are targets, and their events (`None` where they differ).
#[derive(Clone, Debug, Default)]
struct Info {
pub(crate) struct Info {
has: bool,
events: Option<Vec<(String, String)>>,
}
/// `svgInteractivity.info`, read again only when the document or the selection changes.
fn state(app: &mut VectorcraftApp, ctx: &egui::Context) -> Info {
type Key = (u64, u64, usize, Option<NodeId>, Option<NodeId>);
let Some(st) = app.session.active() else { return Info::default() };
/// What [`info`] was read for: (document uid, revision, selection size, first and last selected object).
pub(crate) type SelKey = (u64, u64, usize, Option<NodeId>, Option<NodeId>);
/// A side label's text without its colon: the label draws the colon itself
/// (`CommonWords::caption`), so the catalog's "Event:" keeps its translation here.
// PLAN: the catalog keys carry the colon the side label now adds; strip it where a label is given.
pub(crate) fn caption(label: &'static str) -> &'static str {
crate::i18n::t(label).trim_end_matches(':')
}
fn sel_key(app: &VectorcraftApp) -> Option<SelKey> {
let st = app.session.active()?;
let sel = &st.selection.objects;
let key: Key = (st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied());
let id = egui::Id::unique("svgi-state");
if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, Info)>(id))
&& k == key
{
return v;
Some((st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied()))
}
/// The memoized [`Info`] when it was read for the current document and selection.
fn cached(app: &VectorcraftApp) -> Option<&Info> {
let key = sel_key(app)?;
app.canvas.svg_info.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v)
}
/// `svgInteractivity.info`, read again only when the document or the selection changes.
pub(crate) fn info(app: &mut VectorcraftApp) -> Info {
if let Some(v) = cached(app) {
return v.clone();
}
let Some(key) = sel_key(app) else { return Info::default() };
let r = app.session.execute("svgInteractivity.info", &json!({})).unwrap_or_default();
let events = r["events"]
.as_array()
.map(|a| a.iter().filter_map(|e| Some((e["event"].as_str()?.to_string(), e["script"].as_str()?.to_string()))).collect::<Vec<_>>());
let v = Info { has: r["ids"].as_array().is_some_and(|a| !a.is_empty()), events };
ctx.data_mut(|d| d.insert_temp(id, (key, v.clone())));
app.canvas.svg_info = Some((key, v.clone()));
v
}
/// The event picked in the panel (the first of [`SVG_EVENTS`] until one is).
fn picked(ctx: &egui::Context) -> &'static str {
let e: String = pstate(ctx, EVENT);
fn picked(app: &VectorcraftApp) -> &'static str {
let e = app.ui.svg_interactivity_panel.event.as_str();
SVG_EVENTS.iter().find(|n| **n == e).copied().unwrap_or(SVG_EVENTS[0])
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
let info = state(app, &ctx);
let event = picked(&ctx);
let events = info.events.clone().unwrap_or_default();
widgets::label_row(ui, tl!("Event:"), LABEL_W, |ui| {
ui.add_enabled_ui(info.has, |ui| {
let width = (ui.available_width() - 4.0).max(80.0);
if let Some(i) = widgets::dropdown_names(ui, "svgi-event", event, &SVG_EVENTS, width) {
set_pstate(&ctx, EVENT, SVG_EVENTS.get(i).copied().unwrap_or(event).to_string());
}
});
let info = info(app);
let event = picked(app);
let events = info.events.as_deref().unwrap_or_default();
let names: Vec<Entry<String>> = SVG_EVENTS.iter().map(|e| Entry::new((*e).to_string(), *e)).collect();
let mut pick = None;
Field::new(caption("Event:")).show(ui, |ui, _| {
let out = Select::new(caption("Event:"), Bind::given(event.to_string()), &names).enabled(info.has).show(ui);
pick = out.events.committed().cloned();
});
// Blank where the objects' events differ; empty where none of them has the event.
let script = info.events.as_ref().map(|l| l.iter().find(|(e, _)| e == event).map_or("", |(_, js)| js.as_str()));
widgets::label_row(ui, tl!("JavaScript:"), LABEL_W, |ui| {
ui.add_enabled_ui(info.has, |ui| {
let width = (ui.available_width() - 4.0).max(80.0);
if let Some(js) = widgets::text_field(ui, ("svgi-script", event), script, width, 1) {
app.run("svgInteractivity.setEvent", json!({ "event": event, "script": js })).ok();
}
});
let shown = script.unwrap_or_default();
let mut typed = None;
Field::new(caption("JavaScript:")).show(ui, |ui, _| {
let out = TextField::new(caption("JavaScript:"), Bind::given(shown.to_string())).lines(3).id_salt(event).enabled(info.has).show(ui);
typed = out.events.committed().filter(|js| js.as_str() != shown).cloned();
});
ui.add_space(4.0);
widgets::list_box(ui, |ui| {
egui::ScrollArea::vertical().id_salt("svgi-events").max_height(160.0).auto_shrink([false, true]).show(ui, |ui| {
ui.set_min_height(90.0);
for (e, js) in &events {
// Event names and scripts are data: shown as they are.
if ui.selectable_label(e == event, format!("{e}: {js}")).clicked() {
set_pstate(&ctx, EVENT, e.clone());
}
}
let source = keyed(events, |(e, _): &(String, String)| e.clone());
let selection = events.iter().any(|(e, _)| e == event).then(|| Selection::single(event.to_string())).unwrap_or_default();
let list = List::<String>::options(tl!("Events"))
.selection(Bind::given(selection))
.sizing(Sizing::Fill)
// Event names and scripts are data: shown as they are.
.show_items(ui, &source, &mut |key, _| {
let js = events.iter().find(|(e, _)| e == key).map_or("", |(_, js)| js.as_str());
ListRow::new(format!("{key}: {js}"))
});
});
if !info.has {
widgets::dim_label(ui, if selection_len(app) == 0 { tl!("No Selection") } else { "" });
for e in list.events {
if let CollectionEvent::Activate(key) = e {
pick = Some(key);
}
}
if !info.has && selection_len(app) == 0 {
Text::new(tl!("No Selection")).shade(Shade::Muted).show(ui);
}
let has_doc = app.session.active().is_some();
let listed = events.iter().any(|(e, _)| e == event);
let (mut link, mut remove) = (false, false);
widgets::bottom_bar(ui, |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
remove = widgets::icon_button_enabled(ui, "trash-2", tl!("Remove Selected Entry"), false, listed, 24.0).clicked();
link = widgets::icon_button_enabled(ui, "file-plus", tl!("Link JavaScript Files…"), false, has_doc, 24.0).clicked();
});
});
if remove {
app.run("svgInteractivity.removeEvent", json!({ "event": event })).ok();
let footer = FooterBar::actions([
FooterAction::new(IconId::new("trash"), tl!("Remove Selected Entry")).enabled(listed),
FooterAction::new(IconId::new("new_file"), tl!("Link JavaScript Files…")).enabled(has_doc),
])
.show_footer(ui);
if let Some(e) = pick {
app.ui.svg_interactivity_panel.event = e;
}
if link {
crate::menus::invoke(app, "ui.javascriptFilesDialog", json!({}));
if let Some(js) = typed {
app.run("svgInteractivity.setEvent", json!({ "event": event, "script": js })).ok();
}
match footer.picked {
Some(0) => {
app.run("svgInteractivity.removeEvent", json!({ "event": event })).ok();
}
Some(1) => {
crate::menus::invoke(app, "ui.javascriptFilesDialog", json!({}));
}
_ => {}
}
}
/// The panel (≡) menu: Clear Events.
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let info = state(app, ui.ctx());
/// The panel (≡) menu's rows: Clear Events.
pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
vec![PanelRow::Command(CommandRef::new(CLEAR_EVENTS))]
}
/// Clear Events is on while the objects have events. The panel reads the events each frame it shows; a
/// panel that is not shown leaves the row off.
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
// (Where the objects' events differ, some of them have events.)
let any = info.has && info.events.as_ref().is_none_or(|l| !l.is_empty());
if menu_item(ui, tl!("Clear Events"), any, false) {
app.run("svgInteractivity.clearEvents", json!({})).ok();
}
let any = cached(app).is_some_and(|info| info.has && info.events.as_ref().is_none_or(|l| !l.is_empty()));
states.set(CommandRef::new(CLEAR_EVENTS), CommandState::new().enabled(any));
}
/// The panel's own `ui.svgInteractivity.*` commands: it has none, because its menu row is the engine
/// command `svgInteractivity.clearEvents`.
pub(crate) fn run(_app: &mut VectorcraftApp, _id: &str, _params: &Value) -> Option<Result<Value, String>> {
None
}
/// `ui.javascriptFilesDialog {}`: open the JavaScript Files dialog for the active document.
@@ -126,69 +166,46 @@ pub(crate) fn files_dialog(app: &mut VectorcraftApp, _p: &Value) -> Result<Value
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::panel_harness::Panel;
use vectorcraft_engine::Session;
/// Run the panel and its menu for one headless frame of `ctx`: the texts drawn.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
match s {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
show(app, ui);
menu(app, ui);
});
out.textures_delta.clear();
let mut v = vec![];
out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));
v
}
fn run(app: &mut VectorcraftApp, id: &str, p: Value) -> Value {
app.session.execute(id, &p).unwrap()
}
/// Window › SVG Interactivity opens the panel, as Window's other panel items do.
#[test]
fn window_svg_interactivity_opens_the_panel() {
let app = VectorcraftApp::new(Session::new(), Default::default());
let entries = crate::menus::menu_entries(&app);
let panel = entries
.iter()
.find(|e| e.command.as_deref() == Some("window.panel") && e.params.get("panel").and_then(Value::as_str) == Some(ID))
.expect("the SVG Interactivity panel is listed");
assert_eq!((panel.path.clone(), panel.label.as_str(), panel.enabled), (vec!["Window".to_string()], "SVG Interactivity", true));
}
// (Only names and scripts are checked: they are shown as they are, while tests running
// alongside change the language the labels are drawn in.)
#[test]
fn panel_lists_the_selections_events() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let ctx = egui::Context::default();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let texts = frame(&mut app, &ctx);
assert!(texts.iter().any(|t| t == "onfocusin"), "the first event is picked: {texts:?}");
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "alert(1)"}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onmouseover", "script": "hover()"}));
let texts = frame(&mut app, &ctx);
for want in ["onclick: alert(1)", "onmouseover: hover()"] {
assert!(texts.iter().any(|t| t == want), "{want} in {texts:?}");
let mut panel = Panel::new(app, show);
panel.frame();
assert!(!panel.shows("onclick: alert(1)"), "nothing is selected");
{
let mut app = panel.app();
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "alert(1)"}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onmouseover", "script": "hover()"}));
}
panel.frame();
for want in ["onclick: alert(1)", "onmouseover: hover()"] {
assert!(panel.shows(want), "{want} is listed");
}
assert!(!texts.iter().any(|t| t == "alert(1)"), "{texts:?}");
// With an event picked, the field shows its script.
set_pstate(&ctx, EVENT, "onclick".to_string());
let texts = frame(&mut app, &ctx);
assert!(texts.iter().any(|t| t == "onclick") && texts.iter().any(|t| t == "alert(1)"), "{texts:?}");
panel.app().ui.svg_interactivity_panel.event = "onclick".into();
panel.frame();
assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("alert(1)"));
// Two objects whose events differ show none.
let b = run(&mut app, "shape.ellipse", json!({"x": 60, "y": 0, "width": 30, "height": 30}))["id"].clone();
let a = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id.0;
run(&mut app, "select.set", json!({"ids": [a, b]}));
let texts = frame(&mut app, &ctx);
assert!(!texts.iter().any(|t| t.starts_with("onclick:") || t == "alert(1)"), "{texts:?}");
{
let mut app = panel.app();
let b = run(&mut app, "shape.ellipse", json!({"x": 60, "y": 0, "width": 30, "height": 30}))["id"].clone();
let a = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id.0;
run(&mut app, "select.set", json!({"ids": [a, b]}));
}
panel.frame();
assert!(!panel.shows("onclick: alert(1)"));
assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some(""));
assert!(info(&mut panel.app()).events.is_none());
}
}
@@ -1,6 +1,6 @@
//! The CSS Properties panel drawn headless: the selection's CSS in the code view, Generate CSS
//! for the whole document, the export options in the panel menu, and Copy Selected Style and
//! Export through their UI commands.
//! for the whole document, the export options, and Copy Selected Style and Export through their UI
//! commands.
use std::cell::RefCell;
use std::rc::Rc;
@@ -9,11 +9,13 @@ use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_svg::{CssOptions, CssUnits};
use super::css_properties::{ALL, ID, OPTIONS, menu, show};
use super::set_pstate;
use crate::tests_labels::painted_text;
use super::css_properties::show;
use crate::tests::panel_harness::Panel;
use crate::{Services, VectorcraftApp};
/// The accessible name of the code view.
const CODE: &str = "CSS code";
type Log = Rc<RefCell<Vec<(String, Vec<u8>)>>>;
/// An app with a selected red 30 × 20 rectangle; files written go to the log.
@@ -36,14 +38,14 @@ fn app() -> (VectorcraftApp, Log) {
#[test]
fn the_code_view_shows_the_selections_css_with_the_options() {
let (mut app, _) = app();
assert!(crate::state::ICON_PANELS.iter().any(|(id, ..)| *id == ID));
let text = painted_text(&mut app, show);
let (app, _) = app();
let mut panel = Panel::new(app, show);
panel.frame();
let text = panel.value(CODE).unwrap_or_default();
assert!(text.contains(".rectangle {") && text.contains("background-color: #ff0000;") && text.contains("width: 30px;"), "{text}");
let text = painted_text(&mut app, |app, ui| {
set_pstate(ui.ctx(), OPTIONS, CssOptions { units: CssUnits::Pt, position: true, ..CssOptions::default() });
show(app, ui);
});
panel.app().ui.css_properties_panel.options = CssOptions { units: CssUnits::Pt, position: true, ..CssOptions::default() };
panel.frame();
let text = panel.value(CODE).unwrap_or_default();
assert!(text.contains("width: 30pt;") && text.contains("left: 10pt;"), "{text}");
}
@@ -52,61 +54,15 @@ fn generate_css_shows_the_document_while_nothing_is_selected() {
let (mut app, _) = app();
app.run("shape.ellipse", json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("select.none", json!({})).unwrap();
let text = painted_text(&mut app, show);
assert!(text.contains("No selection") && !text.contains(".rectangle"), "{text}");
let text = painted_text(&mut app, |app, ui| {
set_pstate(ui.ctx(), ALL, true);
show(app, ui);
});
let mut panel = Panel::new(app, show);
panel.frame();
assert!(panel.shows("No selection") && !panel.shows(CODE), "the empty state");
panel.app().run("ui.cssProperties.generate", json!({})).unwrap();
panel.frame();
let text = panel.value(CODE).unwrap_or_default();
assert!(text.contains(".rectangle {") && text.contains(".ellipse {") && text.contains("border-radius: 50%;"), "{text}");
}
/// The note on unnamed objects left out uses the form the language's plural rule picks for the
/// count.
#[test]
fn the_unnamed_objects_note_uses_each_count_form() {
let note = |code: &str, n: u64| {
let (mut app, _) = app();
for i in 1..n {
app.run("shape.rectangle", json!({"x": 10 + 40 * i, "y": 50, "width": 30, "height": 20})).unwrap();
}
app.run("select.all", json!({})).unwrap();
crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap());
let text = painted_text(&mut app, |app, ui| {
set_pstate(ui.ctx(), OPTIONS, CssOptions { unnamed: false, ..CssOptions::default() });
show(app, ui);
});
crate::i18n::set_current(crate::i18n::Lang::EN);
text
};
let text = note("en", 1);
assert!(text.contains("1 unnamed object left out: name it,"), "{text}");
for (n, want) in [(1, "Vynechán 1 nepojmenovaný objekt."), (2, "Vynechány 2 nepojmenované objekty."), (5, "Vynecháno 5 nepojmenovaných objektů.")]
{
let text = note("cs", n);
assert!(text.contains(want), "{n}: {text}");
}
}
#[test]
fn the_panel_menu_lists_the_actions_and_options() {
let (mut app, _) = app();
let text = painted_text(&mut app, menu);
for item in [
"Copy Selected Style",
"Export Selected CSS…",
"Export All…",
"Generate CSS",
"Units: px",
"Absolute Position",
"Width and Height",
"Unnamed Objects",
"Rasterize Unsupported Art",
] {
assert!(text.contains(item), "{item} in {text}");
}
}
#[test]
fn copy_and_export_go_through_the_ui_commands() {
let (mut app, log) = app();