rustenium_core/
contexts.rs1use rustenium_bidi_definitions::browsing_context::command_builders::CreateBuilder;
2use rustenium_bidi_definitions::browsing_context::results::CreateResult;
3use rustenium_bidi_definitions::browsing_context::types::{
4 BrowsingContext as BrowsingContextDefinition, CreateType,
5};
6
7use crate::error::CommandResultError;
8use crate::session::BidiSession;
9use crate::transport::ConnectionTransport;
10
11
12pub struct BrowsingContextBuilder<'a, T: ConnectionTransport> {
13 session: &'a mut BidiSession<T>,
14 r#type: CreateType,
15 reference_context: Option<&'a BrowsingContext>,
16 background: bool,
17}
18
19impl<'a, T: ConnectionTransport> BrowsingContextBuilder<'a, T> {
20 pub fn new(session: &'a mut BidiSession<T>) -> Self {
21 Self {
22 session,
23 r#type: CreateType::Tab,
24 reference_context: None,
25 background: false,
26 }
27 }
28
29 pub fn r#type(mut self, create_type: CreateType) -> Self {
30 self.r#type = create_type;
31 self
32 }
33
34 pub fn reference_context(mut self, reference_context: &'a BrowsingContext) -> Self {
35 self.reference_context = Option::from(reference_context);
36 self
37 }
38
39 pub fn background(mut self, background: bool) -> Self {
40 self.background = background;
41 self
42 }
43
44 pub async fn create(self) -> Result<BrowsingContext, CommandResultError> {
45 let mut create_browsing_context_command_builder = CreateBuilder::default()
46 .r#type(self.r#type.clone())
47 .background(self.background);
48 if let Some(reference_context) = self.reference_context {
49 create_browsing_context_command_builder = create_browsing_context_command_builder.reference_context(reference_context.id.clone());
50 }
51 let context = self
52 .session
53 .send(create_browsing_context_command_builder.build().unwrap())
54 .await;
55 match context {
56 Ok(response) => {
57 let result: CreateResult = response
58 .result
59 .clone()
60 .try_into()
61 .map_err(|_| CommandResultError::InvalidResultTypeError(response.result))?;
62 Ok(BrowsingContext {
63 r#type: self.r#type,
64 id: result.context,
65 })
66 }
67 Err(e) => Err(CommandResultError::SessionSendError(e)),
68 }
69 }
70}
71#[derive(Clone)]
72pub struct BrowsingContext {
73 pub r#type: CreateType,
74 id: BrowsingContextDefinition,
75}
76
77impl BrowsingContext {
78 pub fn from_id(
80 id: impl Into<BrowsingContextDefinition>,
81 context_type: CreateType,
82 ) -> Self {
83 Self {
84 r#type: context_type,
85 id: id.into(),
86 }
87 }
88
89 pub fn id(&self) -> &BrowsingContextDefinition {
91 &self.id
92 }
93}
94
95impl From<BrowsingContext> for String {
96 fn from(browsing_context: BrowsingContext) -> String {
97 browsing_context.id.as_ref().to_string()
98 }
99}