rsvim_core 0.1.3-alpha.2

The core library for RSVIM text editor.
Documentation
//! Ex command definition.

use crate::is_v8_str;
use crate::js::command::attr::*;
use crate::js::command::opt::*;
use crate::js::converter::*;
use crate::prelude::*;
use compact_str::CompactString;
use compact_str::ToCompactString;
use rsvim_macro::ToV8;
use std::fmt::Debug;
use std::rc::Rc;

pub type CommandCallback = Rc<v8::Global<v8::Function>>;

/// Command definition names.
pub const NAME: &str = "name";
pub const CALLBACK: &str = "callback";
pub const ATTRIBUTES: &str = "attributes";
pub const OPTIONS: &str = "options";

#[derive(Clone, ToV8)]
pub struct CommandDefinition {
  pub name: CompactString,
  pub callback: CommandCallback,
  pub attributes: CommandAttributes,
  pub options: CommandOptions,
}

rc_ptr!(CommandDefinition);

impl Debug for CommandDefinition {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct("CommandDefinition")
      .field(NAME, &self.name)
      .field(CALLBACK, &"Rc<v8::Global<v8::Function>>")
      .field(ATTRIBUTES, &self.attributes)
      .field(OPTIONS, &self.options)
      .finish()
  }
}

impl StructFromV8CallbackArguments for CommandDefinition {
  fn from_v8_callback_arguments<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    args: v8::FunctionCallbackArguments<'s>,
  ) -> Self {
    debug_assert!(args.length() == 4);
    debug_assert!(is_v8_str!(args.get(0)));
    let name = args.get(0).to_rust_string_lossy(scope);
    debug_assert!(args.get(1).is_function());
    let callback = v8::Local::<v8::Function>::try_from(args.get(1)).unwrap();
    let callback = Rc::new(v8::Global::new(scope, callback));
    debug_assert!(args.get(2).is_object());
    let attributes =
      CommandAttributes::from_v8(scope, args.get(2).to_object(scope).unwrap());
    debug_assert!(args.get(3).is_object());
    let options =
      CommandOptions::from_v8(scope, args.get(3).to_object(scope).unwrap());

    Self {
      name: name.to_compact_string(),
      callback,
      attributes,
      options,
    }
  }
}