nightshade-api 0.53.0

Procedural high level API for the nightshade game engine
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
//! Textarea-backed code editor with syntax overlay, gutter, find/replace, and a
//! simple built-in tokenizer, plus a tabbed multi-document wrapper.

use std::collections::HashSet;

use leptos::prelude::*;
use wasm_bindgen::JsCast;

/// A syntax highlighter: maps source text to a sequence of `(css-class, text)`
/// runs that are rendered as styled spans behind the editor's textarea.
pub type Highlighter = fn(&str) -> Vec<(&'static str, String)>;

/// Tokenizes `source` into highlighted runs, classifying the given `keywords`
/// and `commands` words while recognizing comments, strings, and numbers.
pub fn highlight_code(
    source: &str,
    keywords: &[&'static str],
    commands: &[&'static str],
) -> Vec<(&'static str, String)> {
    let keyword_set: HashSet<&'static str> = keywords.iter().copied().collect();
    let command_set: HashSet<&'static str> = commands.iter().copied().collect();
    scan(source, &keyword_set, &command_set)
}

fn scan(
    source: &str,
    keywords: &HashSet<&'static str>,
    commands: &HashSet<&'static str>,
) -> Vec<(&'static str, String)> {
    let characters: Vec<char> = source.chars().collect();
    let count = characters.len();
    let mut runs: Vec<(&'static str, String)> = Vec::new();
    let mut index = 0;
    while index < count {
        let current = characters[index];
        if current == '/' && index + 1 < count && characters[index + 1] == '*' {
            let start = index;
            index += 2;
            while index < count
                && !(characters[index] == '*' && index + 1 < count && characters[index + 1] == '/')
            {
                index += 1;
            }
            index = (index + 2).min(count);
            runs.push(("tok-comment", characters[start..index].iter().collect()));
        } else if current == '/' && index + 1 < count && characters[index + 1] == '/' {
            let start = index;
            while index < count && characters[index] != '\n' {
                index += 1;
            }
            runs.push(("tok-comment", characters[start..index].iter().collect()));
        } else if current == '"' {
            let start = index;
            index += 1;
            while index < count {
                if characters[index] == '\\' && index + 1 < count {
                    index += 2;
                    continue;
                }
                let quote = characters[index] == '"';
                index += 1;
                if quote {
                    break;
                }
            }
            runs.push(("tok-string", characters[start..index].iter().collect()));
        } else if current.is_ascii_digit() {
            let start = index;
            while index < count
                && (characters[index].is_ascii_alphanumeric() || characters[index] == '.')
            {
                index += 1;
            }
            runs.push(("tok-number", characters[start..index].iter().collect()));
        } else if current.is_alphabetic() || current == '_' {
            let start = index;
            while index < count && (characters[index].is_alphanumeric() || characters[index] == '_')
            {
                index += 1;
            }
            let word: String = characters[start..index].iter().collect();
            let class = if keywords.contains(word.as_str()) {
                "tok-keyword"
            } else if commands.contains(word.as_str()) {
                "tok-command"
            } else {
                "tok-plain"
            };
            runs.push((class, word));
        } else {
            let start = index;
            index += 1;
            while index < count {
                let next = characters[index];
                let token_start = (next == '/'
                    && index + 1 < count
                    && (characters[index + 1] == '/' || characters[index + 1] == '*'))
                    || next == '"'
                    || next.is_ascii_digit()
                    || next.is_alphabetic()
                    || next == '_';
                if token_start {
                    break;
                }
                index += 1;
            }
            runs.push(("tok-plain", characters[start..index].iter().collect()));
        }
    }
    runs
}

/// A single-buffer code editor: a transparent `textarea` over a highlighted
/// `<pre>` overlay, with an optional line-number `gutter` (marking lines in
/// `diagnostics` as errors), a fixed `height` or `fill` mode, and an optional
/// Ctrl/Cmd+F `find` bar for find/replace over the `value` signal.
#[component]
pub fn CodeEditor(
    value: RwSignal<String>,
    #[prop(optional)] highlighter: Option<Highlighter>,
    #[prop(into, optional, default = "240px".to_string())] height: String,
    #[prop(optional)] fill: bool,
    #[prop(optional)] gutter: bool,
    #[prop(into, optional)] diagnostics: Signal<Vec<usize>>,
    #[prop(optional)] find: bool,
) -> impl IntoView {
    let pre_ref = NodeRef::<leptos::html::Pre>::new();
    let gutter_ref = NodeRef::<leptos::html::Div>::new();
    let area_ref = NodeRef::<leptos::html::Textarea>::new();
    let find_open = RwSignal::new(false);
    let query = RwSignal::new(String::new());
    let replacement = RwSignal::new(String::new());
    let class = if fill {
        "nightshade-code-editor fill"
    } else {
        "nightshade-code-editor"
    };
    let style = (!fill).then(|| format!("height:{height}"));

    let spans = move || {
        let text = value.get();
        match highlighter {
            Some(highlight) => highlight(&text),
            None => vec![("tok-plain", text)],
        }
    };

    let line_count = move || value.get().lines().count().max(1);

    let on_scroll = move |event: web_sys::Event| {
        let area = event
            .target()
            .and_then(|target| target.dyn_into::<web_sys::HtmlElement>().ok());
        if let Some(area) = area {
            if let Some(pre) = pre_ref.get() {
                pre.set_scroll_top(area.scroll_top());
                pre.set_scroll_left(area.scroll_left());
            }
            if let Some(gutter) = gutter_ref.get() {
                gutter.set_scroll_top(area.scroll_top());
            }
        }
    };

    let find_next = move || {
        let needle = query.get_untracked();
        if needle.is_empty() {
            return;
        }
        if let Some(area) = area_ref.get() {
            let text = value.get_untracked();
            let from = area.selection_end().ok().flatten().unwrap_or(0) as usize;
            let found = text
                .get(from.min(text.len())..)
                .and_then(|rest| rest.find(&needle))
                .map(|offset| from + offset)
                .or_else(|| text.find(&needle));
            if let Some(position) = found {
                let _ = area.focus();
                let _ = area.set_selection_range(position as u32, (position + needle.len()) as u32);
            }
        }
    };

    let replace_one = move || {
        let needle = query.get_untracked();
        let with = replacement.get_untracked();
        if needle.is_empty() {
            return;
        }
        if let Some(area) = area_ref.get() {
            let start = area.selection_start().ok().flatten().unwrap_or(0) as usize;
            let end = area.selection_end().ok().flatten().unwrap_or(0) as usize;
            let text = value.get_untracked();
            if end > start && text.get(start..end) == Some(needle.as_str()) {
                let mut next = text.clone();
                next.replace_range(start..end, &with);
                value.set(next);
            }
        }
        find_next();
    };

    let replace_all = move || {
        let needle = query.get_untracked();
        if needle.is_empty() {
            return;
        }
        let with = replacement.get_untracked();
        value.set(value.get_untracked().replace(&needle, &with));
    };

    let on_editor_key = move |event: web_sys::KeyboardEvent| {
        if find && (event.ctrl_key() || event.meta_key()) && event.key() == "f" {
            event.prevent_default();
            find_open.set(true);
        }
    };

    view! {
        <div class=class style=style on:keydown=on_editor_key>
            {find
                .then(|| {
                    view! {
                        <Show when=move || find_open.get() fallback=|| ()>
                            <div class="nightshade-code-find">
                                <input
                                    class="nightshade-code-find-input"
                                    placeholder="Find"
                                    prop:value=move || query.get()
                                    on:input=move |event| query.set(event_target_value(&event))
                                    on:keydown=move |event| {
                                        if event.key() == "Enter" {
                                            event.prevent_default();
                                            find_next();
                                        }
                                    }
                                />
                                <input
                                    class="nightshade-code-find-input"
                                    placeholder="Replace"
                                    prop:value=move || replacement.get()
                                    on:input=move |event| replacement.set(event_target_value(&event))
                                />
                                <button class="nightshade-button" on:click=move |_| find_next()>
                                    "Next"
                                </button>
                                <button class="nightshade-button" on:click=move |_| replace_one()>
                                    "Replace"
                                </button>
                                <button class="nightshade-button" on:click=move |_| replace_all()>
                                    "All"
                                </button>
                                <button class="nightshade-button" on:click=move |_| find_open.set(false)>
                                    "\u{00d7}"
                                </button>
                            </div>
                        </Show>
                    }
                })}
            <div class="nightshade-code-columns">
                {gutter
                .then(|| {
                    view! {
                        <div class="nightshade-code-gutter" node_ref=gutter_ref>
                            {move || {
                                let errors = diagnostics.get();
                                (1..=line_count())
                                    .map(|line| {
                                        let is_error = errors.contains(&line);
                                        view! {
                                            <div class="nightshade-code-gutter-line" class:error=is_error>
                                                {line}
                                            </div>
                                        }
                                    })
                                    .collect_view()
                            }}
                        </div>
                    }
                })}
            <div class="nightshade-code-surface">
                <pre node_ref=pre_ref class="nightshade-code-highlight" aria-hidden="true">
                    {move || {
                        spans()
                            .into_iter()
                            .map(|(class, text)| view! { <span class=class>{text}</span> })
                            .collect_view()
                    }}
                </pre>
                <textarea
                    node_ref=area_ref
                    class="nightshade-code-textarea"
                    spellcheck="false"
                    prop:value=move || value.get()
                    on:input=move |event| value.set(event_target_value(&event))
                    on:scroll=on_scroll
                ></textarea>
            </div>
            </div>
        </div>
    }
}

/// One open document in a [`CodeTabs`] set: a stable `id`, a display `title`,
/// and a reactive `value` buffer shared with the editor.
#[derive(Clone)]
pub struct CodeDocument {
    /// Stable identifier used to select the active tab.
    pub id: String,
    /// Label shown on the tab.
    pub title: String,
    /// Reactive text buffer edited when this document is active.
    pub value: RwSignal<String>,
}

impl CodeDocument {
    /// Builds a document from an `id`, `title`, and shared `value` buffer.
    pub fn new(id: impl Into<String>, title: impl Into<String>, value: RwSignal<String>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            value,
        }
    }
}

/// A tabbed multi-document editor: renders a tab bar for `documents`, tracks
/// the `active` document id, hosts a filling [`CodeEditor`] for the selection,
/// and fires the optional `on_close` callback with a document id when its close
/// button is clicked.
#[component]
pub fn CodeTabs(
    #[prop(into)] documents: Signal<Vec<CodeDocument>>,
    active: RwSignal<String>,
    #[prop(optional)] highlighter: Option<Highlighter>,
    #[prop(optional)] on_close: Option<Callback<String>>,
    #[prop(optional)] find: bool,
) -> impl IntoView {
    let active_doc = move || {
        documents
            .get()
            .into_iter()
            .find(|document| document.id == active.get())
    };
    view! {
        <div class="nightshade-code-tabs">
            <div class="nightshade-code-tabbar" role="tablist">
                {move || {
                    documents
                        .get()
                        .into_iter()
                        .map(|document| {
                            let id_select = document.id.clone();
                            let id_close = document.id.clone();
                            let id_active = document.id.clone();
                            let is_active = move || active.get() == id_active;
                            view! {
                                <div class="nightshade-code-tab" class:active=is_active>
                                    <button
                                        class="nightshade-code-tab-label"
                                        on:click=move |_| active.set(id_select.clone())
                                    >
                                        {document.title}
                                    </button>
                                    {on_close
                                        .map(|callback| {
                                            view! {
                                                <button
                                                    class="nightshade-code-tab-close"
                                                    aria-label="Close"
                                                    on:click=move |_| callback.run(id_close.clone())
                                                >
                                                    "\u{00d7}"
                                                </button>
                                            }
                                        })}
                                </div>
                            }
                        })
                        .collect_view()
                }}
            </div>
            <div class="nightshade-code-tab-body">
                {move || match (active_doc(), highlighter) {
                    (Some(document), Some(highlighter)) => {
                        view! {
                            <CodeEditor
                                value=document.value
                                highlighter=highlighter
                                fill=true
                                find=find
                            />
                        }
                            .into_any()
                    }
                    (Some(document), None) => {
                        view! { <CodeEditor value=document.value fill=true find=find /> }.into_any()
                    }
                    (None, _) => {
                        view! { <div class="nightshade-code-empty">"No open document"</div> }.into_any()
                    }
                }}
            </div>
        </div>
    }
}

const RHAI_KEYWORDS: &[&str] = &[
    "fn", "let", "const", "if", "else", "for", "in", "while", "loop", "return", "break",
    "continue", "switch", "import", "export", "global", "private", "true", "false", "throw", "try",
    "catch", "this",
];

const RHAI_COMMANDS: &[&str] = &[
    "commands",
    "spawn_floor",
    "spawn_object",
    "spawn_cube",
    "spawn_sphere",
    "spawn_cylinder",
    "spawn_cone",
    "spawn_plane",
    "spawn_torus",
    "spawn_label",
    "spawn_text",
    "point_light",
    "spot_light",
    "set_sun",
    "set_emissive",
    "set_color",
    "set_bloom",
    "set_metallic_roughness",
    "set_background",
    "set_ambient",
    "set_texture",
    "set_texture_tiling",
    "set_unlit",
    "set_visible",
    "set_parent",
    "draw_cube",
    "draw_sphere",
    "draw_line",
    "emit_firework",
    "emit_burst",
    "emit_particles",
    "emit_fire",
    "emit_smoke",
    "rotate",
    "set_position",
    "set_scale",
    "set_rotation",
    "despawn",
    "push",
    "set_velocity",
    "apply_force",
    "last",
    "result",
    "tag",
    "entity_ref",
    "hsv",
    "rgb",
    "rgba",
    "random",
    "random_range",
    "random_int",
    "log",
];

/// Tokenizes Rhai `source` into class-name and text pairs for syntax highlighting,
/// recognizing the language keywords and the scene scripting commands.
pub fn highlight_rhai(source: &str) -> Vec<(&'static str, String)> {
    highlight_code(source, RHAI_KEYWORDS, RHAI_COMMANDS)
}