Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

O: Object Library — .dclib files of snippets, Library panel

Brandon Thomas68e624cba4aa
diff --git a/ROADMAP.md b/ROADMAP.md
index ff642f582..511f5d90b 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -52,6 +52,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Edit ▸ Transparency Blend Space (`edit.transparencyBlendSpace`; RGB for web/mobile documents; IDML TransparencyPreference) — stored; compositing is still RGB on screen and in PDF.
- High Contrast interface theme (fifth Interface Color Theme: black chrome, white text, yellow selection).
- Place Excel workbooks (.xlsx): the first worksheet's used range becomes a table (shared/inline strings, numbers, booleans).
+- Object Library (`library.new/open/add/place/remove/list/json/close`, Library panel): `.dclib` files of snippets that keep stories, styles, swatches and images.
- Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).
- Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.
- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.
diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs
index a1d753c6a..046ffd1a6 100644
--- a/apps/designcraft/src/main.rs
+++ b/apps/designcraft/src/main.rs
@@ -83,6 +83,8 @@ fn services() -> Services {
let d = rfd::FileDialog::new();
let d = if purpose == "swatches" {
d.add_filter("Swatch Exchange (ASE)", &["ase"])
+ } else if purpose == "library" {
+ d.add_filter("Object Library", &["dclib"])
} else if purpose == "place" {
d.add_filter(
"Graphics and text",
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 14e798cff..3b873462e 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -394,6 +394,11 @@ fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
Ok(r)
}
+/// The selection as `.designcraft` snippet bytes.
+pub(crate) fn snippet_bytes(s: &mut Session) -> Result<Vec<u8>> {
+ Ok(to_bytes(&super::edit::clip_doc(s)?))
+}
+
fn snippet_export(s: &mut Session, p: &Value) -> Result<Value> {
let d = super::edit::clip_doc(s)?;
let bytes = to_bytes(&d);
@@ -407,7 +412,7 @@ fn snippet_export(s: &mut Session, p: &Value) -> Result<Value> {
}
}
-fn snippet_place(s: &mut Session, p: &Value) -> Result<Value> {
+pub(crate) fn snippet_place(s: &mut Session, p: &Value) -> Result<Value> {
let (bytes, _, _) = read_source(p)?;
let src = from_bytes(&bytes)?;
let ids: Vec<ItemId> = src.spreads.first().map(|sp| sp.items.iter().map(|i| i.id).collect()).unwrap_or_default();
diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs
new file mode 100644
index 000000000..e0ecc7383
--- /dev/null
+++ b/crates/engine/src/cmd/library.rs
@@ -0,0 +1,156 @@
+//! Object Library: a file of reusable objects (each a snippet: items with their stories, styles,
+//! swatches and images). New, open, add the selection, place, remove; saved as `.dclib` JSON.
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use super::{CommandSpec, always, bad, cmd, has_doc, has_selection, ok, str_param};
+use crate::{Result, Session};
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LibraryItem {
+ pub name: String,
+ pub description: String,
+ /// A `.designcraft` snippet, base64.
+ pub snippet: String,
+}
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Library {
+ #[serde(skip)]
+ pub path: Option<String>,
+ pub items: Vec<LibraryItem>,
+}
+
+impl Library {
+ fn save(&self) -> Result<()> {
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Some(p) = &self.path {
+ let bytes = serde_json::to_vec_pretty(self).map_err(|e| crate::EngineError::Other(e.to_string()))?;
+ std::fs::write(p, bytes).map_err(|e| crate::EngineError::Other(format!("{p}: {e}")))?;
+ }
+ Ok(())
+ }
+}
+
+fn has_library(s: &Session) -> std::result::Result<(), String> {
+ if s.library.is_some() { Ok(()) } else { Err("no library open".into()) }
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(noundo "library.new", "New Library", ["File", "New"], None, "{path?} — an empty Object Library (saved to `path` when given)", always, |s, p| {
+ let lib = Library { path: str_param(p, "path").map(str::to_string), items: vec![] };
+ lib.save()?;
+ s.library = Some(lib);
+ ok()
+ }),
+ cmd!(noundo "library.open", "Open Library", [], None, "{path | json} → {items}", always, |s, p| {
+ let (text, path) = match (str_param(p, "json"), str_param(p, "path")) {
+ (Some(j), _) => (j.to_string(), None),
+ (None, Some(path)) => {
+ #[cfg(not(target_arch = "wasm32"))]
+ let t = std::fs::read_to_string(path).map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))?;
+ #[cfg(target_arch = "wasm32")]
+ let t = String::new();
+ (t, Some(path.to_string()))
+ }
+ _ => return Err(bad("library.open", "`path` or `json` required")),
+ };
+ let mut lib: Library = serde_json::from_str(&text).map_err(|e| bad("library.open", format!("not a library: {e}")))?;
+ lib.path = path;
+ let n = lib.items.len();
+ s.library = Some(lib);
+ Ok(json!({"items": n}))
+ }),
+ cmd!(query "library.list", "Library Items", [], None, "{} → [{index, name, description}]", has_library, |s, _| {
+ let lib = s.library.as_ref().expect("enabled");
+ Ok(Value::Array(lib.items.iter().enumerate().map(|(i, it)| json!({"index": i, "name": it.name, "description": it.description})).collect()))
+ }),
+ cmd!(query "library.json", "Library Contents", [], None, "{} → the library as JSON text (to save where there's no file system)", has_library, |s, _| {
+ Ok(json!({"json": serde_json::to_string(s.library.as_ref().expect("enabled")).unwrap_or_default()}))
+ }),
+ cmd!(noundo "library.add", "Add Item", [], None, "{name?, description?} — the selection → {index}", has_selection, |s, p| {
+ has_library(s).map_err(|e| bad("library.add", e))?;
+ let snip = super::file::snippet_bytes(s)?;
+ let (name, description) = {
+ let st = s.doc()?;
+ let first = st.selection.items.first().and_then(|id| st.doc.item(*id));
+ let kind = first.map(|it| if !it.label.is_empty() { it.label.clone() } else { it.default_label().trim_matches(|c| c == '<' || c == '>').to_string() }).unwrap_or_default();
+ let n = st.selection.items.len();
+ (str_param(p, "name").map(str::to_string).unwrap_or_else(|| if n > 1 { format!("{n} objects") } else { kind.clone() }), str_param(p, "description").unwrap_or("").to_string())
+ };
+ let lib = s.library.as_mut().expect("checked");
+ lib.items.push(LibraryItem { name, description, snippet: super::file::base64_encode(&snip) });
+ lib.save()?;
+ Ok(json!({"index": lib.items.len() - 1}))
+ }),
+ cmd!(
+ "library.place",
+ "Place Item",
+ [],
+ None,
+ "{index, spread?, x?, y?} — at its original position unless x/y (top-left) are given",
+ has_doc,
+ |s, p| {
+ let lib = s.library.as_ref().ok_or_else(|| bad("library.place", "no library open"))?;
+ let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("library.place", "`index` required"))? as usize;
+ let it = lib.items.get(i).ok_or_else(|| bad("library.place", format!("no item {i}")))?;
+ let mut q = p.clone();
+ q["base64"] = json!(it.snippet);
+ super::file::snippet_place(s, &q)
+ }
+ ),
+ cmd!(noundo "library.remove", "Delete Item", [], None, "{index}", has_library, |s, p| {
+ let lib = s.library.as_mut().expect("enabled");
+ let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("library.remove", "`index` required"))? as usize;
+ if i >= lib.items.len() {
+ return Err(bad("library.remove", format!("no item {i}")));
+ }
+ lib.items.remove(i);
+ lib.save()?;
+ ok()
+ }),
+ cmd!(noundo "library.close", "Close Library", [], None, "{}", has_library, |s, _| {
+ s.library = None;
+ ok()
+ }),
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn library_round_trip() {
+ let dir = std::env::temp_dir().join(format!("dc-lib-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("brand.dclib").to_string_lossy().to_string();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("library.new", &json!({"path": path})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 172, 122], "content": "text", "text": "Logo", "caret": false})).unwrap();
+ s.execute("library.add", &json!({"name": "Logo block"})).unwrap();
+ // A fresh session opens the saved library and places the item into another document.
+ let mut t = Session::new();
+ t.execute("file.new", &json!({})).unwrap();
+ t.execute("library.open", &json!({"path": path})).unwrap();
+ assert_eq!(t.execute("library.list", &json!({})).unwrap()[0]["name"], "Logo block");
+ let placed = t.execute("library.place", &json!({"index": 0, "x": 300, "y": 300})).unwrap();
+ let id = designcraft_doc::ItemId(placed["ids"][0].as_u64().unwrap());
+ let d = &t.doc().unwrap().doc;
+ let it = d.item(id).unwrap();
+ assert_eq!((it.bounds().x0, it.bounds().y0), (300.0, 300.0));
+ let sid = it.text_frame().unwrap().story;
+ assert_eq!(d.stories[&sid].text, "Logo");
+ let _ = r;
+ t.execute("library.remove", &json!({"index": 0})).unwrap();
+ assert!(t.execute("library.list", &json!({})).unwrap().as_array().unwrap().is_empty());
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 5c2ef84dc..a62a14a85 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -18,6 +18,7 @@ mod inspect;
mod interactive;
pub mod interchange;
mod layout;
+pub mod library;
mod links;
mod lists;
mod notes;
@@ -142,6 +143,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(paths::specs());
v.extend(captions::specs());
v.extend(conditions::specs());
+ v.extend(library::specs());
v.extend(lists::specs());
v.extend(path_type::specs());
v.extend(qr::specs());
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 940654cd4..c3bfe282e 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -192,6 +192,8 @@ pub struct Session {
pub(crate) transforms: (Vec<(String, Value)>, Vec<designcraft_doc::ItemId>, bool),
/// Drag and drop text editing: the press landed in the selected text.
pub(crate) text_drag: bool,
+ /// The open Object Library (File › New / Open Library).
+ pub library: Option<cmd::library::Library>,
}
impl Default for Session {
@@ -216,6 +218,7 @@ impl Session {
loaded: None,
transforms: Default::default(),
text_drag: false,
+ library: None,
untitled: 0,
}
}
diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs
index 9e98064be..76ee54b36 100644
--- a/crates/ui-egui/src/dock.rs
+++ b/crates/ui-egui/src/dock.rs
@@ -32,6 +32,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[
("attributes", "Attributes", "panel-attributes"),
("conditions", "Conditional Text", "panel-conditions"),
("notes", "Notes", "panel-notes"),
+ ("library", "Library", "panel-library"),
];
pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
@@ -169,6 +170,7 @@ pub fn panel_body(app: &mut DesignApp, ui: &mut egui::Ui, id: &str) {
"attributes" => panels::properties::attributes_panel(app, ui),
"conditions" => panels::conditions::show(app, ui),
"notes" => panels::notes::show(app, ui),
+ "library" => panels::library::show(app, ui),
"table" => panels::table::show(app, ui),
_ => panels::properties::info_panel(app, ui),
}
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index 478a38ad5..947cd410e 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -310,6 +310,12 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
pen.circle(10.0, 10.0, 7.0);
pen.line(&[(6.5, 10.0), (9.0, 12.5), (13.5, 7.5)]);
}
+ "panel-library" => {
+ // Books on a shelf.
+ pen.rect(3.0, 4.0, 7.0, 16.0);
+ pen.rect(8.0, 6.0, 12.0, 16.0);
+ pen.line(&[(13.0, 6.5), (17.0, 5.0), (17.5, 15.5), (13.5, 16.5)]);
+ }
"panel-notes" => {
// A note with a folded corner.
pen.closed(&[(4.0, 3.0), (16.0, 3.0), (16.0, 13.0), (12.0, 17.0), (4.0, 17.0)]);
diff --git a/crates/ui-egui/src/panels/library.rs b/crates/ui-egui/src/panels/library.rs
new file mode 100644
index 000000000..52f936094
--- /dev/null
+++ b/crates/ui-egui/src/panels/library.rs
@@ -0,0 +1,54 @@
+//! Object Library panel: the open library's items; add the selection, place or delete an item;
+//! New / Open library.
+
+use serde_json::json;
+
+use crate::DesignApp;
+use crate::theme::Tokens;
+
+pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ ui.horizontal(|ui| {
+ if ui.button("New Library…").clicked() {
+ let path = app.services.pick_save.as_mut().and_then(|f| f("Library.dclib"));
+ let _ = app.run("library.new", json!({"path": path}));
+ }
+ if ui.button("Open…").clicked()
+ && let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("library"))
+ && let Err(e) = app.run("library.open", json!({"path": path}))
+ {
+ app.status(format!("Library: {e}"));
+ }
+ });
+ let Ok(items) = app.session.execute("library.list", &json!({})) else {
+ ui.label(egui::RichText::new("No library open.").size(11.0).color(t.text_dim));
+ return;
+ };
+ let has_sel = app.session.active().is_some_and(|d| !d.selection.items.is_empty());
+ if ui.add_enabled(has_sel, egui::Button::new("Add Selection")).clicked()
+ && let Err(e) = app.run("library.add", json!({}))
+ {
+ app.status(format!("Library: {e}"));
+ }
+ ui.separator();
+ let items = items.as_array().cloned().unwrap_or_default();
+ if items.is_empty() {
+ ui.label(egui::RichText::new("The library is empty. Select objects and Add Selection.").size(11.0).color(t.text_dim));
+ }
+ for it in items {
+ let i = it["index"].clone();
+ ui.horizontal(|ui| {
+ ui.label(it["name"].as_str().unwrap_or(""));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.small_button("Delete").clicked() {
+ let _ = app.run("library.remove", json!({"index": i}));
+ }
+ if ui.small_button("Place").clicked()
+ && let Err(e) = app.run("library.place", json!({"index": i}))
+ {
+ app.status(format!("Library: {e}"));
+ }
+ });
+ });
+ }
+}
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index 647c5ba45..3aa343b64 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -3,6 +3,7 @@
pub mod conditions;
pub mod glyphs;
pub mod layers;
+pub mod library;
pub mod notes;
pub mod pages;
pub mod properties;
diff --git a/docs/parity.md b/docs/parity.md
index cb57ad02a..190c81e34 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -11,7 +11,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
|---|---|---|---|---|---|
| P0 | 102 | 99 | 3 | 0 | 99% |
| P1 | 97 | 75 | 21 | 1 | 88% |
-| P2 | 76 | 21 | 13 | 42 | 36% |
+| P2 | 76 | 22 | 13 | 41 | 38% |
| Area | Parity |
|---|---|
@@ -30,7 +30,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
| Long documents | 88% |
| Interactivity & digital | 45% |
| Output & production | 75% |
-| XML & automation | 50% |
+| XML & automation | 61% |
| View & navigation | 82% |
| Undo, history, saving | 100% |
| Accessibility | 70% |
@@ -295,7 +295,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t
| XML & automation | Script Label | P2 | D |
| XML & automation | Content Collector/Placer | P2 | M |
| XML & automation | Snippets | P1 | D |
-| XML & automation | Object Library | P2 | M |
+| XML & automation | Object Library | P2 | D |
| View & navigation | Zoom commands | P0 | D |
| View & navigation | Power Zoom | P2 | M |
| View & navigation | Animated/scrubby zoom | P1 | D |