DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 106a55af94523d2dcca350a05b8b53d83bb93619 deck-builder/client/src/plugins/game/ui/log.rs -rw-r--r-- 10.2 KiB
106a55afJonni Liljamo chore: remove old-client-for-ref 1 year, 7 months ago
                                                                                
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
/*
 * This file is part of laurelin_client
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

use bevy::{
    a11y::{accesskit::NodeBuilder, AccessibilityNode},
    input::mouse::{MouseScrollUnit, MouseWheel},
    prelude::*,
};

use crate::{game_status::LogSection, plugins::GameData, AppState};

pub struct LogPlugin;

impl Plugin for LogPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<ToggleLogEvent>()
            .add_event::<UpdateLogEvent>()
            .add_system(setup_log.in_schedule(OnEnter(AppState::InGame)))
            .add_system(update_log_button)
            .add_system(toggle_log.run_if(on_event::<ToggleLogEvent>()))
            .add_system(update_log.run_if(on_event::<UpdateLogEvent>()))
            .add_system(log_mouse_scroll);
    }
}

struct ToggleLogEvent;
pub struct UpdateLogEvent;

const NORMAL_BUTTON: Color = Color::rgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::rgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::rgb(0.35, 0.75, 0.35);

#[derive(Component)]
struct LogButton;
#[derive(Component)]
struct LogListParent;
#[derive(Component)]
struct LogList;
#[derive(Component)]
struct LogListEntry;

fn setup_log(mut commands: Commands, asset_server: Res<AssetServer>) {
    let font = asset_server.load("fonts/FiraMono-Bold.ttf");

    // log toggle button
    commands
        .spawn(NodeBundle {
            style: Style {
                position_type: PositionType::Absolute,
                position: UiRect {
                    top: Val::Px(20.),
                    right: Val::Px(20.),
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        })
        .with_children(|parent| {
            parent
                .spawn((
                    ButtonBundle {
                        style: Style {
                            size: Size::new(Val::Px(75.), Val::Px(35.)),
                            // center child text
                            justify_content: JustifyContent::Center,
                            align_items: AlignItems::Center,
                            ..Default::default()
                        },
                        background_color: NORMAL_BUTTON.into(),
                        ..Default::default()
                    },
                    LogButton,
                ))
                .with_children(|parent| {
                    parent.spawn((TextBundle::from_section(
                        "Log",
                        TextStyle {
                            font: font.clone(),
                            font_size: 20.,
                            color: Color::WHITE,
                        },
                    ),));
                });
        });

    // log window
    commands
        .spawn((
            NodeBundle {
                style: Style {
                    flex_direction: FlexDirection::Column,
                    justify_content: JustifyContent::Center,
                    align_items: AlignItems::Center,
                    size: Size {
                        width: Val::Px(475.),
                        height: Val::Percent(75.),
                    },
                    position_type: PositionType::Absolute,
                    position: UiRect {
                        bottom: Val::Percent(12.5),
                        right: Val::Px(100.),
                        ..Default::default()
                    },
                    ..Default::default()
                },
                background_color: Color::rgb(0.15, 0.15, 0.15).into(),
                visibility: Visibility::Hidden,
                ..Default::default()
            },
            LogListParent,
        ))
        .with_children(|parent| {
            parent
                .spawn(NodeBundle {
                    style: Style {
                        flex_direction: FlexDirection::Column,
                        //align_self: AlignSelf::Stretch,
                        size: Size {
                            width: Val::Px(450.),
                            height: Val::Percent(95.),
                        },
                        overflow: Overflow::Hidden,
                        ..Default::default()
                    },
                    ..Default::default()
                })
                .with_children(|parent| {
                    parent
                        .spawn((
                            NodeBundle {
                                style: Style {
                                    flex_direction: FlexDirection::Column,
                                    max_size: Size::UNDEFINED,
                                    ..Default::default()
                                },
                                ..Default::default()
                            },
                            AccessibilityNode(NodeBuilder::new(bevy::a11y::accesskit::Role::List)),
                            ScrollingList::default(),
                            LogList,
                        ))
                        .with_children(|parent| {
                            parent.spawn((
                                TextBundle::from_section(
                                    "Empty".to_string(),
                                    TextStyle {
                                        font: font.clone(),
                                        font_size: 20.,
                                        color: Color::WHITE,
                                    },
                                ),
                                AccessibilityNode(NodeBuilder::new(
                                    bevy::a11y::accesskit::Role::ListItem,
                                )),
                                LogListEntry,
                            ));
                        });
                });
        });
}

fn update_log_button(
    mut interaction_query: Query<
        (&Interaction, &mut BackgroundColor),
        (Changed<Interaction>, With<LogButton>),
    >,
    mut tl_ev_w: EventWriter<ToggleLogEvent>,
) {
    for (interaction, mut color) in &mut interaction_query {
        match interaction {
            Interaction::Clicked => {
                *color = PRESSED_BUTTON.into();
                tl_ev_w.send(ToggleLogEvent);
            }
            Interaction::Hovered => {
                *color = HOVERED_BUTTON.into();
            }
            Interaction::None => {
                *color = NORMAL_BUTTON.into();
            }
        }
    }
}

fn toggle_log(mut log_parent_query: Query<&mut Visibility, With<LogListParent>>) {
    for mut visibility in &mut log_parent_query {
        if *visibility == Visibility::Hidden {
            *visibility = Visibility::Inherited;
        } else {
            *visibility = Visibility::Hidden;
        }
    }
}

fn update_log(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    log_query: Query<Entity, With<LogList>>,
    log_entries_query: Query<Entity, With<LogListEntry>>,
    game_data: Res<GameData>,
) {
    for entity in &log_entries_query {
        commands.entity(entity).despawn_recursive();
    }
    for entity in &log_query {
        let Some(status) = game_data.clone().game_status else {
            return;
        };

        let font = asset_server.load("fonts/FiraMono-Regular.ttf");
        let font_bold = asset_server.load("fonts/FiraMono-Bold.ttf");

        let style = TextStyle {
            font: font.clone(),
            font_size: 20.,
            color: Color::WHITE,
        };

        let index_spaces = status.actions.len().to_string().len();

        for (i, log) in status.log.iter().enumerate() {
            let spaces = " ".repeat(index_spaces - i.to_string().len());
            let index_text = TextSection {
                value: format!("{}{}. ", spaces, i),
                style: TextStyle {
                    font: font_bold.clone(),
                    ..style
                },
            };

            let mut sections = vec![index_text];
            for section in &log.sections {
                match section {
                    LogSection::Normal(value) => {
                        sections.push(TextSection {
                            value: value.to_string(),
                            style: style.clone(),
                        });
                    }
                    LogSection::Bold(value) => {
                        sections.push(TextSection {
                            value: value.to_string(),
                            style: TextStyle {
                                font: font_bold.clone(),
                                ..style.clone()
                            },
                        });
                    }
                }
            }

            commands
                .spawn((
                    TextBundle::from_sections(sections).with_style(Style {
                        max_size: Size {
                            width: Val::Px(450.),
                            height: Val::Undefined,
                        },
                        ..Default::default()
                    }),
                    AccessibilityNode(NodeBuilder::new(bevy::a11y::accesskit::Role::ListItem)),
                    LogListEntry,
                ))
                .set_parent(entity);
        }
    }
}

#[derive(Component, Default)]
struct ScrollingList {
    position: f32,
}

fn log_mouse_scroll(
    mut mouse_wheel_events: EventReader<MouseWheel>,
    mut query_list: Query<(&mut ScrollingList, &mut Style, &Parent, &Node)>,
    query_node: Query<&Node>,
) {
    for mouse_wheel_event in mouse_wheel_events.iter() {
        for (mut scrolling_list, mut style, parent, list_node) in &mut query_list {
            let items_height = list_node.size().y;
            let container_height = query_node.get(parent.get()).unwrap().size().y;

            let max_scroll = (items_height - container_height).max(0.);

            let dy = match mouse_wheel_event.unit {
                MouseScrollUnit::Line => mouse_wheel_event.y * 20.,
                MouseScrollUnit::Pixel => mouse_wheel_event.y,
            };

            scrolling_list.position += dy;
            scrolling_list.position = scrolling_list.position.clamp(-max_scroll, 0.);
            style.position.top = Val::Px(scrolling_list.position);
        }
    }
}