jackdaw 0.3.0

A 3D level editor built with Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use crate::commands::{CommandHistory, EditorCommand};
use crate::custom_properties::{CustomProperties, PropertyValue, SetCustomProperties};

use bevy::prelude::*;
use bevy::ui_widgets::observe;
use jackdaw_feathers::combobox::{ComboBoxSelectedIndex, combobox_with_selected};
use jackdaw_feathers::{
    checkbox::{CheckboxCommitEvent, CheckboxProps, checkbox},
    color_picker::{ColorPickerCommitEvent, ColorPickerProps, color_picker},
    icons::Icon,
    text_edit::{self, TextEditCommitEvent, TextEditProps, TextEditValue},
    tokens,
};

use crate::colors;

use super::{
    CustomPropertyAddRow, CustomPropertyBinding, CustomPropertyNameInput,
    CustomPropertyTypeSelector, rebuild_inspector,
};

pub(super) fn spawn_custom_properties_display(
    commands: &mut Commands,
    parent: Entity,
    source_entity: Entity,
    cp: &CustomProperties,
    editor_font: &Handle<Font>,
    icon_font: &Handle<Font>,
) {
    // Render each property row based on its variant type
    for (prop_name, prop_value) in &cp.properties {
        let row = commands
            .spawn((
                Node {
                    flex_direction: FlexDirection::Row,
                    align_items: AlignItems::Center,
                    column_gap: px(tokens::SPACING_XS),
                    width: Val::Percent(100.0),
                    ..Default::default()
                },
                ChildOf(parent),
            ))
            .id();

        // Property name label
        commands.spawn((
            Text::new(format!("{}:", prop_name)),
            TextFont {
                font: editor_font.clone(),
                font_size: tokens::FONT_SM,
                ..Default::default()
            },
            Node {
                min_width: px(20.0),
                flex_shrink: 0.0,
                ..Default::default()
            },
            TextColor(tokens::TEXT_PRIMARY),
            ChildOf(row),
        ));

        let name = prop_name.clone();
        match prop_value {
            PropertyValue::Bool(val) => {
                let checked = *val;
                commands.spawn((
                    checkbox(
                        CheckboxProps::new("").checked(checked),
                        editor_font,
                        icon_font,
                    ),
                    CustomPropertyBinding {
                        source_entity,
                        property_name: name,
                    },
                    ChildOf(row),
                ));
            }
            PropertyValue::Int(val) => {
                commands.spawn((
                    text_edit::text_edit(
                        TextEditProps::default()
                            .numeric_f32()
                            .grow()
                            .with_default_value((*val).to_string()),
                    ),
                    CustomPropertyBinding {
                        source_entity,
                        property_name: name,
                    },
                    ChildOf(row),
                ));
            }
            PropertyValue::Float(val) => {
                commands.spawn((
                    text_edit::text_edit(
                        TextEditProps::default()
                            .numeric_f32()
                            .grow()
                            .with_default_value(val.to_string()),
                    ),
                    CustomPropertyBinding {
                        source_entity,
                        property_name: name,
                    },
                    ChildOf(row),
                ));
            }
            PropertyValue::String(val) => {
                commands.spawn((
                    text_edit::text_edit(
                        TextEditProps::default()
                            .grow()
                            .with_default_value(val.clone())
                            .allow_empty(),
                    ),
                    CustomPropertyBinding {
                        source_entity,
                        property_name: name,
                    },
                    ChildOf(row),
                ));
            }
            PropertyValue::Vec2(val) => {
                let v = *val;
                let n_x = name.clone();
                let n_y = name.clone();
                spawn_custom_axis(
                    commands,
                    row,
                    "X",
                    v.x as f64,
                    colors::INSPECTOR_AXIS_X,
                    source_entity,
                    n_x,
                    |new_f, old| {
                        if let PropertyValue::Vec2(v) = old {
                            v.x = new_f as f32;
                        }
                    },
                );
                spawn_custom_axis(
                    commands,
                    row,
                    "Y",
                    v.y as f64,
                    colors::INSPECTOR_AXIS_Y,
                    source_entity,
                    n_y,
                    |new_f, old| {
                        if let PropertyValue::Vec2(v) = old {
                            v.y = new_f as f32;
                        }
                    },
                );
            }
            PropertyValue::Vec3(val) => {
                let v = *val;
                let n_x = name.clone();
                let n_y = name.clone();
                let n_z = name.clone();
                spawn_custom_axis(
                    commands,
                    row,
                    "X",
                    v.x as f64,
                    colors::INSPECTOR_AXIS_X,
                    source_entity,
                    n_x,
                    |new_f, old| {
                        if let PropertyValue::Vec3(v) = old {
                            v.x = new_f as f32;
                        }
                    },
                );
                spawn_custom_axis(
                    commands,
                    row,
                    "Y",
                    v.y as f64,
                    colors::INSPECTOR_AXIS_Y,
                    source_entity,
                    n_y,
                    |new_f, old| {
                        if let PropertyValue::Vec3(v) = old {
                            v.y = new_f as f32;
                        }
                    },
                );
                spawn_custom_axis(
                    commands,
                    row,
                    "Z",
                    v.z as f64,
                    colors::INSPECTOR_AXIS_Z,
                    source_entity,
                    n_z,
                    |new_f, old| {
                        if let PropertyValue::Vec3(v) = old {
                            v.z = new_f as f32;
                        }
                    },
                );
            }
            PropertyValue::Color(val) => {
                let srgba = val.to_srgba();
                let rgba = [srgba.red, srgba.green, srgba.blue, srgba.alpha];
                let n = name.clone();
                commands
                    .spawn((
                        color_picker(ColorPickerProps::new().with_color(rgba)),
                        ChildOf(row),
                    ))
                    .observe(
                        move |event: On<ColorPickerCommitEvent>, mut commands: Commands| {
                            let color = event.color;
                            let n = n.clone();
                            commands.queue(move |world: &mut World| {
                                let new_color =
                                    Color::srgba(color[0], color[1], color[2], color[3]);
                                apply_custom_property_with_undo(
                                    world,
                                    source_entity,
                                    &n,
                                    PropertyValue::Color(new_color),
                                );
                            });
                        },
                    );
            }
        }

        // Remove property button (X icon)
        let n = prop_name.clone();
        commands.spawn((
            Text::new(String::from(Icon::X.unicode())),
            TextFont {
                font: icon_font.clone(),
                font_size: tokens::FONT_SM,
                ..Default::default()
            },
            TextColor(tokens::TEXT_SECONDARY),
            ChildOf(row),
            observe(move |_: On<Pointer<Click>>, mut commands: Commands| {
                let n = n.clone();
                commands.queue(move |world: &mut World| {
                    remove_custom_property(world, source_entity, &n);
                });
            }),
        ));
    }

    // "Add Property" row
    spawn_add_property_row(commands, parent, source_entity, editor_font, icon_font);
}

