rustenium_core/
contexts.rs

1use rustenium_bidi_commands::browsing_context::commands::{BrowsingContextCreateMethod, Create as BrowsingContextCreate, CreateParameters as BrowsingContextCreateParameters, BrowsingContextResult};
2use rustenium_bidi_commands::browsing_context::types::{BrowsingContext, CreateType as BrowsingContextCreateType};
3use rustenium_bidi_commands::{BrowsingContextCommand, CommandData, ResultData};
4use crate::error::{CommandResultError};
5use crate::Session;
6use crate::transport::ConnectionTransport;
7
8#[derive(Debug, Clone)]
9pub struct Context {
10    pub r#type: BrowsingContextCreateType,
11    id: BrowsingContext,
12}
13
14impl Context {
15    /// Create a Context from existing ID and type
16    pub fn from_id(id: String, context_type: BrowsingContextCreateType) -> Self {
17        Self {
18            r#type: context_type,
19            id,
20        }
21    }
22
23    pub async fn new<OT: ConnectionTransport>(session: &mut Session<OT>, context_creation_type: Option<BrowsingContextCreateType>, reference_context: Option<&Context>, background: bool) -> Result<Self, CommandResultError>  {
24        let context_creation_type = context_creation_type.unwrap_or(BrowsingContextCreateType::Tab);
25        let create_browsing_context_command = BrowsingContextCreate {
26            method: BrowsingContextCreateMethod::BrowsingContextCreate,
27            params: BrowsingContextCreateParameters {
28                r#type: context_creation_type.clone(),
29                reference_context: reference_context.map(|c| c.id.clone()),
30                background: Option::from(background),
31                // I don't know how to deal with UserContext yet.
32                user_context: None,
33            },
34        };
35        let context = session.send(CommandData::BrowsingContextCommand(BrowsingContextCommand::Create(create_browsing_context_command))).await;
36        match context {
37            Ok(ResultData::BrowsingContextResult(context)) => match context {
38                BrowsingContextResult::CreateResult(context) => {
39                    Ok(Self {
40                        r#type: context_creation_type,
41                        id: context.context
42                    })
43                },
44                _ => Err(CommandResultError::InvalidResultTypeError(ResultData::BrowsingContextResult(context)))
45            },
46            Ok(result) => Err(CommandResultError::InvalidResultTypeError(result)),
47            Err(e) => Err(CommandResultError::SessionSendError(e)),
48        }
49    }
50
51    /// Get the context ID as a string reference
52    pub fn id(&self) -> &BrowsingContext {
53        &self.id
54    }
55
56    /// Get a cloned context ID (deprecated - use id() instead)
57    pub fn get_context_id(&self) -> String {
58        self.id.clone()
59    }
60}