/// Marker that links a custom property axis input to its property name and mutation function.
#[derive(Component)]
pub(super) struct CustomAxisBinding {
    source_entity: Entity,
    property_name: String,
    mutate: fn(f64, &mut PropertyValue),
}

fn spawn_custom_axis(
    commands: &mut Commands,
    parent: Entity,
    label: &str,
    value: f64,
    label_color: Color,
    source_entity: Entity,
    property_name: String,
    mutate: fn(f64, &mut PropertyValue),
) {
    commands.spawn((
        Text::new(label),
        TextFont {
            font_size: tokens::FONT_SM,
            ..Default::default()
        },
        TextColor(label_color),
        Node {
            flex_shrink: 0.0,
            ..Default::default()
        },
        ChildOf(parent),
    ));

    commands.spawn((
        text_edit::text_edit(
            TextEditProps::default()
                .numeric_f32()
                .grow()
                .with_default_value(value.to_string()),
        ),
        CustomAxisBinding {
            source_entity,
            property_name,
            mutate,
        },
        ChildOf(parent),
    ));
}

fn spawn_add_property_row(
    commands: &mut Commands,
    parent: Entity,
    source_entity: Entity,
    _editor_font: &Handle<Font>,
    icon_font: &Handle<Font>,
) {
    let row = commands
        .spawn((
            CustomPropertyAddRow,
            Node {
                flex_direction: FlexDirection::Row,
                align_items: AlignItems::Center,
                column_gap: px(tokens::SPACING_XS),
                width: Val::Percent(100.0),
                padding: UiRect::top(Val::Px(tokens::SPACING_SM)),
                ..Default::default()
            },
            ChildOf(parent),
        ))
        .id();

    // Name input
    commands.spawn((
        CustomPropertyNameInput,
        text_edit::text_edit(
            TextEditProps::default()
                .grow()
                .with_placeholder("name...")
                .allow_empty(),
        ),
        ChildOf(row),
    ));

    // Type selector ComboBox
    let type_names: Vec<String> = PropertyValue::all_type_names()
        .iter()
        .map(|s| s.to_string())
        .collect();
    commands.spawn((
        CustomPropertyTypeSelector,
        combobox_with_selected(type_names, 2), // default to "Float"
        ChildOf(row),
    ));

    // Confirm button
    let font = icon_font.clone();
    commands.spawn((
        Text::new(String::from(Icon::Plus.unicode())),
        TextFont {
            font,
            font_size: tokens::FONT_SM,
            ..Default::default()
        },
        TextColor(tokens::TEXT_ACCENT),
        ChildOf(row),
        observe(move |_: On<Pointer<Click>>, mut commands: Commands| {
            commands.queue(move |world: &mut World| {
                add_custom_property_from_ui(world, source_entity);
            });
        }),
    ));
}

/// Read the name input and type selector, then add a new property.
fn add_custom_property_from_ui(world: &mut World, source_entity: Entity) {
    // Read the name input value
    let name = {
        let mut query = world.query_filtered::<&TextEditValue, With<CustomPropertyNameInput>>();
        let Some(input) = query.iter(world).next() else {
            return;
        };
        let name = input.0.trim().to_string();
        if name.is_empty() {
            return;
        }
        name
    };

    // Read the type selector
    let type_name = {
        let mut query =
            world.query_filtered::<&ComboBoxSelectedIndex, With<CustomPropertyTypeSelector>>();
        let Some(index) = query.iter(world).next() else {
            return;
        };
        let all_types = PropertyValue::all_type_names();
        let idx = index.0.min(all_types.len().saturating_sub(1));
        all_types[idx].to_string()
    };

    let Some(default_value) = PropertyValue::default_for_type(&type_name) else {
        return;
    };

    let Some(cp) = world.get::<CustomProperties>(source_entity) else {
        return;
    };
    let old = cp.clone();
    let mut new = old.clone();
    new.properties.insert(name, default_value);

    let mut cmd = SetCustomProperties {
        entity: source_entity,
        old_properties: old,
        new_properties: new,
    };
    cmd.execute(world);

    let mut history = world.resource_mut::<CommandHistory>();
    history.undo_stack.push(Box::new(cmd));
    history.redo_stack.clear();

    // Rebuild inspector
    rebuild_inspector(world, source_entity);
}

/// Remove a property and push undo.
fn remove_custom_property(world: &mut World, source_entity: Entity, property_name: &str) {
    let Some(cp) = world.get::<CustomProperties>(source_entity) else {
        return;
    };
    let old = cp.clone();
    let mut new = old.clone();
    new.properties.remove(property_name);

    let mut cmd = SetCustomProperties {
        entity: source_entity,
        old_properties: old,
        new_properties: new,
    };
    cmd.execute(world);

    let mut history = world.resource_mut::<CommandHistory>();
    history.undo_stack.push(Box::new(cmd));
    history.redo_stack.clear();

    rebuild_inspector(world, source_entity);
}

/// Apply a custom property value change with undo.
fn apply_custom_property_with_undo(
    world: &mut World,
    source_entity: Entity,
    property_name: &str,
    new_value: PropertyValue,
) {
    let Some(cp) = world.get::<CustomProperties>(source_entity) else {
        return;
    };
    let old = cp.clone();
    let mut new = old.clone();
    new.properties.insert(property_name.to_string(), new_value);

    let mut cmd = SetCustomProperties {
        entity: source_entity,
        old_properties: old,
        new_properties: new,
    };
    cmd.execute(world);

    let mut history = world.resource_mut::<CommandHistory>();
    history.undo_stack.push(Box::new(cmd));
    history.redo_stack.clear();
}

/// Handle TextEditCommitEvent for custom property numeric/string fields + axis bindings.
pub(crate) fn on_custom_property_text_commit(
    event: On<TextEditCommitEvent>,
    bindings: Query<&CustomPropertyBinding>,
    axis_bindings: Query<&CustomAxisBinding>,
    child_of_query: Query<&ChildOf>,
    mut commands: Commands,
) {
    // Walk up from the committed entity to find a CustomPropertyBinding or CustomAxisBinding
    let mut current = event.entity;
    for _ in 0..4 {
        let Ok(child_of) = child_of_query.get(current) else {
            break;
        };
        let parent = child_of.parent();

        // Check for direct property binding (Int/Float/String)
        if let Ok(binding) = bindings.get(parent) {
            let source = binding.source_entity;
            let name = binding.property_name.clone();
            let text = event.text.clone();
            commands.queue(move |world: &mut World| {
                // Determine current type and apply accordingly
                let Some(cp) = world.get::<CustomProperties>(source) else {
                    return;
                };
                let Some(current_val) = cp.properties.get(&name) else {
                    return;
                };
                let new_val = match current_val {
                    PropertyValue::Int(_) => PropertyValue::Int(text.parse().unwrap_or(0)),
                    PropertyValue::Float(_) => PropertyValue::Float(text.parse().unwrap_or(0.0)),
                    PropertyValue::String(_) => PropertyValue::String(text),
                    other => other.clone(),
                };
                apply_custom_property_with_undo(world, source, &name, new_val);
            });
            return;
        }

        // Check for axis binding (Vec2/Vec3 component)
        if let Ok(axis) = axis_bindings.get(parent) {
            let source = axis.source_entity;
            let name = axis.property_name.clone();
            let mutate = axis.mutate;
            let new_f: f64 = event.text.parse().unwrap_or(0.0);
            commands.queue(move |world: &mut World| {
                let Some(cp) = world.get::<CustomProperties>(source) else {
                    return;
                };
                let Some(current) = cp.properties.get(&name) else {
                    return;
                };
                let mut new_val = current.clone();
                mutate(new_f, &mut new_val);
                apply_custom_property_with_undo(world, source, &name, new_val);
            });
            return;
        }

        current = parent;
    }
}

/// Handle checkbox commit for custom property booleans.
pub(crate) fn on_custom_property_checkbox_commit(
    event: On<CheckboxCommitEvent>,
    bindings: Query<&CustomPropertyBinding>,
    mut commands: Commands,
) {
    let Ok(binding) = bindings.get(event.entity) else {
        return;
    };
    let source = binding.source_entity;
    let name = binding.property_name.clone();
    let checked = event.checked;
    commands.queue(move |world: &mut World| {
        apply_custom_property_with_undo(world, source, &name, PropertyValue::Bool(checked));
    });
}