From 106eac1d6eda329605066fdc17b294e5efefabd6 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Wed, 11 Sep 2024 23:03:15 +0530 Subject: [PATCH 01/21] added new notes feature with ui in c++ --- browser/brave_profile_prefs.cc | 1 + .../ui/views/toolbar/brave_toolbar_view.cc | 119 +++++++++++++++++- browser/ui/views/toolbar/brave_toolbar_view.h | 24 ++++ 3 files changed, 143 insertions(+), 1 deletion(-) diff --git a/browser/brave_profile_prefs.cc b/browser/brave_profile_prefs.cc index 346dc8065d6e..1eee4679b97d 100644 --- a/browser/brave_profile_prefs.cc +++ b/browser/brave_profile_prefs.cc @@ -147,6 +147,7 @@ void RegisterProfilePrefsForMigration( // Added 10/2022 registry->RegisterIntegerPref(kDefaultBrowserLaunchingCount, 0); + registry->RegisterListPref("custom_notes"); #endif brave_wallet::RegisterProfilePrefsForMigration(registry); diff --git a/browser/ui/views/toolbar/brave_toolbar_view.cc b/browser/ui/views/toolbar/brave_toolbar_view.cc index 5b54012551d0..32f46fec3b03 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.cc +++ b/browser/ui/views/toolbar/brave_toolbar_view.cc @@ -7,8 +7,10 @@ #include #include +#include #include - +#include "base/values.h" +#include "components/prefs/pref_service.h" #include "base/functional/bind.h" #include "brave/app/brave_command_ids.h" #include "brave/browser/brave_wallet/brave_wallet_context_utils.h" @@ -225,8 +227,25 @@ void BraveToolbarView::Init() { ui::EF_MIDDLE_MOUSE_BUTTON); wallet_->UpdateImageAndText(); + wallet_ = container_view->AddChildViewAt( + std::make_unique(GetAppMenuButton(), profile), + *container_view->GetIndexOf(GetAppMenuButton()) - 1); + wallet_->SetTriggerableEventFlags(ui::EF_LEFT_MOUSE_BUTTON | + ui::EF_MIDDLE_MOUSE_BUTTON); + wallet_->UpdateImageAndText(); + UpdateWalletButtonVisibility(); + custom_button_ = container_view->AddChildViewAt( + std::make_unique( + base::BindRepeating(&BraveToolbarView::ShowCustomPopup, base::Unretained(this)), + u"Custom Button"), + *container_view->GetIndexOf(GetAppMenuButton()) - 1); + + custom_button_->SetTriggerableEventFlags(ui::EF_LEFT_MOUSE_BUTTON); + custom_button_->SetAccessibleName(u"Open Popup"); + custom_button_->SetVisible(true); + #if !BUILDFLAG(ENABLE_BRAVE_VPN) if (brave_vpn::IsAllowedForContext(profile)) { brave_vpn_ = container_view->AddChildViewAt( @@ -434,6 +453,67 @@ void BraveToolbarView::ResetButtonBounds() { } } +void BraveToolbarView::OnAddNote() { + if (!text_field_->GetText().empty()) { + notes_.push_back(base::UTF16ToUTF8(text_field_->GetText())); + SaveNotesToLocalStorage(); // Save to persistent storage + text_field_->SetText(u""); // Clear input field + } +} + +// Method to delete all notes +void BraveToolbarView::OnDeleteAllNotes() { + notes_.clear(); + SaveNotesToLocalStorage(); // Update storage +} + +// Save notes to preferences or a file (acting as local storage) +void BraveToolbarView::SaveNotesToLocalStorage() { + base::Value::List note_list; + + for (const auto& note : notes_) { + note_list.Append(base::Value(note)); + } + + if (pref_service_) { + pref_service_->Set("custom_notes", base::Value(std::move(note_list))); + pref_service_->CommitPendingWrite(); + } else { + LOG(ERROR) << "PrefService is not initialized."; + } +} + +// Load notes from local storage (preferences) +void BraveToolbarView::LoadNotesFromLocalStorage() { + if (pref_service_) { + const base::Value* note_list_value = pref_service_->GetUserPrefValue("custom_notes"); + if (note_list_value && note_list_value->is_list()) { + const base::Value::List& note_list = note_list_value->GetList(); + notes_.clear(); + for (const auto& note_value : note_list) { + if (note_value.is_string()) { + std::u16string u16_string = base::UTF8ToUTF16(note_value.GetString()); + // Convert std::u16string to std::string + std::string str(u16_string.begin(), u16_string.end()); + notes_.push_back(str); + } + } + } + } else { + LOG(ERROR) << "PrefService is not initialized."; + } +} + +void BraveToolbarView::OnNoteAdded(const std::u16string& new_note) { + notes_.push_back(base::UTF16ToUTF8(new_note)); + SaveNotesToLocalStorage(); // Save the updated notes list +} + +// Handling text input changes +void BraveToolbarView::ContentsChanged(views::Textfield* sender, const std::u16string& new_contents) { + note_input_ = new_contents; // Update note content as it is typed +} + void BraveToolbarView::UpdateWalletButtonVisibility() { Profile* profile = browser()->profile(); if (brave_wallet::IsNativeWalletEnabled() && @@ -456,5 +536,42 @@ void BraveToolbarView::UpdateWalletButtonVisibility() { wallet_->SetVisible(false); } +views::View* BraveToolbarView::BuildNotesView() { + auto* container = new views::View(); + container->SetLayoutManager(std::make_unique( + views::BoxLayout::Orientation::kVertical)); + + for (const auto& note : notes_) { + container->AddChildView(std::make_unique(base::UTF8ToUTF16(note))); + } + + return container; +} + + +void BraveToolbarView::ShowCustomPopup() { + // Create a simple popup dialog (for demonstration purposes). + views::DialogDelegate::CreateDialogWidget( + views::Builder() + .SetTitle(u"Custom Note Popup") + .SetLayoutManager(std::make_unique( + views::BoxLayout::Orientation::kVertical)) + .AddChildren( + views::Builder() // Add text input for note + .SetController(&text_field_controller_), // Controller to handle input + views::Builder() + .SetText(u"Add Note") + .SetCallback(base::BindRepeating(&BraveToolbarView::OnAddNote, base::Unretained(this))), + views::Builder() + .SetText(u"Delete All Notes") + .SetCallback(base::BindRepeating(&BraveToolbarView::OnDeleteAllNotes, base::Unretained(this))) + views::Builder() + .AddChildren(BuildNotesView()) + ) + .Build(), + browser_view_->GetWidget()->GetNativeWindow(), nullptr)->Show(); +} + + BEGIN_METADATA(BraveToolbarView) END_METADATA diff --git a/browser/ui/views/toolbar/brave_toolbar_view.h b/browser/ui/views/toolbar/brave_toolbar_view.h index 66aa118de5a7..2c2f40007aad 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.h +++ b/browser/ui/views/toolbar/brave_toolbar_view.h @@ -7,7 +7,11 @@ #define BRAVE_BROWSER_UI_VIEWS_TOOLBAR_BRAVE_TOOLBAR_VIEW_H_ #include "base/memory/raw_ptr.h" +#include #include "base/scoped_observation.h" +#include "ui/views/controls/textfield/textfield_controller.h" +#include "ui/views/controls/textfield/textfield.h" +#include "components/prefs/pref_service.h" #include "brave/components/brave_vpn/common/buildflags/buildflags.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" @@ -25,6 +29,12 @@ class BraveToolbarView : public ToolbarView, public ProfileAttributesStorage::Observer { METADATA_HEADER(BraveToolbarView, ToolbarView) public: + + void OnAddNote(); + // Method to handle deleting all notes + void OnDeleteAllNotes(); + // Method for text input handling + explicit BraveToolbarView(Browser* browser, BrowserView* browser_view); ~BraveToolbarView() override; @@ -49,17 +59,31 @@ class BraveToolbarView : public ToolbarView, void ShowBookmarkBubble(const GURL& url, bool already_bookmarked) override; void ViewHierarchyChanged( const views::ViewHierarchyChangedDetails& details) override; + // void ContentsChanged(views::Textfield* sender, const std::u16string& new_contents) override; private: void LoadImages() override; void ResetLocationBarBounds(); void ResetButtonBounds(); + void SaveNotesToLocalStorage(); void UpdateBookmarkVisibility(); + void LoadNotesFromLocalStorage(); + void OnNoteAdded(const std::u16string& new_note); + void ContentsChanged(); + views::View* BuildNotesView(); + std::u16string note_input_; + std::vector notes_; + raw_ptr text_field_ = nullptr; + raw_ptr pref_service_ = nullptr; + raw_ptr custom_button_ = nullptr; + void ShowCustomPopup(); // ProfileAttributesStorage::Observer: void OnProfileAdded(const base::FilePath& profile_path) override; void OnProfileWasRemoved(const base::FilePath& profile_path, const std::u16string& profile_name) override; + // void ContentsChanged(views::Textfield* sender, + // const std::u16string& new_contents) override; void UpdateWalletButtonVisibility(); From 5ed4f70555c65498390c0c8c92bc14bab018118b Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Sat, 14 Sep 2024 14:59:17 +0530 Subject: [PATCH 02/21] ui is getting rendered, functions are not working as of now --- .../ui/views/toolbar/brave_toolbar_view.cc | 77 +++++++++++-------- browser/ui/views/toolbar/brave_toolbar_view.h | 8 +- 2 files changed, 47 insertions(+), 38 deletions(-) diff --git a/browser/ui/views/toolbar/brave_toolbar_view.cc b/browser/ui/views/toolbar/brave_toolbar_view.cc index 32f46fec3b03..4f07af66db63 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.cc +++ b/browser/ui/views/toolbar/brave_toolbar_view.cc @@ -463,8 +463,8 @@ void BraveToolbarView::OnAddNote() { // Method to delete all notes void BraveToolbarView::OnDeleteAllNotes() { - notes_.clear(); - SaveNotesToLocalStorage(); // Update storage + // notes_.clear(); + // SaveNotesToLocalStorage(); // Update storage } // Save notes to preferences or a file (acting as local storage) @@ -492,10 +492,7 @@ void BraveToolbarView::LoadNotesFromLocalStorage() { notes_.clear(); for (const auto& note_value : note_list) { if (note_value.is_string()) { - std::u16string u16_string = base::UTF8ToUTF16(note_value.GetString()); - // Convert std::u16string to std::string - std::string str(u16_string.begin(), u16_string.end()); - notes_.push_back(str); + notes_.push_back(note_value.GetString()); } } } @@ -505,13 +502,13 @@ void BraveToolbarView::LoadNotesFromLocalStorage() { } void BraveToolbarView::OnNoteAdded(const std::u16string& new_note) { - notes_.push_back(base::UTF16ToUTF8(new_note)); + notes_.push_back(base::UTF16ToUTF8(new_note)); SaveNotesToLocalStorage(); // Save the updated notes list } // Handling text input changes void BraveToolbarView::ContentsChanged(views::Textfield* sender, const std::u16string& new_contents) { - note_input_ = new_contents; // Update note content as it is typed + // note_input_ = new_contents; // Update note content as it is typed } void BraveToolbarView::UpdateWalletButtonVisibility() { @@ -540,38 +537,50 @@ views::View* BraveToolbarView::BuildNotesView() { auto* container = new views::View(); container->SetLayoutManager(std::make_unique( views::BoxLayout::Orientation::kVertical)); - - for (const auto& note : notes_) { - container->AddChildView(std::make_unique(base::UTF8ToUTF16(note))); - } return container; } void BraveToolbarView::ShowCustomPopup() { - // Create a simple popup dialog (for demonstration purposes). - views::DialogDelegate::CreateDialogWidget( - views::Builder() - .SetTitle(u"Custom Note Popup") - .SetLayoutManager(std::make_unique( - views::BoxLayout::Orientation::kVertical)) - .AddChildren( - views::Builder() // Add text input for note - .SetController(&text_field_controller_), // Controller to handle input - views::Builder() - .SetText(u"Add Note") - .SetCallback(base::BindRepeating(&BraveToolbarView::OnAddNote, base::Unretained(this))), - views::Builder() - .SetText(u"Delete All Notes") - .SetCallback(base::BindRepeating(&BraveToolbarView::OnDeleteAllNotes, base::Unretained(this))) - views::Builder() - .AddChildren(BuildNotesView()) - ) - .Build(), - browser_view_->GetWidget()->GetNativeWindow(), nullptr)->Show(); -} + // Create a custom DialogDelegateView + class CustomDialogDelegate : public views::DialogDelegateView { + public: + CustomDialogDelegate(BraveToolbarView* toolbar_view) + : toolbar_view_(toolbar_view) { + SetTitle(u"Custom Note Popup"); + SetLayoutManager(std::make_unique( + views::BoxLayout::Orientation::kVertical)); + + text_field_ = AddChildView(std::make_unique()); + text_field_->SetText(u"Notes"); + + AddChildView(std::make_unique( + base::BindRepeating(&BraveToolbarView::OnAddNote, + base::Unretained(toolbar_view_)), + u"Add Note")); + + AddChildView(std::make_unique( + base::BindRepeating(&BraveToolbarView::OnDeleteAllNotes, + base::Unretained(toolbar_view_)), + u"Delete All Notes")); + + AddChildView(toolbar_view_->BuildNotesView()); + } + bool ShouldShowCloseButton() const override { return true; } + + private: + raw_ptr toolbar_view_; + raw_ptr text_field_; + }; + + // Create and show the dialog + views::Widget::CreateWindowWithContext( + new CustomDialogDelegate(this), + browser_view_->GetWidget()->GetNativeWindow(), + gfx::Rect(300, 300))->Show(); +} BEGIN_METADATA(BraveToolbarView) -END_METADATA +END_METADATA \ No newline at end of file diff --git a/browser/ui/views/toolbar/brave_toolbar_view.h b/browser/ui/views/toolbar/brave_toolbar_view.h index 2c2f40007aad..f316a2dd73c5 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.h +++ b/browser/ui/views/toolbar/brave_toolbar_view.h @@ -71,8 +71,8 @@ class BraveToolbarView : public ToolbarView, void OnNoteAdded(const std::u16string& new_note); void ContentsChanged(); views::View* BuildNotesView(); - std::u16string note_input_; - std::vector notes_; + std::string note_input_; + std::vector notes_; raw_ptr text_field_ = nullptr; raw_ptr pref_service_ = nullptr; raw_ptr custom_button_ = nullptr; @@ -82,8 +82,8 @@ class BraveToolbarView : public ToolbarView, void OnProfileAdded(const base::FilePath& profile_path) override; void OnProfileWasRemoved(const base::FilePath& profile_path, const std::u16string& profile_name) override; - // void ContentsChanged(views::Textfield* sender, - // const std::u16string& new_contents) override; + void ContentsChanged(views::Textfield* sender, + const std::u16string& new_contents); void UpdateWalletButtonVisibility(); From 8d5cb2f031cbef7f17dfe18eb649495a4b2fdc7c Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Mon, 16 Sep 2024 22:53:47 +0530 Subject: [PATCH 03/21] now the notes feature is full functional just need to add ui rendering of the saved notes and deleted notes. --- .../ui/views/toolbar/brave_toolbar_view.cc | 104 +++++++++++------- browser/ui/views/toolbar/brave_toolbar_view.h | 16 +-- build/commands/lib/util.js | 1 + 3 files changed, 75 insertions(+), 46 deletions(-) diff --git a/browser/ui/views/toolbar/brave_toolbar_view.cc b/browser/ui/views/toolbar/brave_toolbar_view.cc index 4f07af66db63..f41f30b63bd9 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.cc +++ b/browser/ui/views/toolbar/brave_toolbar_view.cc @@ -7,11 +7,11 @@ #include #include -#include #include -#include "base/values.h" -#include "components/prefs/pref_service.h" +#include + #include "base/functional/bind.h" +#include "base/values.h" #include "brave/app/brave_command_ids.h" #include "brave/browser/brave_wallet/brave_wallet_context_utils.h" #include "brave/browser/ui/tabs/brave_tab_prefs.h" @@ -55,12 +55,13 @@ constexpr int kLocationBarMaxWidth = 1080; double GetLocationBarMarginHPercent(int toolbar_width) { double location_bar_margin_h_pc = 0.07; - if (toolbar_width < 700) + if (toolbar_width < 700) { location_bar_margin_h_pc = 0; - else if (toolbar_width < 850) + } else if (toolbar_width < 850) { location_bar_margin_h_pc = 0.03; - else if (toolbar_width < 1000) + } else if (toolbar_width < 1000) { location_bar_margin_h_pc = 0.05; + } return location_bar_margin_h_pc; } @@ -128,6 +129,9 @@ BraveToolbarView::~BraveToolbarView() = default; void BraveToolbarView::Init() { ToolbarView::Init(); + pref_service_ = browser_->profile()->GetPrefs(); + LoadNotesFromLocalStorage(); + // This will allow us to move this window by dragging toolbar. // See brave_non_client_hit_test_helper.h views::SetHitTestComponent(this, HTCAPTION); @@ -238,7 +242,8 @@ void BraveToolbarView::Init() { custom_button_ = container_view->AddChildViewAt( std::make_unique( - base::BindRepeating(&BraveToolbarView::ShowCustomPopup, base::Unretained(this)), + base::BindRepeating(&BraveToolbarView::ShowCustomPopup, + base::Unretained(this)), u"Custom Button"), *container_view->GetIndexOf(GetAppMenuButton()) - 1); @@ -290,8 +295,9 @@ void BraveToolbarView::OnEditBookmarksEnabledChanged() { } void BraveToolbarView::OnShowBookmarksButtonChanged() { - if (!bookmark_) + if (!bookmark_) { return; + } UpdateBookmarkVisibility(); } @@ -306,13 +312,16 @@ void BraveToolbarView::OnLocationBarIsWideChanged() { void BraveToolbarView::OnThemeChanged() { ToolbarView::OnThemeChanged(); - if (!brave_initialized_) + if (!brave_initialized_) { return; + } - if (display_mode_ == DisplayMode::NORMAL && bookmark_) + if (display_mode_ == DisplayMode::NORMAL && bookmark_) { bookmark_->UpdateImageAndText(); - if (display_mode_ == DisplayMode::NORMAL && wallet_) + } + if (display_mode_ == DisplayMode::NORMAL && wallet_) { wallet_->UpdateImageAndText(); + } } void BraveToolbarView::OnProfileAdded(const base::FilePath& profile_path) { @@ -326,10 +335,12 @@ void BraveToolbarView::OnProfileWasRemoved(const base::FilePath& profile_path, void BraveToolbarView::LoadImages() { ToolbarView::LoadImages(); - if (bookmark_) + if (bookmark_) { bookmark_->UpdateImageAndText(); - if (wallet_) + } + if (wallet_) { wallet_->UpdateImageAndText(); + } } void BraveToolbarView::Update(content::WebContents* tab) { @@ -350,8 +361,9 @@ void BraveToolbarView::Update(content::WebContents* tab) { } void BraveToolbarView::UpdateBookmarkVisibility() { - if (!bookmark_) + if (!bookmark_) { return; + } DCHECK_EQ(DisplayMode::NORMAL, display_mode_); bookmark_->SetVisible(browser_defaults::bookmarks_enabled && @@ -387,8 +399,9 @@ void BraveToolbarView::ShowBookmarkBubble(const GURL& url, // or the location bar if there is no bookmark button // (i.e. in non-normal display mode). views::View* anchor_view = location_bar_; - if (bookmark_ && bookmark_->GetVisible()) + if (bookmark_ && bookmark_->GetVisible()) { anchor_view = bookmark_; + } std::unique_ptr delegate; delegate = @@ -412,8 +425,9 @@ void BraveToolbarView::ViewHierarchyChanged( void BraveToolbarView::Layout(PassKey) { LayoutSuperclass(this); - if (!brave_initialized_) + if (!brave_initialized_) { return; + } // ToolbarView::Layout() handles below modes. So just return. if (display_mode_ == DisplayMode::CUSTOM_TAB || @@ -453,18 +467,18 @@ void BraveToolbarView::ResetButtonBounds() { } } -void BraveToolbarView::OnAddNote() { - if (!text_field_->GetText().empty()) { - notes_.push_back(base::UTF16ToUTF8(text_field_->GetText())); - SaveNotesToLocalStorage(); // Save to persistent storage - text_field_->SetText(u""); // Clear input field +void BraveToolbarView::OnAddNote(const std::u16string& new_note) { + if (!new_note.empty()) { + notes_.push_back(base::UTF16ToUTF8(new_note)); + SaveNotesToLocalStorage(); } } -// Method to delete all notes void BraveToolbarView::OnDeleteAllNotes() { - // notes_.clear(); - // SaveNotesToLocalStorage(); // Update storage + if (!notes_.empty()) { + notes_.clear(); + SaveNotesToLocalStorage(); + } } // Save notes to preferences or a file (acting as local storage) @@ -472,12 +486,14 @@ void BraveToolbarView::SaveNotesToLocalStorage() { base::Value::List note_list; for (const auto& note : notes_) { + LOG(ERROR) << note; note_list.Append(base::Value(note)); } if (pref_service_) { pref_service_->Set("custom_notes", base::Value(std::move(note_list))); pref_service_->CommitPendingWrite(); + LOG(ERROR) << "ADDED SUCCESSFULLY"; } else { LOG(ERROR) << "PrefService is not initialized."; } @@ -486,7 +502,8 @@ void BraveToolbarView::SaveNotesToLocalStorage() { // Load notes from local storage (preferences) void BraveToolbarView::LoadNotesFromLocalStorage() { if (pref_service_) { - const base::Value* note_list_value = pref_service_->GetUserPrefValue("custom_notes"); + const base::Value* note_list_value = + pref_service_->GetUserPrefValue("custom_notes"); if (note_list_value && note_list_value->is_list()) { const base::Value::List& note_list = note_list_value->GetList(); notes_.clear(); @@ -507,7 +524,8 @@ void BraveToolbarView::OnNoteAdded(const std::u16string& new_note) { } // Handling text input changes -void BraveToolbarView::ContentsChanged(views::Textfield* sender, const std::u16string& new_contents) { +void BraveToolbarView::ContentsChanged(views::Textfield* sender, + const std::u16string& new_contents) { // note_input_ = new_contents; // Update note content as it is typed } @@ -541,9 +559,7 @@ views::View* BraveToolbarView::BuildNotesView() { return container; } - void BraveToolbarView::ShowCustomPopup() { - // Create a custom DialogDelegateView class CustomDialogDelegate : public views::DialogDelegateView { public: CustomDialogDelegate(BraveToolbarView* toolbar_view) @@ -552,13 +568,24 @@ void BraveToolbarView::ShowCustomPopup() { SetLayoutManager(std::make_unique( views::BoxLayout::Orientation::kVertical)); - text_field_ = AddChildView(std::make_unique()); - text_field_->SetText(u"Notes"); - - AddChildView(std::make_unique( - base::BindRepeating(&BraveToolbarView::OnAddNote, - base::Unretained(toolbar_view_)), - u"Add Note")); + auto text_field = std::make_unique(); + auto* text_field_ptr = text_field.get(); + AddChildView(std::move(text_field)); + text_field_ptr->SetPlaceholderText(u"Enter your note here"); + + auto add_note_button = std::make_unique( + base::BindRepeating( + [](views::Textfield* text_field, BraveToolbarView* toolbar_view) { + if (text_field && toolbar_view) { + std::u16string note_text = text_field->GetText(); + toolbar_view->OnAddNote(note_text); + text_field->SetText(u""); // Clear the text field here + } + }, + text_field_ptr, base::Unretained(toolbar_view_)), + u"Add Note"); + + AddChildView(std::move(add_note_button)); AddChildView(std::make_unique( base::BindRepeating(&BraveToolbarView::OnDeleteAllNotes, @@ -575,12 +602,11 @@ void BraveToolbarView::ShowCustomPopup() { raw_ptr text_field_; }; - // Create and show the dialog views::Widget::CreateWindowWithContext( new CustomDialogDelegate(this), - browser_view_->GetWidget()->GetNativeWindow(), - gfx::Rect(300, 300))->Show(); + browser_view_->GetWidget()->GetNativeWindow(), gfx::Rect(300, 300)) + ->Show(); } BEGIN_METADATA(BraveToolbarView) -END_METADATA \ No newline at end of file +END_METADATA diff --git a/browser/ui/views/toolbar/brave_toolbar_view.h b/browser/ui/views/toolbar/brave_toolbar_view.h index f316a2dd73c5..6ea9af3e9d68 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.h +++ b/browser/ui/views/toolbar/brave_toolbar_view.h @@ -6,17 +6,18 @@ #ifndef BRAVE_BROWSER_UI_VIEWS_TOOLBAR_BRAVE_TOOLBAR_VIEW_H_ #define BRAVE_BROWSER_UI_VIEWS_TOOLBAR_BRAVE_TOOLBAR_VIEW_H_ -#include "base/memory/raw_ptr.h" #include + +#include "base/memory/raw_ptr.h" #include "base/scoped_observation.h" -#include "ui/views/controls/textfield/textfield_controller.h" -#include "ui/views/controls/textfield/textfield.h" -#include "components/prefs/pref_service.h" #include "brave/components/brave_vpn/common/buildflags/buildflags.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "components/prefs/pref_member.h" +#include "components/prefs/pref_service.h" #include "ui/base/metadata/metadata_header_macros.h" +#include "ui/views/controls/textfield/textfield.h" +#include "ui/views/controls/textfield/textfield_controller.h" #if BUILDFLAG(ENABLE_BRAVE_VPN) class BraveVPNButton; @@ -29,8 +30,8 @@ class BraveToolbarView : public ToolbarView, public ProfileAttributesStorage::Observer { METADATA_HEADER(BraveToolbarView, ToolbarView) public: + void OnAddNote(const std::u16string& new_note); - void OnAddNote(); // Method to handle deleting all notes void OnDeleteAllNotes(); // Method for text input handling @@ -59,7 +60,8 @@ class BraveToolbarView : public ToolbarView, void ShowBookmarkBubble(const GURL& url, bool already_bookmarked) override; void ViewHierarchyChanged( const views::ViewHierarchyChangedDetails& details) override; - // void ContentsChanged(views::Textfield* sender, const std::u16string& new_contents) override; + // void ContentsChanged(views::Textfield* sender, const std::u16string& + // new_contents) override; private: void LoadImages() override; @@ -83,7 +85,7 @@ class BraveToolbarView : public ToolbarView, void OnProfileWasRemoved(const base::FilePath& profile_path, const std::u16string& profile_name) override; void ContentsChanged(views::Textfield* sender, - const std::u16string& new_contents); + const std::u16string& new_contents); void UpdateWalletButtonVisibility(); diff --git a/build/commands/lib/util.js b/build/commands/lib/util.js index a209966c7f56..90577e6fddcb 100644 --- a/build/commands/lib/util.js +++ b/build/commands/lib/util.js @@ -748,6 +748,7 @@ const util = { let ninjaOpts = [ '-C', options.outputDir || config.outputDir, targets.join(' '), + '-j8', '-k', num_compile_failure, ...config.extraNinjaOpts ] From 5792560d3d00a4d75992b34fb9e7dae35261b5b4 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Mon, 16 Sep 2024 22:55:37 +0530 Subject: [PATCH 04/21] removed the utils changes --- build/commands/lib/util.js | 1 - 1 file changed, 1 deletion(-) diff --git a/build/commands/lib/util.js b/build/commands/lib/util.js index 90577e6fddcb..a209966c7f56 100644 --- a/build/commands/lib/util.js +++ b/build/commands/lib/util.js @@ -748,7 +748,6 @@ const util = { let ninjaOpts = [ '-C', options.outputDir || config.outputDir, targets.join(' '), - '-j8', '-k', num_compile_failure, ...config.extraNinjaOpts ] From 759eeda74886c73a64fab7f553c6b6e67bcd87fd Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Thu, 26 Sep 2024 18:13:28 +0530 Subject: [PATCH 05/21] added the view for saved notes, although its not realtime as of now --- .../ui/views/toolbar/brave_toolbar_view.cc | 145 +++++++++++++++--- browser/ui/views/toolbar/brave_toolbar_view.h | 9 +- 2 files changed, 129 insertions(+), 25 deletions(-) diff --git a/browser/ui/views/toolbar/brave_toolbar_view.cc b/browser/ui/views/toolbar/brave_toolbar_view.cc index f41f30b63bd9..eade9ef8836f 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.cc +++ b/browser/ui/views/toolbar/brave_toolbar_view.cc @@ -37,6 +37,10 @@ #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/window_open_disposition_utils.h" #include "ui/events/event.h" +#include "ui/views/controls/button/label_button.h" +#include "ui/views/controls/label.h" +#include "ui/views/controls/scroll_view.h" +#include "ui/views/layout/box_layout.h" #include "ui/views/window/hit_test_utils.h" #if !BUILDFLAG(ENABLE_BRAVE_VPN) @@ -471,48 +475,79 @@ void BraveToolbarView::OnAddNote(const std::u16string& new_note) { if (!new_note.empty()) { notes_.push_back(base::UTF16ToUTF8(new_note)); SaveNotesToLocalStorage(); + LOG(INFO) << "Added new note: " << base::UTF16ToUTF8(new_note); + RefreshNotesView(); } } void BraveToolbarView::OnDeleteAllNotes() { if (!notes_.empty()) { + LOG(INFO) << "Deleting all " << notes_.size() << " notes"; notes_.clear(); SaveNotesToLocalStorage(); + RefreshNotesView(); } } // Save notes to preferences or a file (acting as local storage) void BraveToolbarView::SaveNotesToLocalStorage() { base::Value::List note_list; - for (const auto& note : notes_) { - LOG(ERROR) << note; note_list.Append(base::Value(note)); } if (pref_service_) { pref_service_->Set("custom_notes", base::Value(std::move(note_list))); pref_service_->CommitPendingWrite(); - LOG(ERROR) << "ADDED SUCCESSFULLY"; + LOG(INFO) << "Saved " << notes_.size() << " notes to local storage"; } else { LOG(ERROR) << "PrefService is not initialized."; } } -// Load notes from local storage (preferences) +void BraveToolbarView::DeleteNote(size_t index) { + if (index < notes_.size()) { + notes_.erase(notes_.begin() + index); + SaveNotesToLocalStorage(); + RefreshNotesView(); + } +} + +void BraveToolbarView::RefreshNotesView() { + LoadNotesFromLocalStorage(); + LOG(INFO) << "Refreshing notes view with " << notes_.size() << " notes"; + if (custom_dialog_) { + views::View* old_notes_view = + custom_dialog_->GetContentsView()->GetViewByID(kNotesViewID); + if (old_notes_view) { + views::View* new_notes_view = BuildNotesView(); + new_notes_view->SetID(kNotesViewID); + custom_dialog_->GetContentsView()->RemoveChildView(old_notes_view); + custom_dialog_->GetContentsView()->AddChildView(new_notes_view); + custom_dialog_->GetContentsView()->InvalidateLayout(); + LOG(INFO) << "Notes view refreshed in custom dialog"; + } else { + LOG(ERROR) << "Could not find old notes view to refresh"; + } + } else { + LOG(ERROR) << "Custom dialog is null during refresh"; + } +} + void BraveToolbarView::LoadNotesFromLocalStorage() { + notes_.clear(); if (pref_service_) { const base::Value* note_list_value = pref_service_->GetUserPrefValue("custom_notes"); if (note_list_value && note_list_value->is_list()) { const base::Value::List& note_list = note_list_value->GetList(); - notes_.clear(); for (const auto& note_value : note_list) { if (note_value.is_string()) { notes_.push_back(note_value.GetString()); } } } + LOG(INFO) << "Loaded " << notes_.size() << " notes from local storage"; } else { LOG(ERROR) << "PrefService is not initialized."; } @@ -552,14 +587,46 @@ void BraveToolbarView::UpdateWalletButtonVisibility() { } views::View* BraveToolbarView::BuildNotesView() { - auto* container = new views::View(); + auto container = std::make_unique(); container->SetLayoutManager(std::make_unique( views::BoxLayout::Orientation::kVertical)); - return container; + auto scroll_view = std::make_unique(); + auto notes_container = std::make_unique(); + notes_container->SetLayoutManager(std::make_unique( + views::BoxLayout::Orientation::kVertical)); + + LOG(INFO) << "Building notes view with " << notes_.size() << " notes"; + + for (size_t i = 0; i < notes_.size(); ++i) { + auto note_view = std::make_unique(); + note_view->SetLayoutManager(std::make_unique( + views::BoxLayout::Orientation::kHorizontal)); + + auto note_label = + std::make_unique(base::UTF8ToUTF16(notes_[i])); + note_view->AddChildView(std::move(note_label)); + + auto delete_button = std::make_unique( + base::BindRepeating(&BraveToolbarView::DeleteNote, + base::Unretained(this), i), + u"Delete"); + note_view->AddChildView(std::move(delete_button)); + + notes_container->AddChildView(std::move(note_view)); + LOG(INFO) << "Added note to view: " << notes_[i]; + } + + scroll_view->SetContents(std::move(notes_container)); + container->AddChildView(std::move(scroll_view)); + + return container.release(); } void BraveToolbarView::ShowCustomPopup() { + LoadNotesFromLocalStorage(); + LOG(INFO) << "Showing custom popup with " << notes_.size() << " notes"; + class CustomDialogDelegate : public views::DialogDelegateView { public: CustomDialogDelegate(BraveToolbarView* toolbar_view) @@ -569,22 +636,14 @@ void BraveToolbarView::ShowCustomPopup() { views::BoxLayout::Orientation::kVertical)); auto text_field = std::make_unique(); - auto* text_field_ptr = text_field.get(); + text_field_ = text_field.get(); AddChildView(std::move(text_field)); - text_field_ptr->SetPlaceholderText(u"Enter your note here"); + text_field_->SetPlaceholderText(u"Enter your note here"); auto add_note_button = std::make_unique( - base::BindRepeating( - [](views::Textfield* text_field, BraveToolbarView* toolbar_view) { - if (text_field && toolbar_view) { - std::u16string note_text = text_field->GetText(); - toolbar_view->OnAddNote(note_text); - text_field->SetText(u""); // Clear the text field here - } - }, - text_field_ptr, base::Unretained(toolbar_view_)), + base::BindRepeating(&CustomDialogDelegate::OnAddNote, + base::Unretained(this)), u"Add Note"); - AddChildView(std::move(add_note_button)); AddChildView(std::make_unique( @@ -592,19 +651,61 @@ void BraveToolbarView::ShowCustomPopup() { base::Unretained(toolbar_view_)), u"Delete All Notes")); - AddChildView(toolbar_view_->BuildNotesView()); + notes_container_ = AddChildView(std::make_unique()); + notes_container_->SetLayoutManager(std::make_unique( + views::BoxLayout::Orientation::kVertical)); + notes_container_->SetID(kNotesViewID); + + RefreshNotesView(); + + LOG(INFO) << "CustomDialogDelegate initialized with " + << toolbar_view_->notes_.size() << " notes"; } bool ShouldShowCloseButton() const override { return true; } private: + void OnAddNote() { + if (text_field_ && toolbar_view_) { + std::u16string note_text = text_field_->GetText(); + toolbar_view_->OnAddNote(note_text); + text_field_->SetText(u""); // Clear the text field + RefreshNotesView(); + } + } + + void RefreshNotesView() { + notes_container_->RemoveAllChildViews(); + for (size_t i = 0; i < toolbar_view_->notes_.size(); ++i) { + auto note_view = std::make_unique(); + note_view->SetLayoutManager(std::make_unique( + views::BoxLayout::Orientation::kHorizontal)); + + auto note_label = std::make_unique( + base::UTF8ToUTF16(toolbar_view_->notes_[i])); + note_view->AddChildView(std::move(note_label)); + + auto delete_button = std::make_unique( + base::BindRepeating(&BraveToolbarView::DeleteNote, + base::Unretained(toolbar_view_), i), + u"Delete"); + note_view->AddChildView(std::move(delete_button)); + + notes_container_->AddChildView(std::move(note_view)); + } + notes_container_->InvalidateLayout(); + notes_container_->SchedulePaint(); + } + raw_ptr toolbar_view_; raw_ptr text_field_; + raw_ptr notes_container_; }; + custom_dialog_ = new CustomDialogDelegate(this); views::Widget::CreateWindowWithContext( - new CustomDialogDelegate(this), - browser_view_->GetWidget()->GetNativeWindow(), gfx::Rect(300, 300)) + custom_dialog_, browser_view_->GetWidget()->GetNativeWindow(), + gfx::Rect(300, 300)) ->Show(); } diff --git a/browser/ui/views/toolbar/brave_toolbar_view.h b/browser/ui/views/toolbar/brave_toolbar_view.h index 6ea9af3e9d68..0f92aa25da93 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.h +++ b/browser/ui/views/toolbar/brave_toolbar_view.h @@ -34,7 +34,10 @@ class BraveToolbarView : public ToolbarView, // Method to handle deleting all notes void OnDeleteAllNotes(); - // Method for text input handling + void DeleteNote(size_t index); + void RefreshNotesView(); + void ShowCustomPopup(); + void LoadNotesFromLocalStorage(); explicit BraveToolbarView(Browser* browser, BrowserView* browser_view); ~BraveToolbarView() override; @@ -69,7 +72,6 @@ class BraveToolbarView : public ToolbarView, void ResetButtonBounds(); void SaveNotesToLocalStorage(); void UpdateBookmarkVisibility(); - void LoadNotesFromLocalStorage(); void OnNoteAdded(const std::u16string& new_note); void ContentsChanged(); views::View* BuildNotesView(); @@ -78,7 +80,8 @@ class BraveToolbarView : public ToolbarView, raw_ptr text_field_ = nullptr; raw_ptr pref_service_ = nullptr; raw_ptr custom_button_ = nullptr; - void ShowCustomPopup(); + static constexpr int kNotesViewID = 1001; // Choose a unique ID + raw_ptr custom_dialog_ = nullptr; // ProfileAttributesStorage::Observer: void OnProfileAdded(const base::FilePath& profile_path) override; From 30e6bf386611cc639143a7e02c00978e2c46900c Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Mon, 30 Sep 2024 23:48:41 +0530 Subject: [PATCH 06/21] added webui page for ping://custom-notes --- browser/ui/BUILD.gn | 2 + .../brave_custom_notes_ui.cc | 29 +++++ .../brave_custom_notes_ui.h | 17 +++ .../webui/brave_web_ui_controller_factory.cc | 6 +- .../chrome/common/webui_url_constants.cc | 3 +- .../resources/page/BUILD.gn | 17 +++ .../resources/page/brave_custom_notes.html | 12 ++ .../resources/page/brave_custom_notes.tsx | 104 ++++++++++++++++++ .../resources/page/tsconfig.json | 9 ++ components/constants/webui_url_constants.h | 2 + .../resources/brave_components_resources.grd | 1 + 11 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc create mode 100644 browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h create mode 100644 components/brave_custom_notes/resources/page/BUILD.gn create mode 100644 components/brave_custom_notes/resources/page/brave_custom_notes.html create mode 100644 components/brave_custom_notes/resources/page/brave_custom_notes.tsx create mode 100644 components/brave_custom_notes/resources/page/tsconfig.json diff --git a/browser/ui/BUILD.gn b/browser/ui/BUILD.gn index ea3e39158189..b9e2be063e0d 100644 --- a/browser/ui/BUILD.gn +++ b/browser/ui/BUILD.gn @@ -239,6 +239,8 @@ source_set("ui") { "webui/private_new_tab_page/brave_private_new_tab_page_handler.h", "webui/private_new_tab_page/brave_private_new_tab_ui.cc", "webui/private_new_tab_page/brave_private_new_tab_ui.h", + "webui/brave_custom_notes/brave_custom_notes_ui.cc", + "webui/brave_custom_notes/brave_custom_notes_ui.h", "webui/settings/brave_adblock_handler.cc", "webui/settings/brave_adblock_handler.h", "webui/settings/brave_appearance_handler.cc", diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc new file mode 100644 index 000000000000..23461e900e35 --- /dev/null +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc @@ -0,0 +1,29 @@ +#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h" + +#include "chrome/browser/profiles/profile.h" +#include "components/grit/brave_components_resources.h" // For resources like HTML +#include "components/strings/grit/components_strings.h" // For string resources +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +// Define the custom notes host constant +namespace chrome { +const char kBraveCustomNotesHost[] = "custom-notes"; +} + +BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + // Create and add a WebUIDataSource for our hello world page + content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd( + Profile::FromWebUI(web_ui), chrome::kBraveCustomNotesHost); + + // Adding a simple HTML resource and default fallback + source->AddResourcePath("brave_custom_notes.html", + IDR_BRAVE_CUSTOM_NOTES_HTML); + source->SetDefaultResource(IDR_BRAVE_CUSTOM_NOTES_HTML); + + // Adding a string to the source that can be used in the HTML + source->AddString("message", "Hello World"); +} + +BraveCustomNotesUI::~BraveCustomNotesUI() = default; diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h new file mode 100644 index 000000000000..3d0404e01b00 --- /dev/null +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h @@ -0,0 +1,17 @@ +#ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_UI_H_ +#define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_UI_H_ + +#include "content/public/browser/web_ui_controller.h" + +class BraveCustomNotesUI : public content::WebUIController { + public: + explicit BraveCustomNotesUI(content::WebUI* web_ui); + ~BraveCustomNotesUI() override; + + private: + // Prevent copy and assign + BraveCustomNotesUI(const BraveCustomNotesUI&) = delete; + BraveCustomNotesUI& operator=(const BraveCustomNotesUI&) = delete; +}; + +#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_UI_H_ diff --git a/browser/ui/webui/brave_web_ui_controller_factory.cc b/browser/ui/webui/brave_web_ui_controller_factory.cc index fe012671ba9f..c5ed400b3b44 100644 --- a/browser/ui/webui/brave_web_ui_controller_factory.cc +++ b/browser/ui/webui/brave_web_ui_controller_factory.cc @@ -15,6 +15,7 @@ #include "brave/browser/ethereum_remote_client/buildflags/buildflags.h" #include "brave/browser/ui/webui/brave_adblock_internals_ui.h" #include "brave/browser/ui/webui/brave_adblock_ui.h" +#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h" #include "brave/browser/ui/webui/brave_rewards_internals_ui.h" #include "brave/browser/ui/webui/brave_rewards_page_ui.h" #include "brave/browser/ui/webui/skus_internals_ui.h" @@ -112,6 +113,8 @@ WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { return new BraveAdblockUI(web_ui, url.host()); } else if (host == kAdblockInternalsHost) { return new BraveAdblockInternalsUI(web_ui, url.host()); + } else if (host == kBraveCustomNotesHost) { + return new BraveCustomNotesUI(web_ui); } else if (host == kSkusInternalsHost) { return new SkusInternalsUI(web_ui, url.host()); #if !BUILDFLAG(IS_ANDROID) @@ -260,7 +263,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, url.host_piece() == brave_player::kBravePlayerHost) || #endif url.host_piece() == kRewardsPageHost || - url.host_piece() == kRewardsInternalsHost) { + url.host_piece() == kRewardsInternalsHost || + url.host_piece() == kBraveCustomNotesHost) { return &NewWebUI; } diff --git a/chromium_src/chrome/common/webui_url_constants.cc b/chromium_src/chrome/common/webui_url_constants.cc index 60af8f2f3144..ad76efa77fd4 100644 --- a/chromium_src/chrome/common/webui_url_constants.cc +++ b/chromium_src/chrome/common/webui_url_constants.cc @@ -4,13 +4,14 @@ * You can obtain one at https://mozilla.org/MPL/2.0/. */ #include "brave/components/constants/webui_url_constants.h" + #include "brave/components/ipfs/buildflags/buildflags.h" #include "chrome/common/webui_url_constants.h" #define kChromeUIAttributionInternalsHost \ kChromeUIAttributionInternalsHost, kAdblockHost, kAdblockInternalsHost, \ kRewardsPageHost, kRewardsInternalsHost, kWelcomeHost, kWalletPageHost, \ - kTorInternalsHost, kSkusInternalsHost + kTorInternalsHost, kSkusInternalsHost, kBraveCustomNotesHost #define kPerformanceSubPage kPerformanceSubPage_UnUsed #if BUILDFLAG(ENABLE_IPFS_INTERNALS_WEBUI) diff --git a/components/brave_custom_notes/resources/page/BUILD.gn b/components/brave_custom_notes/resources/page/BUILD.gn new file mode 100644 index 000000000000..007927bb0c2b --- /dev/null +++ b/components/brave_custom_notes/resources/page/BUILD.gn @@ -0,0 +1,17 @@ +import("//brave/components/common/typescript.gni") + +transpile_web_ui("brave_custom_notes_ui") { + entry_points = [[ + "brave_custom_notes", + rebase_path("brave_custom_notes.tsx"), + ]] + resource_name = "brave_custom_notes" + +} + +pack_web_resources("generated_resources") { + resource_name = "brave_custom_notes" + output_dir = + "$root_gen_dir/brave/components/brave_custom_notes/resources/page" + deps = [ ":brave_custom_notes" ] +} \ No newline at end of file diff --git a/components/brave_custom_notes/resources/page/brave_custom_notes.html b/components/brave_custom_notes/resources/page/brave_custom_notes.html new file mode 100644 index 000000000000..8f31a4213753 --- /dev/null +++ b/components/brave_custom_notes/resources/page/brave_custom_notes.html @@ -0,0 +1,12 @@ + + + + + + Custom Notes + + +

Brave Custom Notes Ferature

+ + + \ No newline at end of file diff --git a/components/brave_custom_notes/resources/page/brave_custom_notes.tsx b/components/brave_custom_notes/resources/page/brave_custom_notes.tsx new file mode 100644 index 000000000000..7f7ed6d6851c --- /dev/null +++ b/components/brave_custom_notes/resources/page/brave_custom_notes.tsx @@ -0,0 +1,104 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at https://mozilla.org/MPL/2.0/. */ +import * as React from 'react'; +import { useState } from 'react'; +import styled from 'styled-components'; + +const NotesContainer = styled.div` + display: flex; + flex-direction: column; + align-items: center; + padding: 20px; + max-width: 600px; + margin: 0 auto; + background-color: #f0f4f8; + border-radius: 8px; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); +`; + +const Title = styled.h1` + font-size: 24px; + color: #333; + margin-bottom: 20px; +`; + +const NoteInput = styled.textarea` + width: 100%; + padding: 10px; + font-size: 16px; + border: 2px solid #ccc; + border-radius: 5px; + margin-bottom: 15px; + resize: none; + min-height: 80px; +`; + +const AddButton = styled.button` + background-color: #007bff; + color: white; + border: none; + padding: 10px 20px; + font-size: 16px; + border-radius: 5px; + cursor: pointer; + &:hover { + background-color: #0056b3; + } +`; + +const NotesList = styled.ul` + list-style-type: none; + padding: 0; + margin: 20px 0; + width: 100%; +`; + +const NoteItem = styled.li` + background-color: #fff; + padding: 10px; + border-radius: 5px; + margin-bottom: 10px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); +`; + +const NoNotesMessage = styled.p` + font-size: 16px; + color: #999; +`; + +const Notes: React.FC = () => { + const [note, setNote] = useState(''); + const [notesList, setNotesList] = useState([]); + + const handleAddNote = () => { + if (note.trim()) { + setNotesList([...notesList, note]); + setNote(''); + } + }; + + return ( + + My Notes + setNote(e.target.value)} + placeholder="Write a new note..." + /> + Add Note + + {notesList.length === 0 ? ( + No notes added yet! + ) : ( + + {notesList.map((note, index) => ( + {note} + ))} + + )} + + ); +}; + +export default Notes; diff --git a/components/brave_custom_notes/resources/page/tsconfig.json b/components/brave_custom_notes/resources/page/tsconfig.json new file mode 100644 index 000000000000..9d2e1f99cb58 --- /dev/null +++ b/components/brave_custom_notes/resources/page/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../../../tsconfig", + "include": [ + "**/*.ts", + "**/*.tsx", + "**/*.d.ts", + "../definitions/*.d.ts" + ] +} \ No newline at end of file diff --git a/components/constants/webui_url_constants.h b/components/constants/webui_url_constants.h index cc2f73067dfc..4e08f0c19aa6 100644 --- a/components/constants/webui_url_constants.h +++ b/components/constants/webui_url_constants.h @@ -83,6 +83,8 @@ inline constexpr char kSpeedreaderPanelHost[] = "brave-speedreader.top-chrome"; inline constexpr char kShortcutsURL[] = "chrome://settings/system/shortcuts"; inline constexpr char kChatUIURL[] = "chrome-untrusted://chat/"; inline constexpr char kChatUIHost[] = "chat"; +inline constexpr char kBraveCustomNotesHost[] = "custom-notes"; +inline constexpr char16_t kBraveCustomNotesURL[] = u"chrome://custom-notes/"; inline constexpr char16_t kTransactionSimulationLearnMoreURL[] = u"https://github.com/brave/brave-browser/wiki/Transaction-Simulation"; diff --git a/components/resources/brave_components_resources.grd b/components/resources/brave_components_resources.grd index c51e26a95d9c..cf1ab3c124df 100644 --- a/components/resources/brave_components_resources.grd +++ b/components/resources/brave_components_resources.grd @@ -8,6 +8,7 @@ + From 9a12273fbce8cf287c97cd6012c4569e154dcc7a Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Tue, 1 Oct 2024 23:25:23 +0530 Subject: [PATCH 07/21] added changes in ids.spec --- browser/ui/BUILD.gn | 1 + .../resources/page/BUILD.gn | 4 +- .../resources/page/brave_custom_notes.html | 23 +-- .../resources/page/brave_custom_notes.tsx | 132 ++++-------------- .../resources/page/container.tsx | 104 ++++++++++++++ components/resources/BUILD.gn | 2 + resources/resource_ids.spec | 7 +- 7 files changed, 158 insertions(+), 115 deletions(-) create mode 100644 components/brave_custom_notes/resources/page/container.tsx diff --git a/browser/ui/BUILD.gn b/browser/ui/BUILD.gn index b9e2be063e0d..804c53c6cf58 100644 --- a/browser/ui/BUILD.gn +++ b/browser/ui/BUILD.gn @@ -972,6 +972,7 @@ source_set("ui") { "//brave/components/brave_private_new_tab_ui/common", "//brave/components/brave_private_new_tab_ui/common:mojom", "//brave/components/brave_private_new_tab_ui/resources/page:generated_resources", + "//brave/components/brave_custom_notes/resources/page:generated_resources", "//brave/components/brave_rewards/browser", "//brave/components/brave_rewards/resources/rewards_panel:brave_rewards_panel_generated", "//brave/components/brave_rewards/resources/tip_panel:tip_panel_generated", diff --git a/components/brave_custom_notes/resources/page/BUILD.gn b/components/brave_custom_notes/resources/page/BUILD.gn index 007927bb0c2b..6facdfeeeb69 100644 --- a/components/brave_custom_notes/resources/page/BUILD.gn +++ b/components/brave_custom_notes/resources/page/BUILD.gn @@ -1,6 +1,6 @@ import("//brave/components/common/typescript.gni") -transpile_web_ui("brave_custom_notes_ui") { +transpile_web_ui("brave_custom_notes") { entry_points = [[ "brave_custom_notes", rebase_path("brave_custom_notes.tsx"), @@ -12,6 +12,6 @@ transpile_web_ui("brave_custom_notes_ui") { pack_web_resources("generated_resources") { resource_name = "brave_custom_notes" output_dir = - "$root_gen_dir/brave/components/brave_custom_notes/resources/page" + "$root_gen_dir/brave/components/brave_custom_notes/resources/page/" deps = [ ":brave_custom_notes" ] } \ No newline at end of file diff --git a/components/brave_custom_notes/resources/page/brave_custom_notes.html b/components/brave_custom_notes/resources/page/brave_custom_notes.html index 8f31a4213753..f41c2731cc57 100644 --- a/components/brave_custom_notes/resources/page/brave_custom_notes.html +++ b/components/brave_custom_notes/resources/page/brave_custom_notes.html @@ -1,12 +1,19 @@ - - + + - - - Custom Notes + + +Brave Custom Notes + + + + + + + + -

Brave Custom Notes Ferature

+
- - \ No newline at end of file + diff --git a/components/brave_custom_notes/resources/page/brave_custom_notes.tsx b/components/brave_custom_notes/resources/page/brave_custom_notes.tsx index 7f7ed6d6851c..e0179c9f9566 100644 --- a/components/brave_custom_notes/resources/page/brave_custom_notes.tsx +++ b/components/brave_custom_notes/resources/page/brave_custom_notes.tsx @@ -1,104 +1,28 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at https://mozilla.org/MPL/2.0/. */ -import * as React from 'react'; -import { useState } from 'react'; -import styled from 'styled-components'; - -const NotesContainer = styled.div` - display: flex; - flex-direction: column; - align-items: center; - padding: 20px; - max-width: 600px; - margin: 0 auto; - background-color: #f0f4f8; - border-radius: 8px; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); -`; - -const Title = styled.h1` - font-size: 24px; - color: #333; - margin-bottom: 20px; -`; - -const NoteInput = styled.textarea` - width: 100%; - padding: 10px; - font-size: 16px; - border: 2px solid #ccc; - border-radius: 5px; - margin-bottom: 15px; - resize: none; - min-height: 80px; -`; - -const AddButton = styled.button` - background-color: #007bff; - color: white; - border: none; - padding: 10px 20px; - font-size: 16px; - border-radius: 5px; - cursor: pointer; - &:hover { - background-color: #0056b3; - } -`; - -const NotesList = styled.ul` - list-style-type: none; - padding: 0; - margin: 20px 0; - width: 100%; -`; - -const NoteItem = styled.li` - background-color: #fff; - padding: 10px; - border-radius: 5px; - margin-bottom: 10px; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); -`; - -const NoNotesMessage = styled.p` - font-size: 16px; - color: #999; -`; - -const Notes: React.FC = () => { - const [note, setNote] = useState(''); - const [notesList, setNotesList] = useState([]); - - const handleAddNote = () => { - if (note.trim()) { - setNotesList([...notesList, note]); - setNote(''); - } - }; - - return ( - - My Notes - setNote(e.target.value)} - placeholder="Write a new note..." - /> - Add Note - - {notesList.length === 0 ? ( - No notes added yet! - ) : ( - - {notesList.map((note, index) => ( - {note} - ))} - - )} - - ); -}; - -export default Notes; +// Copyright (c) 2022 The Brave Authors. All rights reserved. +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// you can obtain one at https://mozilla.org/MPL/2.0/. + +import * as React from 'react' +import { createRoot } from 'react-dom/client' +import { initLocale } from 'brave-ui' + +import { loadTimeData } from '../../../common/loadTimeData' +import BraveCoreThemeProvider from '../../../common/BraveCoreThemeProvider' +import Notes from './container' + +function App() { + return ( + + + + ) +} + +function initialize() { + initLocale(loadTimeData.data_) + const root = createRoot(document.getElementById('mountPoint')!) + root.render() +} + +document.addEventListener('DOMContentLoaded', initialize) diff --git a/components/brave_custom_notes/resources/page/container.tsx b/components/brave_custom_notes/resources/page/container.tsx new file mode 100644 index 000000000000..72c85580b312 --- /dev/null +++ b/components/brave_custom_notes/resources/page/container.tsx @@ -0,0 +1,104 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at https://mozilla.org/MPL/2.0/. */ +import * as React from 'react'; +import { useState } from 'react'; +import styled from 'styled-components'; + +const NotesContainer = styled.div` + display: flex; + flex-direction: column; + align-items: center; + padding: 20px; + max-width: 600px; + margin: 0 auto; + background-color: #f0f4f8; + border-radius: 8px; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); + `; + +const Title = styled.h1` + font-size: 24px; + color: #333; + margin-bottom: 20px; + `; + +const NoteInput = styled.textarea` + width: 100%; + padding: 10px; + font-size: 16px; + border: 2px solid #ccc; + border-radius: 5px; + margin-bottom: 15px; + resize: none; + min-height: 80px; + `; + +const AddButton = styled.button` + background-color: #007bff; + color: white; + border: none; + padding: 10px 20px; + font-size: 16px; + border-radius: 5px; + cursor: pointer; + &:hover { + background-color: #0056b3; + } + `; + +const NotesList = styled.ul` + list-style-type: none; + padding: 0; + margin: 20px 0; + width: 100%; + `; + +const NoteItem = styled.li` + background-color: #fff; + padding: 10px; + border-radius: 5px; + margin-bottom: 10px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + `; + +const NoNotesMessage = styled.p` + font-size: 16px; + color: #999; + `; + +const Notes: React.FC = () => { + const [note, setNote] = useState(''); + const [notesList, setNotesList] = useState([]); + + const handleAddNote = () => { + if (note.trim()) { + setNotesList([...notesList, note]); + setNote(''); + } + }; + + return ( + + My Notes + setNote(e.target.value)} + placeholder="Write a new note..." + /> + Add Note + + {notesList.length === 0 ? ( + No notes added yet! + ) : ( + + {notesList.map((note, index) => ( + {note} + ))} + + )} + + ); +}; + +export default Notes; diff --git a/components/resources/BUILD.gn b/components/resources/BUILD.gn index 742e2ddba7b7..3393f9971c9e 100644 --- a/components/resources/BUILD.gn +++ b/components/resources/BUILD.gn @@ -86,6 +86,7 @@ repack("resources") { "//brave/components/brave_news/browser/resources:generated_resources", "//brave/components/brave_news/browser/resources:generated_resources", "//brave/components/brave_private_new_tab_ui/resources/page:generated_resources", + "//brave/components/brave_custom_notes/resources/page:generated_resources", "//brave/components/brave_shields/resources/cookie_list_opt_in:cookie_list_opt_in_generated", "//brave/components/brave_shields/resources/panel:brave_shields_panel_generated", "//brave/components/brave_welcome_ui:generated_resources", @@ -97,6 +98,7 @@ repack("resources") { "$root_gen_dir/brave/components/brave_new_tab/resources/brave_new_tab_generated.pak", "$root_gen_dir/brave/components/brave_news/browser/resources/brave_news_internals_generated.pak", "$root_gen_dir/brave/components/brave_private_new_tab/resources/page/brave_private_new_tab_generated.pak", + "$root_gen_dir/brave/components/brave_custom_notes/resources/page/brave_custom_notes_generated.pak", "$root_gen_dir/brave/components/brave_shields/resources/cookie_list_opt_in/cookie_list_opt_in_generated.pak", "$root_gen_dir/brave/components/brave_shields/resources/panel/brave_shields_panel_generated.pak", "$root_gen_dir/brave/components/brave_welcome/resources/brave_welcome_generated.pak", diff --git a/resources/resource_ids.spec b/resources/resource_ids.spec index 861561fc8566..80c6fe067a3b 100644 --- a/resources/resource_ids.spec +++ b/resources/resource_ids.spec @@ -235,5 +235,10 @@ }, "brave/components/ping_ai_copilot/resources.grd": { "includes": [63100], - } + }, + # This file is generated during the build. + "<(SHARED_INTERMEDIATE_DIR)/brave/web-ui-brave_custom_notes/brave_custom_notes.grd": { + "META": {"sizes": {"includes": [10]}}, + "includes": [63200], + }, } From 3a8a60d0d685571d0347e0ffb4d6357630de4dde Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Wed, 2 Oct 2024 23:02:53 +0530 Subject: [PATCH 08/21] some changes for better approach --- .../ui/webui/brave_custom_notes/brave_custom_notes_ui.cc | 3 +-- components/brave_custom_notes/resources/page/BUILD.gn | 4 ++-- .../page/{brave_custom_notes.html => custom_notes.html} | 6 +++--- .../page/{brave_custom_notes.tsx => custom_notes.tsx} | 0 components/resources/brave_components_resources.grd | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) rename components/brave_custom_notes/resources/page/{brave_custom_notes.html => custom_notes.html} (81%) rename components/brave_custom_notes/resources/page/{brave_custom_notes.tsx => custom_notes.tsx} (100%) diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc index 23461e900e35..6af3df271fe0 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc @@ -18,8 +18,7 @@ BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui) Profile::FromWebUI(web_ui), chrome::kBraveCustomNotesHost); // Adding a simple HTML resource and default fallback - source->AddResourcePath("brave_custom_notes.html", - IDR_BRAVE_CUSTOM_NOTES_HTML); + source->AddResourcePath("custom_notes.html", IDR_BRAVE_CUSTOM_NOTES_HTML); source->SetDefaultResource(IDR_BRAVE_CUSTOM_NOTES_HTML); // Adding a string to the source that can be used in the HTML diff --git a/components/brave_custom_notes/resources/page/BUILD.gn b/components/brave_custom_notes/resources/page/BUILD.gn index 6facdfeeeb69..a7dda645d0e5 100644 --- a/components/brave_custom_notes/resources/page/BUILD.gn +++ b/components/brave_custom_notes/resources/page/BUILD.gn @@ -2,8 +2,8 @@ import("//brave/components/common/typescript.gni") transpile_web_ui("brave_custom_notes") { entry_points = [[ - "brave_custom_notes", - rebase_path("brave_custom_notes.tsx"), + "custom_notes", + rebase_path("./custom_notes.tsx"), ]] resource_name = "brave_custom_notes" diff --git a/components/brave_custom_notes/resources/page/brave_custom_notes.html b/components/brave_custom_notes/resources/page/custom_notes.html similarity index 81% rename from components/brave_custom_notes/resources/page/brave_custom_notes.html rename to components/brave_custom_notes/resources/page/custom_notes.html index f41c2731cc57..94bbe8f69a07 100644 --- a/components/brave_custom_notes/resources/page/brave_custom_notes.html +++ b/components/brave_custom_notes/resources/page/custom_notes.html @@ -1,5 +1,5 @@ - + @@ -11,9 +11,9 @@ - -
+ +
diff --git a/components/brave_custom_notes/resources/page/brave_custom_notes.tsx b/components/brave_custom_notes/resources/page/custom_notes.tsx similarity index 100% rename from components/brave_custom_notes/resources/page/brave_custom_notes.tsx rename to components/brave_custom_notes/resources/page/custom_notes.tsx diff --git a/components/resources/brave_components_resources.grd b/components/resources/brave_components_resources.grd index cf1ab3c124df..25235405a4e4 100644 --- a/components/resources/brave_components_resources.grd +++ b/components/resources/brave_components_resources.grd @@ -8,7 +8,7 @@ - + From 8cc4fb4170e4e84c1ab1e4e875364a6f4ee8c2c2 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Thu, 3 Oct 2024 17:18:00 +0530 Subject: [PATCH 09/21] Now Working --- .../brave_custom_notes_ui.cc | 19 +++++++------------ .../brave_custom_notes_ui.h | 2 +- .../webui/brave_web_ui_controller_factory.cc | 2 +- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc index 6af3df271fe0..c8cdbec73eaf 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc @@ -1,25 +1,20 @@ #include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h" +#include "brave/browser/ui/webui/brave_webui_source.h" +#include "brave/components/brave_custom_notes/resources/page/grit/brave_custom_notes_generated_map.h" #include "chrome/browser/profiles/profile.h" #include "components/grit/brave_components_resources.h" // For resources like HTML #include "components/strings/grit/components_strings.h" // For string resources #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" -// Define the custom notes host constant -namespace chrome { -const char kBraveCustomNotesHost[] = "custom-notes"; -} - -BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui) +BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui, + const std::string& name) : WebUIController(web_ui) { // Create and add a WebUIDataSource for our hello world page - content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd( - Profile::FromWebUI(web_ui), chrome::kBraveCustomNotesHost); - - // Adding a simple HTML resource and default fallback - source->AddResourcePath("custom_notes.html", IDR_BRAVE_CUSTOM_NOTES_HTML); - source->SetDefaultResource(IDR_BRAVE_CUSTOM_NOTES_HTML); + content::WebUIDataSource* source = CreateAndAddWebUIDataSource( + web_ui, name, kBraveCustomNotesGenerated, kBraveCustomNotesGeneratedSize, + IDR_BRAVE_CUSTOM_NOTES_HTML); // Adding a string to the source that can be used in the HTML source->AddString("message", "Hello World"); diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h index 3d0404e01b00..469d2febfbbd 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h @@ -5,7 +5,7 @@ class BraveCustomNotesUI : public content::WebUIController { public: - explicit BraveCustomNotesUI(content::WebUI* web_ui); + explicit BraveCustomNotesUI(content::WebUI* web_ui, const std::string& name); ~BraveCustomNotesUI() override; private: diff --git a/browser/ui/webui/brave_web_ui_controller_factory.cc b/browser/ui/webui/brave_web_ui_controller_factory.cc index c5ed400b3b44..d7778afea9f6 100644 --- a/browser/ui/webui/brave_web_ui_controller_factory.cc +++ b/browser/ui/webui/brave_web_ui_controller_factory.cc @@ -114,7 +114,7 @@ WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { } else if (host == kAdblockInternalsHost) { return new BraveAdblockInternalsUI(web_ui, url.host()); } else if (host == kBraveCustomNotesHost) { - return new BraveCustomNotesUI(web_ui); + return new BraveCustomNotesUI(web_ui, url.host()); } else if (host == kSkusInternalsHost) { return new SkusInternalsUI(web_ui, url.host()); #if !BUILDFLAG(IS_ANDROID) From c933e8d4bf268315808585992624971eb3543242 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Tue, 8 Oct 2024 00:38:07 +0530 Subject: [PATCH 10/21] integrated mojom --- browser/brave_content_browser_client.cc | 4 + browser/sources.gni | 2 + browser/ui/BUILD.gn | 4 + .../brave_custom_notes_handler.cc | 88 +++++++++++++ .../brave_custom_notes_handler.h | 55 ++++++++ .../brave_custom_notes_ui.cc | 31 +++-- .../brave_custom_notes_ui.h | 33 +++-- .../brave_private_new_tab_page_handler.cc | 18 ++- components/brave_custom_notes/common/BUILD.gn | 18 +++ .../common/brave_custom_notes.mojom | 50 ++++++++ .../brave_custom_notes/common/constants.h | 31 +++++ .../resources/page/BUILD.gn | 2 +- .../page/api/brave_custom_notes_handler.ts | 38 ++++++ .../resources/page/container.tsx | 117 ++++++++++-------- .../resources/page/custom_notes.html | 33 +++-- .../resources/brave_components_strings.grd | 17 +++ components/webui/webui_resources.cc | 25 ++++ 17 files changed, 480 insertions(+), 86 deletions(-) create mode 100644 browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc create mode 100644 browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h create mode 100644 components/brave_custom_notes/common/BUILD.gn create mode 100644 components/brave_custom_notes/common/brave_custom_notes.mojom create mode 100644 components/brave_custom_notes/common/constants.h create mode 100644 components/brave_custom_notes/resources/page/api/brave_custom_notes_handler.ts diff --git a/browser/brave_content_browser_client.cc b/browser/brave_content_browser_client.cc index a6f432435d0d..6b62bb2931aa 100644 --- a/browser/brave_content_browser_client.cc +++ b/browser/brave_content_browser_client.cc @@ -221,6 +221,7 @@ using extensions::ChromeContentBrowserClientExtensionsPart; #if !BUILDFLAG(IS_ANDROID) #include "brave/browser/new_tab/new_tab_shows_navigation_throttle.h" #include "brave/browser/ui/geolocation/brave_geolocation_permission_tab_helper.h" +#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h" #include "brave/browser/ui/webui/brave_news_internals/brave_news_internals_ui.h" #include "brave/browser/ui/webui/brave_rewards/rewards_panel_ui.h" #include "brave/browser/ui/webui/brave_rewards/tip_panel_ui.h" @@ -231,6 +232,7 @@ using extensions::ChromeContentBrowserClientExtensionsPart; #include "brave/browser/ui/webui/brave_wallet/wallet_panel_ui.h" #include "brave/browser/ui/webui/new_tab_page/brave_new_tab_ui.h" #include "brave/browser/ui/webui/private_new_tab_page/brave_private_new_tab_ui.h" +#include "brave/components/brave_custom_notes/common/brave_custom_notes.mojom.h" #include "brave/components/brave_new_tab_ui/brave_new_tab_page.mojom.h" #include "brave/components/brave_news/common/brave_news.mojom.h" #include "brave/components/brave_news/common/features.h" @@ -823,6 +825,8 @@ void BraveContentBrowserClient::RegisterBrowserInterfaceBindersForFrame( brave_wallet::mojom::PanelHandlerFactory, WalletPanelUI>(map); content::RegisterWebUIControllerInterfaceBinder< brave_private_new_tab::mojom::PageHandler, BravePrivateNewTabUI>(map); + content::RegisterWebUIControllerInterfaceBinder< + brave_custom_notes::mojom::NotesPageHandler, BraveCustomNotesUI>(map); content::RegisterWebUIControllerInterfaceBinder< brave_shields::mojom::PanelHandlerFactory, ShieldsPanelUI>(map); if (base::FeatureList::IsEnabled( diff --git a/browser/sources.gni b/browser/sources.gni index 290a9755c978..d1ce228ea341 100644 --- a/browser/sources.gni +++ b/browser/sources.gni @@ -146,6 +146,8 @@ brave_chrome_browser_deps = [ "//brave/components/brave_perf_predictor/browser", "//brave/components/brave_private_new_tab_ui/common", "//brave/components/brave_private_new_tab_ui/common:mojom", + "//brave/components/brave_custom_notes/common", + "//brave/components/brave_custom_notes/common:mojom", "//brave/components/brave_referrals/browser", "//brave/components/brave_rewards/common", "//brave/components/brave_rewards/common:features", diff --git a/browser/ui/BUILD.gn b/browser/ui/BUILD.gn index 804c53c6cf58..bb26ef3d6696 100644 --- a/browser/ui/BUILD.gn +++ b/browser/ui/BUILD.gn @@ -239,6 +239,8 @@ source_set("ui") { "webui/private_new_tab_page/brave_private_new_tab_page_handler.h", "webui/private_new_tab_page/brave_private_new_tab_ui.cc", "webui/private_new_tab_page/brave_private_new_tab_ui.h", + "webui/brave_custom_notes/brave_custom_notes_handler.cc", + "webui/brave_custom_notes/brave_custom_notes_handler.h", "webui/brave_custom_notes/brave_custom_notes_ui.cc", "webui/brave_custom_notes/brave_custom_notes_ui.h", "webui/settings/brave_adblock_handler.cc", @@ -972,6 +974,8 @@ source_set("ui") { "//brave/components/brave_private_new_tab_ui/common", "//brave/components/brave_private_new_tab_ui/common:mojom", "//brave/components/brave_private_new_tab_ui/resources/page:generated_resources", + "//brave/components/brave_custom_notes/common", + "//brave/components/brave_custom_notes/common:mojom", "//brave/components/brave_custom_notes/resources/page:generated_resources", "//brave/components/brave_rewards/browser", "//brave/components/brave_rewards/resources/rewards_panel:brave_rewards_panel_generated", diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc new file mode 100644 index 000000000000..dddc3ea7a487 --- /dev/null +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc @@ -0,0 +1,88 @@ +// Copyright (c) 2024 The Brave Authors. All rights reserved. +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// you can obtain one at http://mozilla.org/MPL/2.0/. + +#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h" + +#include + +#include "base/functional/bind.h" +#include "base/strings/utf_string_conversions.h" +#include "brave_custom_notes_handler.h" + +BraveCustomNotesPageHandler::BraveCustomNotesPageHandler( + content::WebContents* web_contents, + mojo::PendingReceiver receiver) + : web_contents_(web_contents), receiver_(this, std::move(receiver)) {} + +BraveCustomNotesPageHandler::~BraveCustomNotesPageHandler() = default; + +void BraveCustomNotesPageHandler::SetClientPage( + mojo::PendingRemote page) { + page_.Bind(std::move(page)); +} + +void BraveCustomNotesPageHandler::CreateNote(const std::string& title, + const std::string& content, + CreateNoteCallback callback) { + auto new_note = brave_custom_notes::mojom::Note::New(); + new_note->id = notes_.size() + 1; // Simple ID generation + new_note->title = title; + new_note->content = content; + + notes_.push_back(std::move(new_note)); + + std::move(callback).Run(true); + + if (page_) { + page_->OnNotesUpdated(notes_); + } +} + +void BraveCustomNotesPageHandler::EditNote(int32_t note_id, + const std::string& new_title, + const std::string& new_content, + EditNoteCallback callback) { + auto it = + std::find_if(notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); + + if (it != notes_.end()) { + (*it)->title = new_title; + (*it)->content = new_content; + std::move(callback).Run(true); + + if (page_) { + page_->OnNotesUpdated(notes_); + } + } else { + std::move(callback).Run(false); + } +} + +void BraveCustomNotesPageHandler::DeleteNote(int32_t note_id, + DeleteNoteCallback callback) { + auto it = std::remove_if( + notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); + + if (it != notes_.end()) { + notes_.erase(it, notes_.end()); + std::move(callback).Run(true); + + if (page_) { + page_->OnNotesUpdated(notes_); + } + } else { + std::move(callback).Run(false); + } +} + +void BraveCustomNotesPageHandler::GetAllNotes(GetAllNotesCallback callback) { + std::vector notes_copy; + for (const auto& note : notes_) { + notes_copy.push_back(note.Clone()); + } + std::move(callback).Run(std::move(notes_copy)); +} diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h new file mode 100644 index 000000000000..69761c01416b --- /dev/null +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h @@ -0,0 +1,55 @@ +#ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_PAGE_HANDLER_H_ +#define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_PAGE_HANDLER_H_ + +#include +#include +#include + +#include "base/scoped_observation.h" +#include "brave/components/brave_custom_notes/common/brave_custom_notes.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" + +namespace content { +class WebContents; +} // namespace content + +class BraveCustomNotesPageHandler + : public brave_custom_notes::mojom::NotesPageHandler { + public: + BraveCustomNotesPageHandler( + content::WebContents* web_contents, + mojo::PendingReceiver + receiver); + BraveCustomNotesPageHandler(const BraveCustomNotesPageHandler&) = delete; + BraveCustomNotesPageHandler& operator=(const BraveCustomNotesPageHandler&) = + delete; + ~BraveCustomNotesPageHandler() override; + + // brave_custom_notes::mojom::PageHandler overrides: + void SetClientPage( + mojo::PendingRemote page) + override; + void CreateNote(const std::string& title, + const std::string& content, + CreateNoteCallback callback) override; + void EditNote(int32_t note_id, + const std::string& new_title, + const std::string& new_content, + EditNoteCallback callback) override; + void DeleteNote(int32_t note_id, DeleteNoteCallback callback) override; + void GetAllNotes(GetAllNotesCallback callback) override; + + private: + // Handle back to the page by which we can pass results. + mojo::Remote page_; + + // The Profile* handed to us in our constructor. + raw_ptr web_contents_ = nullptr; + mojo::Receiver receiver_; + std::vector notes_; +}; + +#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_PAGE_HANDLER_H_ diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc index c8cdbec73eaf..fd95263f3caf 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc @@ -1,23 +1,38 @@ #include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h" +#include + +#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h" #include "brave/browser/ui/webui/brave_webui_source.h" +#include "brave/components/brave_custom_notes/common/constants.h" #include "brave/components/brave_custom_notes/resources/page/grit/brave_custom_notes_generated_map.h" -#include "chrome/browser/profiles/profile.h" -#include "components/grit/brave_components_resources.h" // For resources like HTML -#include "components/strings/grit/components_strings.h" // For string resources -#include "content/public/browser/web_ui.h" +#include "brave/components/l10n/common/localization_util.h" +#include "components/grit/brave_components_resources.h" +#include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui_data_source.h" BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui, const std::string& name) - : WebUIController(web_ui) { - // Create and add a WebUIDataSource for our hello world page + : ui::MojoWebUIController(web_ui, false) { content::WebUIDataSource* source = CreateAndAddWebUIDataSource( web_ui, name, kBraveCustomNotesGenerated, kBraveCustomNotesGeneratedSize, IDR_BRAVE_CUSTOM_NOTES_HTML); - // Adding a string to the source that can be used in the HTML - source->AddString("message", "Hello World"); + for (const auto& str : brave_custom_notes::kLocalizedStrings) { + std::u16string l10n_str = + brave_l10n::GetLocalizedResourceUTF16String(str.id); + source->AddString(str.name, l10n_str); + } } BraveCustomNotesUI::~BraveCustomNotesUI() = default; + +void BraveCustomNotesUI::BindInterface( + mojo::PendingReceiver + receiver) { + custom_notes_handler_ = std::make_unique( + web_ui()->GetWebContents(), std::move(receiver)); +} + +// Move WEB_UI_CONTROLLER_TYPE_IMPL outside any function or block +WEB_UI_CONTROLLER_TYPE_IMPL(BraveCustomNotesUI) diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h index 469d2febfbbd..2f2082beea9f 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h @@ -1,17 +1,34 @@ -#ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_UI_H_ -#define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_UI_H_ +// Copyright (c) 2022 The Brave Authors. All rights reserved. +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// you can obtain one at http://mozilla.org/MPL/2.0/. +#ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ +#define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ + +#include +#include + +#include "brave/components/brave_custom_notes/common/brave_custom_notes.mojom-forward.h" #include "content/public/browser/web_ui_controller.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "ui/webui/mojo_web_ui_controller.h" -class BraveCustomNotesUI : public content::WebUIController { +class BraveCustomNotesUI : public ui::MojoWebUIController { public: - explicit BraveCustomNotesUI(content::WebUI* web_ui, const std::string& name); + BraveCustomNotesUI(content::WebUI* web_ui, const std::string& name); ~BraveCustomNotesUI() override; - - private: - // Prevent copy and assign BraveCustomNotesUI(const BraveCustomNotesUI&) = delete; BraveCustomNotesUI& operator=(const BraveCustomNotesUI&) = delete; + + void BindInterface( + mojo::PendingReceiver + receiver); + + private: + std::unique_ptr + custom_notes_handler_; + WEB_UI_CONTROLLER_TYPE_DECL(); }; -#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_UI_H_ +#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ diff --git a/browser/ui/webui/private_new_tab_page/brave_private_new_tab_page_handler.cc b/browser/ui/webui/private_new_tab_page/brave_private_new_tab_page_handler.cc index 17bb3b7b2520..333b59c2eac5 100644 --- a/browser/ui/webui/private_new_tab_page/brave_private_new_tab_page_handler.cc +++ b/browser/ui/webui/private_new_tab_page/brave_private_new_tab_page_handler.cc @@ -39,15 +39,17 @@ BravePrivateNewTabPageHandler::BravePrivateNewTabPageHandler( receiver_(this, std::move(receiver)) { #if BUILDFLAG(ENABLE_TOR) tor_launcher_factory_ = TorLauncherFactory::GetInstance(); - if (tor_launcher_factory_) + if (tor_launcher_factory_) { tor_launcher_factory_->AddObserver(this); + } #endif } BravePrivateNewTabPageHandler::~BravePrivateNewTabPageHandler() { #if BUILDFLAG(ENABLE_TOR) - if (tor_launcher_factory_) + if (tor_launcher_factory_) { tor_launcher_factory_->RemoveObserver(this); + } #endif } @@ -83,11 +85,13 @@ void BravePrivateNewTabPageHandler::GetIsTorConnected( GetIsTorConnectedCallback callback) { bool is_connected = false; #if BUILDFLAG(ENABLE_TOR) - if (tor_launcher_factory_) + if (tor_launcher_factory_) { is_connected = tor_launcher_factory_->IsTorConnected(); + } #endif - else + else { is_connected = false; + } std::move(callback).Run(is_connected); } @@ -134,8 +138,9 @@ void BravePrivateNewTabPageHandler::GoToBraveSupport() { web_contents = browser->tab_strip_model()->GetActiveWebContents(); } - if (!web_contents) + if (!web_contents) { web_contents = web_contents_; + } web_contents->OpenURL( content::OpenURLParams(GURL("https://ping-browser.com/faqs-and-help"), @@ -170,8 +175,9 @@ void BravePrivateNewTabPageHandler::OnTorInitializing( } void BravePrivateNewTabPageHandler::OnTorCircuitTimer(ConnectionStatus status) { - if (!page_) + if (!page_) { return; + } if (status == ConnectionStatus::kConnectionSlow) { // First time shot of stuck_timer_ means that 'connection is slow' we diff --git a/components/brave_custom_notes/common/BUILD.gn b/components/brave_custom_notes/common/BUILD.gn new file mode 100644 index 000000000000..2cfa57c045c3 --- /dev/null +++ b/components/brave_custom_notes/common/BUILD.gn @@ -0,0 +1,18 @@ +import("//mojo/public/tools/bindings/mojom.gni") + +static_library("common") { + sources = [ + "constants.h", + ] + + deps = [ + "//base", + "//brave/components/resources:strings", + "//ui/base", + ] +} + +mojom("mojom") { + sources = [ "brave_custom_notes.mojom" ] + public_deps = [ "//mojo/public/mojom/base" ] +} diff --git a/components/brave_custom_notes/common/brave_custom_notes.mojom b/components/brave_custom_notes/common/brave_custom_notes.mojom new file mode 100644 index 000000000000..aa200c9a8546 --- /dev/null +++ b/components/brave_custom_notes/common/brave_custom_notes.mojom @@ -0,0 +1,50 @@ +// Copyright (c) 2022 The Brave Authors. All rights reserved. +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// you can obtain one at http://mozilla.org/MPL/2.0/. + +module brave_custom_notes.mojom; + +// Browser-side handler for requests from the WebUI page related to custom notes. +interface NotesPageHandler { + // Registers the webui page for managing notes. + SetClientPage(pending_remote page); + + // Creates a new custom note with the provided content. + CreateNote(string title, string content) => (int32 note_id); + + // Edits an existing note by note ID, updating its title and content. + EditNote(int32 note_id, string new_title, string new_content) => (bool success); + + // Deletes a note based on the note ID. + DeleteNote(int32 note_id) => (bool success); + + // Retrieves the content of a note by note ID. + GetNoteContent(int32 note_id) => (string title, string content); + + // Retrieves all notes with their titles and IDs. + GetAllNotes() => (array notes); +}; + +// Struct that defines the properties of a note. +struct Note { + int32 id; // Unique identifier for the note. + string title; // Title of the note. + string content; // Content/body of the note. + string timestamp; // Timestamp when the note was created or last edited. +}; + +// WebUI page that receives updates about the note-taking process. +interface CustomNotesPage { + // Triggered when a note is successfully created. + OnNoteCreated(int32 note_id, string title); + + // Triggered when a note is successfully edited. + OnNoteEdited(int32 note_id, string new_title); + + // Triggered when a note is successfully deleted. + OnNoteDeleted(int32 note_id); + + // Triggered when the list of notes is updated (e.g., on page load or after changes). + OnNotesUpdated(array notes); +}; diff --git a/components/brave_custom_notes/common/constants.h b/components/brave_custom_notes/common/constants.h new file mode 100644 index 000000000000..fcbdc9c0f21d --- /dev/null +++ b/components/brave_custom_notes/common/constants.h @@ -0,0 +1,31 @@ +/* Copyright (c) 2022 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_CUSTOM_NOTES_H_ +#define BRAVE_COMPONENTS_BRAVE_CUSTOM_NOTES_H_ + +#include "components/grit/brave_components_strings.h" +#include "ui/base/webui/web_ui_util.h" + +namespace brave_custom_notes { + +inline constexpr webui::LocalizedString kLocalizedStrings[] = { + {"notesHeaderTitle", IDS_BRAVE_CUSTOM_NOTES_HEADER_TITLE}, + {"notesHeaderDesc", IDS_BRAVE_CUSTOM_NOTES_HEADER_DESCRIPTION}, + {"createNoteButton", IDS_BRAVE_CUSTOM_NOTES_CREATE_NOTE_BUTTON}, + {"editNoteButton", IDS_BRAVE_CUSTOM_NOTES_EDIT_NOTE_BUTTON}, + {"deleteNoteButton", IDS_BRAVE_CUSTOM_NOTES_DELETE_NOTE_BUTTON}, + {"notePlaceholderTitle", IDS_BRAVE_CUSTOM_NOTES_PLACEHOLDER_TITLE}, + {"notePlaceholderContent", IDS_BRAVE_CUSTOM_NOTES_PLACEHOLDER_CONTENT}, + {"noteSavedMessage", IDS_BRAVE_CUSTOM_NOTES_NOTE_SAVED_MESSAGE}, + {"noteDeletedMessage", IDS_BRAVE_CUSTOM_NOTES_NOTE_DELETED_MESSAGE}, + {"notesListTitle", IDS_BRAVE_CUSTOM_NOTES_LIST_TITLE}, + {"noNotesMessage", IDS_BRAVE_CUSTOM_NOTES_NO_NOTES_MESSAGE}, + {"notesSearchPlaceholder", IDS_BRAVE_CUSTOM_NOTES_SEARCH_PLACEHOLDER}, +}; + +} // namespace brave_custom_notes + +#endif // BRAVE_COMPONENTS_BRAVE_CUSTOM_NOTES_H_ diff --git a/components/brave_custom_notes/resources/page/BUILD.gn b/components/brave_custom_notes/resources/page/BUILD.gn index a7dda645d0e5..58b9e176ac64 100644 --- a/components/brave_custom_notes/resources/page/BUILD.gn +++ b/components/brave_custom_notes/resources/page/BUILD.gn @@ -6,7 +6,7 @@ transpile_web_ui("brave_custom_notes") { rebase_path("./custom_notes.tsx"), ]] resource_name = "brave_custom_notes" - + deps = [ "//brave/components/brave_custom_notes/common:mojom_js" ] } pack_web_resources("generated_resources") { diff --git a/components/brave_custom_notes/resources/page/api/brave_custom_notes_handler.ts b/components/brave_custom_notes/resources/page/api/brave_custom_notes_handler.ts new file mode 100644 index 000000000000..6f4e6b9b4766 --- /dev/null +++ b/components/brave_custom_notes/resources/page/api/brave_custom_notes_handler.ts @@ -0,0 +1,38 @@ +/* Copyright (c) 2022 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at https://mozilla.org/MPL/2.0/. */ +// @ts-nocheck + import * as BraveCustomNotes from 'gen/brave/components/brave_custom_notes/common/brave_custom_notes.mojom.m.js' + + // Provide access to all the generated types + export * from 'gen/brave/components/brave_custom_notes/common/brave_custom_notes.mojom.m.js' + + interface API { + pageHandler: BraveCustomNotes.PageHandlerRemote + callbackRouter: BraveCustomNotes.CustomNotesPageCallbackRouter + } + + let apiInstance: API + + class CustomNotesAPI implements API { + pageHandler: BraveCustomNotes.PageHandlerRemote + callbackRouter: BraveCustomNotes.CustomNotesPageCallbackRouter + + constructor () { + // Initialize page handler to communicate with backend + this.pageHandler = BraveCustomNotes.PageHandler.getRemote() + // Initialize callback router to handle responses from backend + this.callbackRouter = new BraveCustomNotes.CustomNotesPageCallbackRouter() + // Set the callback router in the page handler to link it with the frontend + this.pageHandler.setClientPage(this.callbackRouter.$.bindNewPipeAndPassRemote()) + } + } + + export default function getCustomNotesHandlerInstance () { + if (!apiInstance) { + apiInstance = new CustomNotesAPI() + } + return apiInstance + } + \ No newline at end of file diff --git a/components/brave_custom_notes/resources/page/container.tsx b/components/brave_custom_notes/resources/page/container.tsx index 72c85580b312..8597a6cc893c 100644 --- a/components/brave_custom_notes/resources/page/container.tsx +++ b/components/brave_custom_notes/resources/page/container.tsx @@ -1,80 +1,95 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at https://mozilla.org/MPL/2.0/. */ + import * as React from 'react'; -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import styled from 'styled-components'; +import getCustomNotesHandlerInstance from './api/brave_custom_notes_handler'; const NotesContainer = styled.div` - display: flex; - flex-direction: column; - align-items: center; - padding: 20px; - max-width: 600px; - margin: 0 auto; - background-color: #f0f4f8; - border-radius: 8px; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); - `; + display: flex; + flex-direction: column; + align-items: center; + padding: 20px; + max-width: 600px; + margin: 0 auto; + background-color: #f0f4f8; + border-radius: 8px; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); + `; const Title = styled.h1` - font-size: 24px; - color: #333; - margin-bottom: 20px; - `; + font-size: 24px; + color: #333; + margin-bottom: 20px; + `; const NoteInput = styled.textarea` - width: 100%; - padding: 10px; - font-size: 16px; - border: 2px solid #ccc; - border-radius: 5px; - margin-bottom: 15px; - resize: none; - min-height: 80px; - `; + width: 100%; + padding: 10px; + font-size: 16px; + border: 2px solid #ccc; + border-radius: 5px; + margin-bottom: 15px; + resize: none; + min-height: 80px; + `; const AddButton = styled.button` - background-color: #007bff; - color: white; - border: none; - padding: 10px 20px; - font-size: 16px; - border-radius: 5px; - cursor: pointer; - &:hover { - background-color: #0056b3; - } - `; + background-color: #007bff; + color: white; + border: none; + padding: 10px 20px; + font-size: 16px; + border-radius: 5px; + cursor: pointer; + &:hover { + background-color: #0056b3; + } + `; const NotesList = styled.ul` - list-style-type: none; - padding: 0; - margin: 20px 0; - width: 100%; - `; + list-style-type: none; + padding: 0; + margin: 20px 0; + width: 100%; + `; const NoteItem = styled.li` - background-color: #fff; - padding: 10px; - border-radius: 5px; - margin-bottom: 10px; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); - `; + background-color: #fff; + padding: 10px; + border-radius: 5px; + margin-bottom: 10px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + `; const NoNotesMessage = styled.p` - font-size: 16px; - color: #999; - `; + font-size: 16px; + color: #999; + `; const Notes: React.FC = () => { const [note, setNote] = useState(''); const [notesList, setNotesList] = useState([]); + // Fetch mojom instance + const customNotesAPI = getCustomNotesHandlerInstance(); + + // Load existing notes on component mount (from backend) + useEffect(() => { + customNotesAPI.pageHandler.getNotes().then((response: { notes: any; }) => { + setNotesList(response.notes || []); + }); + }, []); + const handleAddNote = () => { if (note.trim()) { - setNotesList([...notesList, note]); - setNote(''); + // Add note to the backend via mojom handler + customNotesAPI.pageHandler.addNote(note).then(() => { + setNotesList([...notesList, note]); + setNote(''); + }); } }; diff --git a/components/brave_custom_notes/resources/page/custom_notes.html b/components/brave_custom_notes/resources/page/custom_notes.html index 94bbe8f69a07..1e194a395dd5 100644 --- a/components/brave_custom_notes/resources/page/custom_notes.html +++ b/components/brave_custom_notes/resources/page/custom_notes.html @@ -1,19 +1,28 @@ - - -Brave Custom Notes - - - - - - - + + + Brave Custom Notes + + + + + + + + + - -
+ +
diff --git a/components/resources/brave_components_strings.grd b/components/resources/brave_components_strings.grd index 60769fd89dcb..8aefbd8c174a 100644 --- a/components/resources/brave_components_strings.grd +++ b/components/resources/brave_components_strings.grd @@ -411,6 +411,23 @@ Search the web privately + + + Custom Notes + Manage your notes easily. + Add a new note + Edit note + Delete note + Title of your note + Content of your note + Note saved successfully! + Note deleted successfully! + Your Notes + No notes available. Start by adding a new note! + Search notes... + + + Additional Filters Warning: Turning on too many filters will degrade performance diff --git a/components/webui/webui_resources.cc b/components/webui/webui_resources.cc index d13801ac5256..f008e22ea604 100644 --- a/components/webui/webui_resources.cc +++ b/components/webui/webui_resources.cc @@ -347,6 +347,31 @@ base::span GetWebUILocalizedStrings( // Private Tab - Private Window - Tor Box {"boxTorText2", IDS_BRAVE_PRIVATE_NEW_TAB_BOX_TOR_TEXT_2}, {"boxTorButton", IDS_BRAVE_PRIVATE_NEW_TAB_BOX_TOR_BUTTON}, + + // Custom Notes - Header + {"headerTitle", IDS_BRAVE_CUSTOM_NOTES_HEADER_TITLE}, + {"headerText", IDS_BRAVE_CUSTOM_NOTES_HEADER_DESCRIPTION}, + + // Custom Notes - Actions + {"createNoteButton", IDS_BRAVE_CUSTOM_NOTES_CREATE_NOTE_BUTTON}, + {"editNoteButton", IDS_BRAVE_CUSTOM_NOTES_EDIT_NOTE_BUTTON}, + {"deleteNoteButton", IDS_BRAVE_CUSTOM_NOTES_DELETE_NOTE_BUTTON}, + + // Custom Notes - Placeholders + {"notePlaceholderTitle", + IDS_BRAVE_CUSTOM_NOTES_PLACEHOLDER_TITLE}, + {"notePlaceholderContent", + IDS_BRAVE_CUSTOM_NOTES_PLACEHOLDER_CONTENT}, + + // Custom Notes - Messages + {"noteSavedMessage", IDS_BRAVE_CUSTOM_NOTES_NOTE_SAVED_MESSAGE}, + {"noteDeletedMessage", + IDS_BRAVE_CUSTOM_NOTES_NOTE_DELETED_MESSAGE}, + {"notesListTitle", IDS_BRAVE_CUSTOM_NOTES_LIST_TITLE}, + {"noNotesMessage", IDS_BRAVE_CUSTOM_NOTES_NO_NOTES_MESSAGE}, + {"notesSearchPlaceholder", + IDS_BRAVE_CUSTOM_NOTES_SEARCH_PLACEHOLDER}, + #endif // !BUILDFLAG(IS_ANDROID) // Brave Talk shortcut From 90c1c4a303d3bc50a2ba076989530afcc93bdcaa Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Thu, 10 Oct 2024 23:11:52 +0530 Subject: [PATCH 11/21] mojo message pipe is now working fine, there are still few errors in several functionalities, not all the functionalities are well tested --- .../brave_custom_notes_handler.cc | 120 +++++++++++++++++- .../brave_custom_notes_handler.h | 38 ++++-- .../brave_custom_notes_ui.cc | 12 +- .../brave_custom_notes_ui.h | 5 - .../common/brave_custom_notes.mojom | 29 +---- .../page/api/brave_custom_notes_handler.ts | 2 +- .../resources/page/container.tsx | 2 +- 7 files changed, 159 insertions(+), 49 deletions(-) diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc index dddc3ea7a487..13ebfd405114 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc @@ -1,20 +1,39 @@ -// Copyright (c) 2024 The Brave Authors. All rights reserved. +// Copyright(c) 2022 The Brave Authors.All rights reserved. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. #include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h" +#include +#include #include +#include #include "base/functional/bind.h" #include "base/strings/utf_string_conversions.h" -#include "brave_custom_notes_handler.h" +#include "brave/components/search_engines/brave_prepopulated_engines.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_finder.h" +#include "components/prefs/pref_service.h" +#include "components/prefs/scoped_user_pref_update.h" +#include "content/public/browser/page_navigator.h" +#include "content/public/browser/web_contents.h" + +namespace { +const char kCustomNotesKey[] = "custom_notes"; +} // namespace BraveCustomNotesPageHandler::BraveCustomNotesPageHandler( + Profile* profile, content::WebContents* web_contents, mojo::PendingReceiver receiver) - : web_contents_(web_contents), receiver_(this, std::move(receiver)) {} + : profile_(profile), + web_contents_(web_contents), + receiver_(this, std::move(receiver)) { + LoadNotesFromPrefs(); +} BraveCustomNotesPageHandler::~BraveCustomNotesPageHandler() = default; @@ -27,16 +46,34 @@ void BraveCustomNotesPageHandler::CreateNote(const std::string& title, const std::string& content, CreateNoteCallback callback) { auto new_note = brave_custom_notes::mojom::Note::New(); - new_note->id = notes_.size() + 1; // Simple ID generation + new_note->id = notes_.empty() ? 1 : notes_.back()->id + 1; new_note->title = title; new_note->content = content; notes_.push_back(std::move(new_note)); + SaveNotesToPrefs(); + + std::move(callback).Run(true); + + if (page_) { + UpdatePageWithNotes(); + } +} + +void BraveCustomNotesPageHandler::AddNote(const std::string& content, + AddNoteCallback callback) { + auto new_note = brave_custom_notes::mojom::Note::New(); + new_note->id = notes_.empty() ? 1 : notes_.back()->id + 1; + new_note->title = "New Note"; + new_note->content = content; + + notes_.push_back(std::move(new_note)); + SaveNotesToPrefs(); std::move(callback).Run(true); if (page_) { - page_->OnNotesUpdated(notes_); + UpdatePageWithNotes(); } } @@ -51,10 +88,11 @@ void BraveCustomNotesPageHandler::EditNote(int32_t note_id, if (it != notes_.end()) { (*it)->title = new_title; (*it)->content = new_content; + SaveNotesToPrefs(); std::move(callback).Run(true); if (page_) { - page_->OnNotesUpdated(notes_); + UpdatePageWithNotes(); } } else { std::move(callback).Run(false); @@ -69,20 +107,88 @@ void BraveCustomNotesPageHandler::DeleteNote(int32_t note_id, if (it != notes_.end()) { notes_.erase(it, notes_.end()); + SaveNotesToPrefs(); std::move(callback).Run(true); if (page_) { - page_->OnNotesUpdated(notes_); + UpdatePageWithNotes(); } } else { std::move(callback).Run(false); } } +void BraveCustomNotesPageHandler::GetNoteContent( + int32_t note_id, + GetNoteContentCallback callback) { + auto it = + std::find_if(notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); + + if (it != notes_.end()) { + std::move(callback).Run(true, (*it)->content); + } else { + std::move(callback).Run(false, std::string()); + } +} + void BraveCustomNotesPageHandler::GetAllNotes(GetAllNotesCallback callback) { std::vector notes_copy; + notes_copy.reserve(notes_.size()); for (const auto& note : notes_) { notes_copy.push_back(note.Clone()); } std::move(callback).Run(std::move(notes_copy)); } + +void BraveCustomNotesPageHandler::LoadNotesFromPrefs() { + notes_.clear(); + const base::Value::List& stored_notes = + profile_->GetPrefs()->GetList(kCustomNotesKey); + + for (const auto& note_value : stored_notes) { + if (!note_value.is_dict()) { + continue; + } + + const auto& dict = note_value.GetDict(); + auto note = brave_custom_notes::mojom::Note::New(); + + note->id = dict.FindInt("id").value_or(0); + const std::string* title = dict.FindString("title"); + note->title = title ? *title : ""; + const std::string* content = dict.FindString("content"); + note->content = content ? *content : ""; + + if (note->id > 0) { // Only add valid notes + notes_.push_back(std::move(note)); + } + } +} + +void BraveCustomNotesPageHandler::SaveNotesToPrefs() { + ScopedListPrefUpdate update(profile_->GetPrefs(), kCustomNotesKey); + base::Value::List& prefs_notes = update.Get(); + prefs_notes.clear(); + + for (const auto& note : notes_) { + base::Value::Dict note_dict; + note_dict.Set("id", note->id); + note_dict.Set("title", note->title); + note_dict.Set("content", note->content); + prefs_notes.Append(std::move(note_dict)); + } +} + +void BraveCustomNotesPageHandler::UpdatePageWithNotes() { + if (!page_) { + return; + } + + std::vector notes_copy; + notes_copy.reserve(notes_.size()); + for (const auto& note : notes_) { + notes_copy.push_back(note.Clone()); + } + page_->OnNotesUpdated(std::move(notes_copy)); +} diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h index 69761c01416b..55a883bb9271 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h @@ -1,34 +1,42 @@ -#ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_PAGE_HANDLER_H_ -#define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_PAGE_HANDLER_H_ +// Copyright (c) 2022 The Brave Authors. All rights reserved. +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// you can obtain one at http://mozilla.org/MPL/2.0/. +#ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_HANDLER_H_ +#define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_HANDLER_H_ #include #include #include -#include "base/scoped_observation.h" +#include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" #include "brave/components/brave_custom_notes/common/brave_custom_notes.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" +class Profile; namespace content { class WebContents; -} // namespace content +} class BraveCustomNotesPageHandler : public brave_custom_notes::mojom::NotesPageHandler { public: BraveCustomNotesPageHandler( + Profile* profile, content::WebContents* web_contents, mojo::PendingReceiver receiver); + ~BraveCustomNotesPageHandler() override; + BraveCustomNotesPageHandler(const BraveCustomNotesPageHandler&) = delete; BraveCustomNotesPageHandler& operator=(const BraveCustomNotesPageHandler&) = delete; - ~BraveCustomNotesPageHandler() override; - // brave_custom_notes::mojom::PageHandler overrides: + // brave_custom_notes::mojom::NotesPageHandler: void SetClientPage( mojo::PendingRemote page) override; @@ -40,16 +48,24 @@ class BraveCustomNotesPageHandler const std::string& new_content, EditNoteCallback callback) override; void DeleteNote(int32_t note_id, DeleteNoteCallback callback) override; + void GetNoteContent(int32_t note_id, + GetNoteContentCallback callback) override; void GetAllNotes(GetAllNotesCallback callback) override; + void AddNote(const std::string& content, AddNoteCallback callback) override; private: - // Handle back to the page by which we can pass results. - mojo::Remote page_; + void LoadNotesFromPrefs(); + void SaveNotesToPrefs(); + void UpdatePageWithNotes(); - // The Profile* handed to us in our constructor. - raw_ptr web_contents_ = nullptr; + raw_ptr profile_; + raw_ptr web_contents_; mojo::Receiver receiver_; + mojo::Remote page_; + std::vector notes_; + + base::WeakPtrFactory weak_ptr_factory_{this}; }; -#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_PAGE_HANDLER_H_ +#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_HANDLER_H_ diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc index fd95263f3caf..ef9722155bb9 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc @@ -1,3 +1,8 @@ +// Copyright (c) 2022 The Brave Authors. All rights reserved. +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// you can obtain one at http://mozilla.org/MPL/2.0/. + #include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h" #include @@ -7,6 +12,7 @@ #include "brave/components/brave_custom_notes/common/constants.h" #include "brave/components/brave_custom_notes/resources/page/grit/brave_custom_notes_generated_map.h" #include "brave/components/l10n/common/localization_util.h" +#include "chrome/browser/profiles/profile.h" #include "components/grit/brave_components_resources.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui_data_source.h" @@ -14,6 +20,7 @@ BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui, const std::string& name) : ui::MojoWebUIController(web_ui, false) { + Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource* source = CreateAndAddWebUIDataSource( web_ui, name, kBraveCustomNotesGenerated, kBraveCustomNotesGeneratedSize, IDR_BRAVE_CUSTOM_NOTES_HTML); @@ -23,6 +30,8 @@ BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui, brave_l10n::GetLocalizedResourceUTF16String(str.id); source->AddString(str.name, l10n_str); } + source->AddBoolean("isWindowTor", profile->IsTor()); + AddBackgroundColorToSource(source, web_ui->GetWebContents()); } BraveCustomNotesUI::~BraveCustomNotesUI() = default; @@ -31,7 +40,8 @@ void BraveCustomNotesUI::BindInterface( mojo::PendingReceiver receiver) { custom_notes_handler_ = std::make_unique( - web_ui()->GetWebContents(), std::move(receiver)); + Profile::FromWebUI(web_ui()), web_ui()->GetWebContents(), + std::move(receiver)); } // Move WEB_UI_CONTROLLER_TYPE_IMPL outside any function or block diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h index 2f2082beea9f..42c4ec6a3543 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h @@ -2,10 +2,8 @@ // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. - #ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ #define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ - #include #include @@ -13,14 +11,12 @@ #include "content/public/browser/web_ui_controller.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/webui/mojo_web_ui_controller.h" - class BraveCustomNotesUI : public ui::MojoWebUIController { public: BraveCustomNotesUI(content::WebUI* web_ui, const std::string& name); ~BraveCustomNotesUI() override; BraveCustomNotesUI(const BraveCustomNotesUI&) = delete; BraveCustomNotesUI& operator=(const BraveCustomNotesUI&) = delete; - void BindInterface( mojo::PendingReceiver receiver); @@ -30,5 +26,4 @@ class BraveCustomNotesUI : public ui::MojoWebUIController { custom_notes_handler_; WEB_UI_CONTROLLER_TYPE_DECL(); }; - #endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ diff --git a/components/brave_custom_notes/common/brave_custom_notes.mojom b/components/brave_custom_notes/common/brave_custom_notes.mojom index aa200c9a8546..01f9eca950cd 100644 --- a/components/brave_custom_notes/common/brave_custom_notes.mojom +++ b/components/brave_custom_notes/common/brave_custom_notes.mojom @@ -7,44 +7,27 @@ module brave_custom_notes.mojom; // Browser-side handler for requests from the WebUI page related to custom notes. interface NotesPageHandler { - // Registers the webui page for managing notes. SetClientPage(pending_remote page); - - // Creates a new custom note with the provided content. CreateNote(string title, string content) => (int32 note_id); - - // Edits an existing note by note ID, updating its title and content. EditNote(int32 note_id, string new_title, string new_content) => (bool success); - - // Deletes a note based on the note ID. DeleteNote(int32 note_id) => (bool success); - - // Retrieves the content of a note by note ID. - GetNoteContent(int32 note_id) => (string title, string content); - - // Retrieves all notes with their titles and IDs. + GetNoteContent(int32 note_id) => (bool success, string content); GetAllNotes() => (array notes); + AddNote(string content) => (bool success); }; // Struct that defines the properties of a note. struct Note { - int32 id; // Unique identifier for the note. - string title; // Title of the note. - string content; // Content/body of the note. - string timestamp; // Timestamp when the note was created or last edited. + int32 id; + string title; + string content; + string timestamp; }; // WebUI page that receives updates about the note-taking process. interface CustomNotesPage { - // Triggered when a note is successfully created. OnNoteCreated(int32 note_id, string title); - - // Triggered when a note is successfully edited. OnNoteEdited(int32 note_id, string new_title); - - // Triggered when a note is successfully deleted. OnNoteDeleted(int32 note_id); - - // Triggered when the list of notes is updated (e.g., on page load or after changes). OnNotesUpdated(array notes); }; diff --git a/components/brave_custom_notes/resources/page/api/brave_custom_notes_handler.ts b/components/brave_custom_notes/resources/page/api/brave_custom_notes_handler.ts index 6f4e6b9b4766..e4cbe3a4a4a8 100644 --- a/components/brave_custom_notes/resources/page/api/brave_custom_notes_handler.ts +++ b/components/brave_custom_notes/resources/page/api/brave_custom_notes_handler.ts @@ -21,7 +21,7 @@ constructor () { // Initialize page handler to communicate with backend - this.pageHandler = BraveCustomNotes.PageHandler.getRemote() + this.pageHandler = BraveCustomNotes.NotesPageHandler.getRemote() // Initialize callback router to handle responses from backend this.callbackRouter = new BraveCustomNotes.CustomNotesPageCallbackRouter() // Set the callback router in the page handler to link it with the frontend diff --git a/components/brave_custom_notes/resources/page/container.tsx b/components/brave_custom_notes/resources/page/container.tsx index 8597a6cc893c..7cbc40b3b4ca 100644 --- a/components/brave_custom_notes/resources/page/container.tsx +++ b/components/brave_custom_notes/resources/page/container.tsx @@ -78,7 +78,7 @@ const Notes: React.FC = () => { // Load existing notes on component mount (from backend) useEffect(() => { - customNotesAPI.pageHandler.getNotes().then((response: { notes: any; }) => { + customNotesAPI.pageHandler.getAllNotes().then((response: { notes: any; }) => { setNotesList(response.notes || []); }); }, []); From 1ac8fad4ee7881fff62a4cdf6b088f1847b92562 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Fri, 11 Oct 2024 19:13:39 +0530 Subject: [PATCH 12/21] custom_notes all features impl successfully, a date fetch bug just remains --- .../resources/page/container.tsx | 175 ++++++++++++------ 1 file changed, 115 insertions(+), 60 deletions(-) diff --git a/components/brave_custom_notes/resources/page/container.tsx b/components/brave_custom_notes/resources/page/container.tsx index 7cbc40b3b4ca..083099c7f773 100644 --- a/components/brave_custom_notes/resources/page/container.tsx +++ b/components/brave_custom_notes/resources/page/container.tsx @@ -8,107 +8,162 @@ import styled from 'styled-components'; import getCustomNotesHandlerInstance from './api/brave_custom_notes_handler'; const NotesContainer = styled.div` - display: flex; - flex-direction: column; - align-items: center; - padding: 20px; - max-width: 600px; - margin: 0 auto; - background-color: #f0f4f8; - border-radius: 8px; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); - `; + display: flex; + flex-direction: column; + align-items: center; + padding: 20px; + max-width: 600px; + margin: 0 auto; + background-color: #f0f4f8; + border-radius: 8px; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); + `; const Title = styled.h1` - font-size: 24px; - color: #333; - margin-bottom: 20px; - `; + font-size: 24px; + color: #333; + margin-bottom: 20px; + `; const NoteInput = styled.textarea` - width: 100%; - padding: 10px; - font-size: 16px; - border: 2px solid #ccc; - border-radius: 5px; - margin-bottom: 15px; - resize: none; - min-height: 80px; - `; - -const AddButton = styled.button` - background-color: #007bff; - color: white; - border: none; - padding: 10px 20px; - font-size: 16px; - border-radius: 5px; - cursor: pointer; - &:hover { - background-color: #0056b3; - } - `; + width: 100%; + padding: 10px; + font-size: 16px; + border: 2px solid #ccc; + border-radius: 5px; + margin-bottom: 15px; + resize: none; + min-height: 80px; + `; + +const Button = styled.button` + background-color: #007bff; + color: white; + border: none; + padding: 10px 20px; + font-size: 16px; + border-radius: 5px; + cursor: pointer; + margin-right: 10px; + &:hover { + background-color: #0056b3; + } + `; + +const DeleteButton = styled(Button)` + background-color: #dc3545; + &:hover { + background-color: #c82333; + } + `; const NotesList = styled.ul` - list-style-type: none; - padding: 0; - margin: 20px 0; - width: 100%; - `; + list-style-type: none; + padding: 0; + margin: 20px 0; + width: 100%; + `; const NoteItem = styled.li` - background-color: #fff; - padding: 10px; - border-radius: 5px; - margin-bottom: 10px; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); - `; + background-color: #fff; + padding: 10px; + border-radius: 5px; + margin-bottom: 10px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + `; const NoNotesMessage = styled.p` - font-size: 16px; - color: #999; - `; + font-size: 16px; + color: #999; + `; + +interface Note { + id: number; + title: string; + content: string; + timestamp: number; +} const Notes: React.FC = () => { const [note, setNote] = useState(''); - const [notesList, setNotesList] = useState([]); + const [notesList, setNotesList] = useState([]); + const [editingNote, setEditingNote] = useState(null); // Fetch mojom instance const customNotesAPI = getCustomNotesHandlerInstance(); // Load existing notes on component mount (from backend) useEffect(() => { - customNotesAPI.pageHandler.getAllNotes().then((response: { notes: any; }) => { + loadNotes(); + }, []); + + const loadNotes = () => { + customNotesAPI.pageHandler.getAllNotes().then((response: { notes: Note[] }) => { setNotesList(response.notes || []); }); - }, []); + }; const handleAddNote = () => { if (note.trim()) { // Add note to the backend via mojom handler customNotesAPI.pageHandler.addNote(note).then(() => { - setNotesList([...notesList, note]); + loadNotes(); setNote(''); }); } }; + const handleEditNote = (noteToEdit: Note) => { + setEditingNote(noteToEdit); + setNote(noteToEdit.content); + }; + + const handleUpdateNote = () => { + if (editingNote && note.trim()) { + customNotesAPI.pageHandler.editNote(editingNote.id, editingNote.title, note).then(() => { + loadNotes(); + setNote(''); + setEditingNote(null); + }); + } + }; + + const handleDeleteNote = (noteId: number) => { + customNotesAPI.pageHandler.deleteNote(noteId).then(() => { + loadNotes(); + }); + }; + return ( My Notes setNote(e.target.value)} - placeholder="Write a new note..." + placeholder={editingNote ? "Edit note..." : "Write a new note..."} /> - Add Note - + {editingNote ? ( + + ) : ( + + )} + {editingNote && ( + + )} {notesList.length === 0 ? ( No notes added yet! ) : ( - {notesList.map((note, index) => ( - {note} + {notesList.map((note) => ( + +

{note.title}

+

{note.content}

+ {new Date(note.timestamp).toLocaleString()} +
+ + handleDeleteNote(note.id)}>Delete +
+
))}
)} @@ -116,4 +171,4 @@ const Notes: React.FC = () => { ); }; -export default Notes; +export default Notes; \ No newline at end of file From e92518e5d806c9e8a2bffab842942943098a45a6 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Fri, 18 Oct 2024 22:38:38 +0530 Subject: [PATCH 13/21] working but response not coming, debugging it --- browser/ui/BUILD.gn | 2 + .../brave_custom_notes_api_handler.cc | 178 ++++++++++++++++++ .../brave_custom_notes_api_handler.h | 42 +++++ .../brave_custom_notes_handler.cc | 55 +++++- .../brave_custom_notes_handler.h | 28 ++- .../brave_custom_notes_ui.cc | 16 +- .../brave_custom_notes_ui.h | 19 +- .../common/brave_custom_notes.mojom | 2 + .../resources/page/container.tsx | 146 ++++++++------ 9 files changed, 398 insertions(+), 90 deletions(-) create mode 100644 browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc create mode 100644 browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h diff --git a/browser/ui/BUILD.gn b/browser/ui/BUILD.gn index bb26ef3d6696..5e28aa963411 100644 --- a/browser/ui/BUILD.gn +++ b/browser/ui/BUILD.gn @@ -243,6 +243,8 @@ source_set("ui") { "webui/brave_custom_notes/brave_custom_notes_handler.h", "webui/brave_custom_notes/brave_custom_notes_ui.cc", "webui/brave_custom_notes/brave_custom_notes_ui.h", + "webui/brave_custom_notes/brave_custom_notes_api_handler.cc", + "webui/brave_custom_notes/brave_custom_notes_api_handler.h", "webui/settings/brave_adblock_handler.cc", "webui/settings/brave_adblock_handler.h", "webui/settings/brave_appearance_handler.cc", diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc new file mode 100644 index 000000000000..62e4cac03fde --- /dev/null +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc @@ -0,0 +1,178 @@ +/* Copyright (c) 2022 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * you can obtain one at https://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h" + +#include "services/network/public/cpp/resource_request.h" +#include "services/network/public/cpp/simple_url_loader.h" +#include "url/gurl.h" +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/values.h" +#include "net/traffic_annotation/network_traffic_annotation.h" + +// Traffic annotation for the network requests +constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetworkTrafficAnnotation( + "brave_custom_notes_api", + R"( + semantics { + sender: "Brave Custom Notes API" + description: "Handles summarizing and rephrasing notes." + trigger: "User interacts with note features to summarize or rephrase content." + data: "User-provided note content." + destination: OTHER + } + policy { + cookies_allowed: NO + setting: "No user settings needed." + policy_exception_justification: "Not required." + })"); + +// API Endpoints +const char kSummarizeAPIEndpoint[] = "https://openai-text-summarizer.azurewebsites.net/summarize"; +const char kRephraseAPIEndpoint[] = "https://openai-text-summarizer.azurewebsites.net/rephrase"; + +namespace { + +std::unique_ptr CreateLoader( + const GURL& api_url, + const std::string& content) { + VLOG(1) << "Creating loader for URL: " << api_url.spec(); + LOG(INFO) << "Request content length: " << content.length(); + + auto resource_request = std::make_unique(); + resource_request->url = api_url; + resource_request->method = "POST"; + resource_request->headers.SetHeader("Content-Type", "application/json"); + + auto loader = network::SimpleURLLoader::Create( + std::move(resource_request), + kTrafficAnnotation); + + base::Value::Dict request_dict; + request_dict.Set("content", content); + std::string request_body; + base::JSONWriter::Write(request_dict, &request_body); + + VLOG(2) << "Request body: " << request_body; + + loader->AttachStringForUpload(request_body, "application/json"); + + // Set retry options + loader->SetRetryOptions( + 3, // max retries + network::SimpleURLLoader::RetryMode::RETRY_ON_NETWORK_CHANGE); + + return loader; +} + +} // namespace + +BraveCustomNotesAPIHandler::BraveCustomNotesAPIHandler( + scoped_refptr url_loader_factory) + : url_loader_factory_(std::move(url_loader_factory)) { + LOG(INFO) << "BraveCustomNotesAPIHandler initialized"; + } + +BraveCustomNotesAPIHandler::~BraveCustomNotesAPIHandler(){ + LOG(INFO) << "BraveCustomNotesAPIHandler destroyed"; + if (!loaders_.empty()) { + LOG(WARNING) << "Destroying handler with " << loaders_.size() + << " pending requests"; + } +} + +void BraveCustomNotesAPIHandler::CallSummarizeAPI( + const std::string& content, std::string* summary) { + VLOG(1) << "Calling summarize API"; + GURL api_url(kSummarizeAPIEndpoint); + auto loader = CreateLoader(api_url, content); + + loader->DownloadToString( + url_loader_factory_.get(), + base::BindOnce(&BraveCustomNotesAPIHandler::OnSummarizeAPISuccess, + weak_ptr_factory_.GetWeakPtr(), loader.get(), summary), + 1024 * 1024 /* 1MB max size */); + + loaders_.push_back(std::move(loader)); + VLOG(1) << "Summarize request sent. Active loaders: " << loaders_.size(); +} + +void BraveCustomNotesAPIHandler::CallRephraseAPI( + const std::string& content, std::string* rephrased_content) { + VLOG(1) << "Calling rephrase API"; + GURL api_url(kRephraseAPIEndpoint); + auto loader = CreateLoader(api_url, content); + + loader->DownloadToString( + url_loader_factory_.get(), + base::BindOnce(&BraveCustomNotesAPIHandler::OnRephraseAPISuccess, + weak_ptr_factory_.GetWeakPtr(), loader.get(), rephrased_content), + 1024 * 1024 /* 1MB max size */); + + loaders_.push_back(std::move(loader)); + VLOG(1) << "Rephrase request sent. Active loaders: " << loaders_.size(); +} + +void BraveCustomNotesAPIHandler::OnSummarizeAPISuccess( + network::SimpleURLLoader* loader, + std::string* summary, + std::unique_ptr response_body) { + VLOG(1) << "Processing summarize API response"; + if (response_body) { + auto json_result = base::JSONReader::Read(*response_body); + if (json_result && json_result->is_dict()) { + const std::string* api_result = json_result->GetDict().FindString("summary"); + if (api_result) { + *summary = *api_result; + } else { + *summary = "Key 'summary' not found in the response."; + } + } else { + *summary = "Invalid JSON response."; + } + } else { + *summary = "Failed to get a response."; + } + + // Cleanup completed loader + auto it = std::find_if(loaders_.begin(), loaders_.end(), + [loader](const std::unique_ptr& l) { + return l.get() == loader; + }); + if (it != loaders_.end()) { + loaders_.erase(it); + } +} + +void BraveCustomNotesAPIHandler::OnRephraseAPISuccess( + network::SimpleURLLoader* loader, + std::string* rephrased_content, + std::unique_ptr response_body) { + if (response_body) { + auto json_result = base::JSONReader::Read(*response_body); + if (json_result && json_result->is_dict()) { + const std::string* api_result = json_result->GetDict().FindString("rephrased_content"); + if (api_result) { + *rephrased_content = *api_result; + } else { + *rephrased_content = "Key 'rephrased_content' not found in the response."; + } + } else { + *rephrased_content = "Invalid JSON response."; + } + } else { + *rephrased_content = "Failed to get a response."; + } + + // Cleanup completed loader + auto it = std::find_if(loaders_.begin(), loaders_.end(), + [loader](const std::unique_ptr& l) { + return l.get() == loader; + }); + if (it != loaders_.end()) { + loaders_.erase(it); + } +} \ No newline at end of file diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h new file mode 100644 index 000000000000..087f4081ba7d --- /dev/null +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h @@ -0,0 +1,42 @@ +/* Copyright (c) 2022 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at https://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_API_HANDLER_H_ +#define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_API_HANDLER_H_ + +#include +#include +#include + +#include "base/memory/weak_ptr.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/network/public/cpp/simple_url_loader.h" + +class BraveCustomNotesAPIHandler { + public: + explicit BraveCustomNotesAPIHandler( + scoped_refptr url_loader_factory); + ~BraveCustomNotesAPIHandler(); + + BraveCustomNotesAPIHandler(const BraveCustomNotesAPIHandler&) = delete; + BraveCustomNotesAPIHandler& operator=(const BraveCustomNotesAPIHandler&) = delete; + + void CallSummarizeAPI(const std::string& content, std::string* summary); + void CallRephraseAPI(const std::string& content, std::string* rephrased_content); + + private: + void OnSummarizeAPISuccess(network::SimpleURLLoader* loader, + std::string* summary, + std::unique_ptr response_body); + void OnRephraseAPISuccess(network::SimpleURLLoader* loader, + std::string* rephrased_content, + std::unique_ptr response_body); + + scoped_refptr url_loader_factory_; + std::vector> loaders_; + base::WeakPtrFactory weak_ptr_factory_{this}; +}; + +#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_API_HANDLER_H_ \ No newline at end of file diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc index 13ebfd405114..321368d7b753 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc @@ -1,7 +1,7 @@ -// Copyright(c) 2022 The Brave Authors.All rights reserved. -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// you can obtain one at http://mozilla.org/MPL/2.0/. +/* Copyright(c) 2022 The Brave Authors.All rights reserved. + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this file, + you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h" @@ -21,6 +21,8 @@ #include "content/public/browser/page_navigator.h" #include "content/public/browser/web_contents.h" +#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h" + namespace { const char kCustomNotesKey[] = "custom_notes"; } // namespace @@ -28,10 +30,12 @@ const char kCustomNotesKey[] = "custom_notes"; BraveCustomNotesPageHandler::BraveCustomNotesPageHandler( Profile* profile, content::WebContents* web_contents, - mojo::PendingReceiver receiver) + mojo::PendingReceiver receiver, + scoped_refptr url_loader_factory) : profile_(profile), web_contents_(web_contents), - receiver_(this, std::move(receiver)) { + receiver_(this, std::move(receiver)), + api_handler_(std::make_unique(url_loader_factory)) { LoadNotesFromPrefs(); } @@ -99,6 +103,44 @@ void BraveCustomNotesPageHandler::EditNote(int32_t note_id, } } +void BraveCustomNotesPageHandler::CallSummarizeAPI( + const std::string& content, std::string* summary) { + api_handler_->CallSummarizeAPI(content, summary); +} + +void BraveCustomNotesPageHandler::CallRephraseAPI( + const std::string& content, std::string* rephrased_content) { + api_handler_->CallRephraseAPI(content, rephrased_content); +} + +void BraveCustomNotesPageHandler::SummarizeNoteContent( + int32_t note_id, SummarizeNoteContentCallback callback) { + // Find the note with the given ID + auto it = std::find_if(notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); + if (it != notes_.end()) { + std::string summary; + CallSummarizeAPI((*it)->content, &summary); + std::move(callback).Run(true,summary); + } else { + std::move(callback).Run(false,"Note not found"); + } +} + +void BraveCustomNotesPageHandler::RephraseNoteContent( + int32_t note_id, RephraseNoteContentCallback callback) { + // Find the note with the given ID + auto it = std::find_if(notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); + if (it != notes_.end()) { + std::string rephrased_content; + CallRephraseAPI((*it)->content, &rephrased_content); + std::move(callback).Run(true,rephrased_content); + } else { + std::move(callback).Run(false,"Note not found"); + } +} + void BraveCustomNotesPageHandler::DeleteNote(int32_t note_id, DeleteNoteCallback callback) { auto it = std::remove_if( @@ -192,3 +234,4 @@ void BraveCustomNotesPageHandler::UpdatePageWithNotes() { } page_->OnNotesUpdated(std::move(notes_copy)); } + diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h index 55a883bb9271..3dc5f414a20d 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h @@ -2,6 +2,7 @@ // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. + #ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_HANDLER_H_ #define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_HANDLER_H_ @@ -16,7 +17,9 @@ #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" +#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h" +// Forward declarations for dependencies class Profile; namespace content { class WebContents; @@ -28,18 +31,19 @@ class BraveCustomNotesPageHandler BraveCustomNotesPageHandler( Profile* profile, content::WebContents* web_contents, - mojo::PendingReceiver - receiver); + mojo::PendingReceiver receiver, + scoped_refptr url_loader_factory); ~BraveCustomNotesPageHandler() override; + // Disable copy and assignment BraveCustomNotesPageHandler(const BraveCustomNotesPageHandler&) = delete; - BraveCustomNotesPageHandler& operator=(const BraveCustomNotesPageHandler&) = - delete; + BraveCustomNotesPageHandler& operator=(const BraveCustomNotesPageHandler&) = delete; - // brave_custom_notes::mojom::NotesPageHandler: + // Implementations for brave_custom_notes::mojom::NotesPageHandler void SetClientPage( - mojo::PendingRemote page) - override; + mojo::PendingRemote page) override; + void SummarizeNoteContent(int32_t note_id, SummarizeNoteContentCallback callback) override; + void RephraseNoteContent(int32_t note_id, RephraseNoteContentCallback callback) override; void CreateNote(const std::string& title, const std::string& content, CreateNoteCallback callback) override; @@ -58,14 +62,18 @@ class BraveCustomNotesPageHandler void SaveNotesToPrefs(); void UpdatePageWithNotes(); + // Pointer members raw_ptr profile_; raw_ptr web_contents_; mojo::Receiver receiver_; mojo::Remote page_; - std::vector notes_; - + std::unique_ptr api_handler_; base::WeakPtrFactory weak_ptr_factory_{this}; + + // Method declarations for API calls + void CallSummarizeAPI(const std::string& content, std::string* summary); + void CallRephraseAPI(const std::string& content, std::string* rephrased_content); }; -#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_HANDLER_H_ +#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_HANDLER_H_ \ No newline at end of file diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc index ef9722155bb9..0eeb0f22cb44 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.cc @@ -14,11 +14,12 @@ #include "brave/components/l10n/common/localization_util.h" #include "chrome/browser/profiles/profile.h" #include "components/grit/brave_components_resources.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/web_ui_data_source.h" BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui, - const std::string& name) + const std::string& name) : ui::MojoWebUIController(web_ui, false) { Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource* source = CreateAndAddWebUIDataSource( @@ -30,6 +31,7 @@ BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui, brave_l10n::GetLocalizedResourceUTF16String(str.id); source->AddString(str.name, l10n_str); } + source->AddBoolean("isWindowTor", profile->IsTor()); AddBackgroundColorToSource(source, web_ui->GetWebContents()); } @@ -37,12 +39,12 @@ BraveCustomNotesUI::BraveCustomNotesUI(content::WebUI* web_ui, BraveCustomNotesUI::~BraveCustomNotesUI() = default; void BraveCustomNotesUI::BindInterface( - mojo::PendingReceiver - receiver) { + mojo::PendingReceiver receiver) { custom_notes_handler_ = std::make_unique( - Profile::FromWebUI(web_ui()), web_ui()->GetWebContents(), - std::move(receiver)); + Profile::FromWebUI(web_ui()), + web_ui()->GetWebContents(), + std::move(receiver), // Pass receiver first + Profile::FromWebUI(web_ui())->GetURLLoaderFactory()); // URL loader factory last } -// Move WEB_UI_CONTROLLER_TYPE_IMPL outside any function or block -WEB_UI_CONTROLLER_TYPE_IMPL(BraveCustomNotesUI) +WEB_UI_CONTROLLER_TYPE_IMPL(BraveCustomNotesUI) \ No newline at end of file diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h index 42c4ec6a3543..002fd7d0684f 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_ui.h @@ -2,28 +2,35 @@ // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. + #ifndef BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ #define BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ + #include #include -#include "brave/components/brave_custom_notes/common/brave_custom_notes.mojom-forward.h" +#include "brave/components/brave_custom_notes/common/brave_custom_notes.mojom.h" #include "content/public/browser/web_ui_controller.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/webui/mojo_web_ui_controller.h" + +class BraveCustomNotesPageHandler; // Forward declaration + class BraveCustomNotesUI : public ui::MojoWebUIController { public: BraveCustomNotesUI(content::WebUI* web_ui, const std::string& name); ~BraveCustomNotesUI() override; + BraveCustomNotesUI(const BraveCustomNotesUI&) = delete; BraveCustomNotesUI& operator=(const BraveCustomNotesUI&) = delete; + void BindInterface( - mojo::PendingReceiver - receiver); + mojo::PendingReceiver receiver); private: - std::unique_ptr - custom_notes_handler_; + std::unique_ptr custom_notes_handler_; + WEB_UI_CONTROLLER_TYPE_DECL(); }; -#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ + +#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_UI_H_ \ No newline at end of file diff --git a/components/brave_custom_notes/common/brave_custom_notes.mojom b/components/brave_custom_notes/common/brave_custom_notes.mojom index 01f9eca950cd..c1ebb34e157f 100644 --- a/components/brave_custom_notes/common/brave_custom_notes.mojom +++ b/components/brave_custom_notes/common/brave_custom_notes.mojom @@ -14,6 +14,8 @@ interface NotesPageHandler { GetNoteContent(int32 note_id) => (bool success, string content); GetAllNotes() => (array notes); AddNote(string content) => (bool success); + SummarizeNoteContent(int32 note_id) => (bool success, string summary); + RephraseNoteContent(int32 note_id) => (bool success, string rephrased_content); }; // Struct that defines the properties of a note. diff --git a/components/brave_custom_notes/resources/page/container.tsx b/components/brave_custom_notes/resources/page/container.tsx index 083099c7f773..8e47d7077cc9 100644 --- a/components/brave_custom_notes/resources/page/container.tsx +++ b/components/brave_custom_notes/resources/page/container.tsx @@ -8,79 +8,68 @@ import styled from 'styled-components'; import getCustomNotesHandlerInstance from './api/brave_custom_notes_handler'; const NotesContainer = styled.div` - display: flex; - flex-direction: column; - align-items: center; - padding: 20px; - max-width: 600px; - margin: 0 auto; - background-color: #f0f4f8; - border-radius: 8px; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); + display: flex; + flex-direction: column; + align-items: center; + padding: 20px; + max-width: 600px; + margin: 0 auto; + background-color: #f0f4f8; + border-radius: 8px; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); `; const Title = styled.h1` - font-size: 24px; - color: #333; - margin-bottom: 20px; + font-size: 24px; + color: #333; + margin-bottom: 20px; `; const NoteInput = styled.textarea` - width: 100%; - padding: 10px; - font-size: 16px; - border: 2px solid #ccc; - border-radius: 5px; - margin-bottom: 15px; - resize: none; - min-height: 80px; + width: 100%; + padding: 10px; + font-size: 16px; + border: 2px solid #ccc; + border-radius: 5px; + margin-bottom: 15px; + resize: none; + min-height: 80px; `; const Button = styled.button` - background-color: #007bff; - color: white; - border: none; - padding: 10px 20px; - font-size: 16px; - border-radius: 5px; - cursor: pointer; - margin-right: 10px; - &:hover { - background-color: #0056b3; - } - `; - -const DeleteButton = styled(Button)` - background-color: #dc3545; - &:hover { - background-color: #c82333; - } + background-color: #007bff; + color: white; + border: none; + padding: 10px 20px; + font-size: 16px; + border-radius: 5px; + cursor: pointer; + margin-right: 10px; + &:hover { + background-color: #0056b3; + } `; const NotesList = styled.ul` - list-style-type: none; - padding: 0; - margin: 20px 0; - width: 100%; + list-style-type: none; + padding: 0; + margin: 20px 0; + width: 100%; `; const NoteItem = styled.li` - background-color: #fff; - padding: 10px; - border-radius: 5px; - margin-bottom: 10px; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); - `; - -const NoNotesMessage = styled.p` - font-size: 16px; - color: #999; + background-color: #fff; + padding: 10px; + border-radius: 5px; + margin-bottom: 10px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); `; interface Note { id: number; title: string; content: string; + summary?: string; timestamp: number; } @@ -105,7 +94,6 @@ const Notes: React.FC = () => { const handleAddNote = () => { if (note.trim()) { - // Add note to the backend via mojom handler customNotesAPI.pageHandler.addNote(note).then(() => { loadNotes(); setNote(''); @@ -134,6 +122,36 @@ const Notes: React.FC = () => { }); }; + // Summarize the selected note + const handleSummarizeNote = (noteId: number) => { + customNotesAPI.pageHandler.summarizeNoteContent(noteId) + .then((response: { success: boolean, summary: string }) => { + if (response.success) { + setNotesList(prevNotes => + prevNotes.map(note => + note.id === noteId ? { ...note, summary: response.summary } : note + ) + ); + } + }) + .catch((err: Error) => { + console.error(err); + }); + }; + + // Rephrase the currently typed note + const handleRephraseNote = () => { + customNotesAPI.pageHandler.rephraseNoteContent(note) + .then((response: { success: boolean, rephrased_content: string }) => { + if (response.success) { + setNote(response.rephrased_content); // Replace the note content with the rephrased version + } + }) + .catch((err: Error) => { + console.error(err); + }); + }; + return ( My Notes @@ -142,16 +160,15 @@ const Notes: React.FC = () => { onChange={(e) => setNote(e.target.value)} placeholder={editingNote ? "Edit note..." : "Write a new note..."} /> - {editingNote ? ( - - ) : ( - - )} + {editingNote && ( )} + {notesList.length === 0 ? ( - No notes added yet! +

No notes added yet!

) : ( {notesList.map((note) => ( @@ -159,9 +176,16 @@ const Notes: React.FC = () => {

{note.title}

{note.content}

{new Date(note.timestamp).toLocaleString()} + {note.summary && ( + <> +

Summary:

+

{note.summary}

+ + )}
- handleDeleteNote(note.id)}>Delete + +
))} @@ -171,4 +195,4 @@ const Notes: React.FC = () => { ); }; -export default Notes; \ No newline at end of file +export default Notes; From 73907f003353b0b85bdce95ed31430c9553b59a5 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Mon, 21 Oct 2024 21:23:57 +0530 Subject: [PATCH 14/21] new changes, response is getting received from the server but not getting communicated to the frontend. --- .../brave_custom_notes_api_handler.cc | 249 +++++++++++------- .../brave_custom_notes_api_handler.h | 23 +- .../brave_custom_notes_handler.cc | 177 ++++++++++--- .../brave_custom_notes_handler.h | 57 ++-- .../resources/page/container.tsx | 171 +++++++++--- 5 files changed, 484 insertions(+), 193 deletions(-) diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc index 62e4cac03fde..6703801e2f62 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc @@ -12,6 +12,7 @@ #include "base/json/json_writer.h" #include "base/values.h" #include "net/traffic_annotation/network_traffic_annotation.h" +#include "base/logging.h" // Traffic annotation for the network requests constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetworkTrafficAnnotation( @@ -31,36 +32,78 @@ constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetwo })"); // API Endpoints -const char kSummarizeAPIEndpoint[] = "https://openai-text-summarizer.azurewebsites.net/summarize"; -const char kRephraseAPIEndpoint[] = "https://openai-text-summarizer.azurewebsites.net/rephrase"; +const char kSummarizeAPIEndpoint[] = "https://ping.openai.azure.com/openai/deployments/ai-summariser-gpt-35-turbo/chat/completions?api-version=2024-02-15-preview"; +const char kRephraseAPIEndpoint[] = "https://ping.openai.azure.com/openai/deployments/ai-summariser-gpt-35-turbo/chat/completions?api-version=2024-02-15-preview"; +const char kAPIKey[] = "b487c4dc0bc1490e801cb6220cf04039"; + +// Constructor implementation +BraveCustomNotesAPIHandler::BraveCustomNotesAPIHandler( + scoped_refptr url_loader_factory) + : url_loader_factory_(std::move(url_loader_factory)) {} + +// Destructor implementation +BraveCustomNotesAPIHandler::~BraveCustomNotesAPIHandler() = default; namespace { +// Create network request loader std::unique_ptr CreateLoader( const GURL& api_url, - const std::string& content) { - VLOG(1) << "Creating loader for URL: " << api_url.spec(); - LOG(INFO) << "Request content length: " << content.length(); + const std::string& content, + const std::string& mode) { + + LOG(INFO) << "Creating loader for URL: " << api_url.spec(); + LOG(INFO) << "Request content to send: " << content; + // Create the resource request auto resource_request = std::make_unique(); resource_request->url = api_url; resource_request->method = "POST"; resource_request->headers.SetHeader("Content-Type", "application/json"); + + // Add API key header (as provided in the CURL command) + resource_request->headers.SetHeader("api-key", kAPIKey); + // Create the URL loader auto loader = network::SimpleURLLoader::Create( std::move(resource_request), kTrafficAnnotation); - + + // Building JSON body for the request + base::Value::Dict system_message; + if (mode == "summarize") { + system_message.Set("role", "system"); + system_message.Set("content", "You are a Ping AI summariser whose job is to create a summary of the text in a webpage. You help the user by creating bullet points which make it easier to get a gist of the webpage he is viewing. You also add emojis in the bullet points to make it more engaging. You create short to the point summaries for the user. Each point must not be more than a short sentence."); + } else if (mode == "rephrase") { + system_message.Set("role", "system"); + system_message.Set("content", "You are an AI designed to rephrase text. Please rephrase the provided content to make it clearer and more concise."); + } + + base::Value::Dict user_message; + user_message.Set("role", "user"); + user_message.Set("content", content); + + base::Value::List messages; + messages.Append(std::move(system_message)); + messages.Append(std::move(user_message)); + base::Value::Dict request_dict; - request_dict.Set("content", content); + request_dict.Set("messages", std::move(messages)); + request_dict.Set("max_tokens", 800); + request_dict.Set("temperature", 0.5); + request_dict.Set("frequency_penalty", 0); + request_dict.Set("presence_penalty", 0); + request_dict.Set("top_p", 0.95); + std::string request_body; base::JSONWriter::Write(request_dict, &request_body); - VLOG(2) << "Request body: " << request_body; + LOG(INFO) << "JSON request body: " << request_body; + // Attach the JSON body to the loader loader->AttachStringForUpload(request_body, "application/json"); - - // Set retry options + + // Set retry options in case of network errors loader->SetRetryOptions( 3, // max retries network::SimpleURLLoader::RetryMode::RETRY_ON_NETWORK_CHANGE); @@ -70,74 +113,83 @@ std::unique_ptr CreateLoader( } // namespace -BraveCustomNotesAPIHandler::BraveCustomNotesAPIHandler( - scoped_refptr url_loader_factory) - : url_loader_factory_(std::move(url_loader_factory)) { - LOG(INFO) << "BraveCustomNotesAPIHandler initialized"; - } +// Handle API response for both Summarize and Rephrase +void BraveCustomNotesAPIHandler::OnAPIResponse( + network::SimpleURLLoader* loader, + std::string* output_content, + std::unique_ptr response_body) { + LOG(INFO) << "Processing API response"; -BraveCustomNotesAPIHandler::~BraveCustomNotesAPIHandler(){ - LOG(INFO) << "BraveCustomNotesAPIHandler destroyed"; - if (!loaders_.empty()) { - LOG(WARNING) << "Destroying handler with " << loaders_.size() - << " pending requests"; - } -} + if (response_body) { + LOG(INFO) << "API response body: " << *response_body; -void BraveCustomNotesAPIHandler::CallSummarizeAPI( - const std::string& content, std::string* summary) { - VLOG(1) << "Calling summarize API"; - GURL api_url(kSummarizeAPIEndpoint); - auto loader = CreateLoader(api_url, content); + // Attempt to read and parse the JSON response + auto json_result = base::JSONReader::Read(*response_body); + + if (!json_result) { + LOG(ERROR) << "Failed to parse JSON response."; + *output_content = "Failed to parse JSON response."; + return; + } + + if (!json_result->is_dict()) { + LOG(ERROR) << "Parsed JSON is not a dictionary."; + *output_content = "Parsed JSON is not a dictionary."; + return; + } - loader->DownloadToString( - url_loader_factory_.get(), - base::BindOnce(&BraveCustomNotesAPIHandler::OnSummarizeAPISuccess, - weak_ptr_factory_.GetWeakPtr(), loader.get(), summary), - 1024 * 1024 /* 1MB max size */); + // Get the list of choices + const base::Value::List* choices = json_result->GetDict().FindList("choices"); + if (!choices) { + LOG(ERROR) << "'choices' not found in the response."; + *output_content = "'choices' not found in the response."; + return; + } - loaders_.push_back(std::move(loader)); - VLOG(1) << "Summarize request sent. Active loaders: " << loaders_.size(); -} + if (choices->empty()) { + LOG(ERROR) << "No choices found in the response."; + *output_content = "No choices found in the response."; + return; + } -void BraveCustomNotesAPIHandler::CallRephraseAPI( - const std::string& content, std::string* rephrased_content) { - VLOG(1) << "Calling rephrase API"; - GURL api_url(kRephraseAPIEndpoint); - auto loader = CreateLoader(api_url, content); + // Access the first choice + const base::Value::Dict& first_choice = choices->front().GetDict(); - loader->DownloadToString( - url_loader_factory_.get(), - base::BindOnce(&BraveCustomNotesAPIHandler::OnRephraseAPISuccess, - weak_ptr_factory_.GetWeakPtr(), loader.get(), rephrased_content), - 1024 * 1024 /* 1MB max size */); + // Log the entire first choice for debugging + LOG(INFO) << "First choice: " << first_choice.DebugString(); - loaders_.push_back(std::move(loader)); - VLOG(1) << "Rephrase request sent. Active loaders: " << loaders_.size(); -} + // Extract the message content + const base::Value::Dict* message = first_choice.FindDict("message"); + if (!message) { + LOG(ERROR) << "'message' not found in the first choice."; + *output_content = "'message' not found in the first choice."; + return; + } -void BraveCustomNotesAPIHandler::OnSummarizeAPISuccess( - network::SimpleURLLoader* loader, - std::string* summary, - std::unique_ptr response_body) { - VLOG(1) << "Processing summarize API response"; - if (response_body) { - auto json_result = base::JSONReader::Read(*response_body); - if (json_result && json_result->is_dict()) { - const std::string* api_result = json_result->GetDict().FindString("summary"); - if (api_result) { - *summary = *api_result; - } else { - *summary = "Key 'summary' not found in the response."; - } + const std::string* api_result = message->FindString("content"); + if (api_result) { + *output_content = *api_result; // Set output_content to the extracted message + } else { + LOG(ERROR) << "'content' not found in 'message'."; + *output_content = "'content' not found in 'message'."; + } + + // Optionally log content filter results + const base::Value::Dict* content_filter_results = first_choice.FindDict("content_filter_results"); + if (content_filter_results) { + LOG(INFO) << "Content filter results: " << content_filter_results->DebugString(); } else { - *summary = "Invalid JSON response."; + LOG(INFO) << "No content filter results found."; } } else { - *summary = "Failed to get a response."; + LOG(ERROR) << "Failed to get a response."; + *output_content = "Failed to get a response."; } - // Cleanup completed loader + // Log the output content for debugging + LOG(INFO) << "Output content: " << *output_content; + + // Remove completed loader from the active loaders list auto it = std::find_if(loaders_.begin(), loaders_.end(), [loader](const std::unique_ptr& l) { return l.get() == loader; @@ -147,32 +199,47 @@ void BraveCustomNotesAPIHandler::OnSummarizeAPISuccess( } } -void BraveCustomNotesAPIHandler::OnRephraseAPISuccess( - network::SimpleURLLoader* loader, - std::string* rephrased_content, - std::unique_ptr response_body) { - if (response_body) { - auto json_result = base::JSONReader::Read(*response_body); - if (json_result && json_result->is_dict()) { - const std::string* api_result = json_result->GetDict().FindString("rephrased_content"); - if (api_result) { - *rephrased_content = *api_result; - } else { - *rephrased_content = "Key 'rephrased_content' not found in the response."; - } - } else { - *rephrased_content = "Invalid JSON response."; - } - } else { - *rephrased_content = "Failed to get a response."; + +// Function to call the Summarize API +void BraveCustomNotesAPIHandler::CallSummarizeAPI( + const std::string& content, std::string* summary) { + + GURL api_url(kSummarizeAPIEndpoint); + LOG(INFO) << "Attempting to call Summarize API at: " << api_url.spec(); + auto loader = CreateLoader(api_url, content, "summarize"); + + // Check if loader was created successfully + if (!loader) { + LOG(ERROR) << "Failed to create loader for Summarize API."; + return; } - // Cleanup completed loader - auto it = std::find_if(loaders_.begin(), loaders_.end(), - [loader](const std::unique_ptr& l) { - return l.get() == loader; - }); - if (it != loaders_.end()) { - loaders_.erase(it); + loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + url_loader_factory_.get(), + base::BindOnce(&BraveCustomNotesAPIHandler::OnAPIResponse, + base::Unretained(this), loader.get(), summary)); + + loaders_.push_back(std::move(loader)); +} + +// Function to call the Rephrase API +void BraveCustomNotesAPIHandler::CallRephraseAPI( + const std::string& content, std::string* rephrased_content) { + + GURL api_url(kRephraseAPIEndpoint); + LOG(INFO) << "Attempting to call Rephrase API at: " << api_url.spec(); + auto loader = CreateLoader(api_url, content, "rephrase"); + + // Check if loader was created successfully + if (!loader) { + LOG(ERROR) << "Failed to create loader for Rephrase API."; + return; } -} \ No newline at end of file + + loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + url_loader_factory_.get(), + base::BindOnce(&BraveCustomNotesAPIHandler::OnAPIResponse, + base::Unretained(this), loader.get(), rephrased_content)); + + loaders_.push_back(std::move(loader)); +} diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h index 087f4081ba7d..4d84ff30b80a 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h @@ -16,27 +16,44 @@ class BraveCustomNotesAPIHandler { public: + // Constructor that initializes the URL loader factory explicit BraveCustomNotesAPIHandler( scoped_refptr url_loader_factory); + + // Destructor ~BraveCustomNotesAPIHandler(); + // Delete copy constructor and assignment operator to avoid object copying BraveCustomNotesAPIHandler(const BraveCustomNotesAPIHandler&) = delete; BraveCustomNotesAPIHandler& operator=(const BraveCustomNotesAPIHandler&) = delete; + // Public methods to call the Summarize and Rephrase API endpoints void CallSummarizeAPI(const std::string& content, std::string* summary); void CallRephraseAPI(const std::string& content, std::string* rephrased_content); private: - void OnSummarizeAPISuccess(network::SimpleURLLoader* loader, + // Private method to handle the success response from Summarize API + void OnSummarizeAPIResponse(network::SimpleURLLoader* loader, std::string* summary, std::unique_ptr response_body); - void OnRephraseAPISuccess(network::SimpleURLLoader* loader, + + void OnAPIResponse(network::SimpleURLLoader* loader, + std::string* output_content, + std::unique_ptr response_body); + + // Private method to handle the success response from Rephrase API + void OnRephraseAPIResponse(network::SimpleURLLoader* loader, std::string* rephrased_content, std::unique_ptr response_body); + // URL loader factory to handle network requests scoped_refptr url_loader_factory_; + + // A vector to hold all active URL loaders to manage their lifetimes std::vector> loaders_; + + // Weak pointer factory to safely manage asynchronous callbacks base::WeakPtrFactory weak_ptr_factory_{this}; }; -#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_API_HANDLER_H_ \ No newline at end of file +#endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_API_HANDLER_H_ diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc index 321368d7b753..65cb6778b545 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc @@ -1,7 +1,7 @@ -/* Copyright(c) 2022 The Brave Authors.All rights reserved. - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this file, - you can obtain one at http://mozilla.org/MPL/2.0/. */ +/* Copyright(c) 2022 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h" @@ -9,6 +9,7 @@ #include #include #include +#include #include "base/functional/bind.h" #include "base/strings/utf_string_conversions.h" @@ -27,6 +28,28 @@ namespace { const char kCustomNotesKey[] = "custom_notes"; } // namespace +class BraveCustomNotesPageHandler::APICallbackHelper { + public: + explicit APICallbackHelper(base::WeakPtr handler, + int32_t note_id) + : handler_(handler), + note_id_(note_id) {} + + void OnSummarizeComplete(const std::string& summary) { + if (handler_) + handler_->OnSummarizeComplete(note_id_, summary); + } + + void OnRephraseComplete(const std::string& rephrased) { + if (handler_) + handler_->OnRephraseComplete(note_id_, rephrased); + } + + private: + base::WeakPtr handler_; + int32_t note_id_; +}; + BraveCustomNotesPageHandler::BraveCustomNotesPageHandler( Profile* profile, content::WebContents* web_contents, @@ -35,7 +58,8 @@ BraveCustomNotesPageHandler::BraveCustomNotesPageHandler( : profile_(profile), web_contents_(web_contents), receiver_(this, std::move(receiver)), - api_handler_(std::make_unique(url_loader_factory)) { + api_handler_(std::make_unique(url_loader_factory)), + weak_ptr_factory_(this) { LoadNotesFromPrefs(); } @@ -47,8 +71,8 @@ void BraveCustomNotesPageHandler::SetClientPage( } void BraveCustomNotesPageHandler::CreateNote(const std::string& title, - const std::string& content, - CreateNoteCallback callback) { + const std::string& content, + CreateNoteCallback callback) { auto new_note = brave_custom_notes::mojom::Note::New(); new_note->id = notes_.empty() ? 1 : notes_.back()->id + 1; new_note->title = title; @@ -65,7 +89,7 @@ void BraveCustomNotesPageHandler::CreateNote(const std::string& title, } void BraveCustomNotesPageHandler::AddNote(const std::string& content, - AddNoteCallback callback) { + AddNoteCallback callback) { auto new_note = brave_custom_notes::mojom::Note::New(); new_note->id = notes_.empty() ? 1 : notes_.back()->id + 1; new_note->title = "New Note"; @@ -82,12 +106,11 @@ void BraveCustomNotesPageHandler::AddNote(const std::string& content, } void BraveCustomNotesPageHandler::EditNote(int32_t note_id, - const std::string& new_title, - const std::string& new_content, - EditNoteCallback callback) { - auto it = - std::find_if(notes_.begin(), notes_.end(), - [note_id](const auto& note) { return note->id == note_id; }); + const std::string& new_title, + const std::string& new_content, + EditNoteCallback callback) { + auto it = std::find_if(notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); if (it != notes_.end()) { (*it)->title = new_title; @@ -103,46 +126,118 @@ void BraveCustomNotesPageHandler::EditNote(int32_t note_id, } } -void BraveCustomNotesPageHandler::CallSummarizeAPI( - const std::string& content, std::string* summary) { - api_handler_->CallSummarizeAPI(content, summary); -} - -void BraveCustomNotesPageHandler::CallRephraseAPI( - const std::string& content, std::string* rephrased_content) { - api_handler_->CallRephraseAPI(content, rephrased_content); -} - void BraveCustomNotesPageHandler::SummarizeNoteContent( int32_t note_id, SummarizeNoteContentCallback callback) { - // Find the note with the given ID auto it = std::find_if(notes_.begin(), notes_.end(), - [note_id](const auto& note) { return note->id == note_id; }); + [note_id](const auto& note) { return note->id == note_id; }); + if (it != notes_.end()) { - std::string summary; - CallSummarizeAPI((*it)->content, &summary); - std::move(callback).Run(true,summary); + // Log the start of the summarization process + LOG(INFO) << "Starting to summarize note with ID: " << note_id; + + // Store the callback for later use + pending_summarize_callbacks_[note_id] = std::move(callback); + + // Create a string to store the summary + auto summary = std::make_unique(); + + // Create a helper to handle the API callback + auto helper = std::make_unique( + weak_ptr_factory_.GetWeakPtr(), note_id); + + // Log the note content being passed to the summarization API + LOG(INFO) << "Note content being summarized: " << (*it)->content; + + // Call the API with the note content + api_handler_->CallSummarizeAPI((*it)->content, summary.get()); + + // Store the output string + pending_summaries_[note_id] = std::move(summary); + } else { - std::move(callback).Run(false,"Note not found"); + LOG(WARNING) << "Failed to find note with ID: " << note_id; + std::move(callback).Run(false, "Note not found"); } } +// Inside the RephraseNoteContent function void BraveCustomNotesPageHandler::RephraseNoteContent( int32_t note_id, RephraseNoteContentCallback callback) { - // Find the note with the given ID auto it = std::find_if(notes_.begin(), notes_.end(), - [note_id](const auto& note) { return note->id == note_id; }); + [note_id](const auto& note) { return note->id == note_id; }); + if (it != notes_.end()) { - std::string rephrased_content; - CallRephraseAPI((*it)->content, &rephrased_content); - std::move(callback).Run(true,rephrased_content); + // Log the start of the rephrasing process + LOG(INFO) << "Starting to rephrase note with ID: " << note_id; + + // Store the callback for later use + pending_rephrase_callbacks_[note_id] = std::move(callback); + + // Create a string to store the rephrased content + auto rephrased = std::make_unique(); + + // Create a helper to handle the API callback + auto helper = std::make_unique( + weak_ptr_factory_.GetWeakPtr(), note_id); + + // Log the note content being passed to the rephrasing API + LOG(INFO) << "Note content being rephrased: " << (*it)->content; + + // Call the API with the note content + api_handler_->CallRephraseAPI((*it)->content, rephrased.get()); + + // Store the output string + pending_rephrased_[note_id] = std::move(rephrased); } else { - std::move(callback).Run(false,"Note not found"); + LOG(WARNING) << "Failed to find note with ID: " << note_id; + std::move(callback).Run(false, "Note not found"); + } +} + +// Inside the OnSummarizeComplete function +void BraveCustomNotesPageHandler::OnSummarizeComplete( + int32_t note_id, + const std::string& summary) { + auto callback_it = pending_summarize_callbacks_.find(note_id); + auto summary_it = pending_summaries_.find(note_id); + + if (callback_it != pending_summarize_callbacks_.end() && + summary_it != pending_summaries_.end()) { + // Log the completion of the summarization process + LOG(INFO) << "Summarization complete for note with ID: " << note_id; + LOG(INFO) << "Summary: " << summary; + + std::move(callback_it->second).Run(true, summary); + pending_summarize_callbacks_.erase(callback_it); + pending_summaries_.erase(summary_it); + } else { + LOG(WARNING) << "Summarization callback or summary not found for note with ID: " << note_id; + } +} + +// Inside the OnRephraseComplete function +void BraveCustomNotesPageHandler::OnRephraseComplete( + int32_t note_id, + const std::string& rephrased) { + auto callback_it = pending_rephrase_callbacks_.find(note_id); + auto rephrased_it = pending_rephrased_.find(note_id); + + if (callback_it != pending_rephrase_callbacks_.end() && + rephrased_it != pending_rephrased_.end()) { + // Log the completion of the rephrasing process + LOG(INFO) << "Rephrasing complete for note with ID: " << note_id; + LOG(INFO) << "Rephrased content: " << rephrased; + + std::move(callback_it->second).Run(true, rephrased); + pending_rephrase_callbacks_.erase(callback_it); + pending_rephrased_.erase(rephrased_it); + } else { + LOG(WARNING) << "Rephrasing callback or rephrased content not found for note with ID: " << note_id; } } void BraveCustomNotesPageHandler::DeleteNote(int32_t note_id, - DeleteNoteCallback callback) { + DeleteNoteCallback callback) { auto it = std::remove_if( notes_.begin(), notes_.end(), [note_id](const auto& note) { return note->id == note_id; }); @@ -163,9 +258,8 @@ void BraveCustomNotesPageHandler::DeleteNote(int32_t note_id, void BraveCustomNotesPageHandler::GetNoteContent( int32_t note_id, GetNoteContentCallback callback) { - auto it = - std::find_if(notes_.begin(), notes_.end(), - [note_id](const auto& note) { return note->id == note_id; }); + auto it = std::find_if(notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); if (it != notes_.end()) { std::move(callback).Run(true, (*it)->content); @@ -233,5 +327,4 @@ void BraveCustomNotesPageHandler::UpdatePageWithNotes() { notes_copy.push_back(note.Clone()); } page_->OnNotesUpdated(std::move(notes_copy)); -} - +} \ No newline at end of file diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h index 3dc5f414a20d..9891277ded41 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h @@ -1,4 +1,4 @@ -// Copyright (c) 2022 The Brave Authors. All rights reserved. +// Copyright(c) 2022 The Brave Authors. All rights reserved. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. @@ -9,18 +9,19 @@ #include #include #include +#include -#include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" -#include "brave/components/brave_custom_notes/common/brave_custom_notes.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" -#include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "brave/components/brave_custom_notes/common/brave_custom_notes.mojom.h" -// Forward declarations for dependencies class Profile; +class BraveCustomNotesAPIHandler; + namespace content { class WebContents; } @@ -33,47 +34,57 @@ class BraveCustomNotesPageHandler content::WebContents* web_contents, mojo::PendingReceiver receiver, scoped_refptr url_loader_factory); - ~BraveCustomNotesPageHandler() override; - // Disable copy and assignment BraveCustomNotesPageHandler(const BraveCustomNotesPageHandler&) = delete; BraveCustomNotesPageHandler& operator=(const BraveCustomNotesPageHandler&) = delete; - // Implementations for brave_custom_notes::mojom::NotesPageHandler + ~BraveCustomNotesPageHandler() override; + + // brave_custom_notes::mojom::NotesPageHandler: void SetClientPage( mojo::PendingRemote page) override; - void SummarizeNoteContent(int32_t note_id, SummarizeNoteContentCallback callback) override; - void RephraseNoteContent(int32_t note_id, RephraseNoteContentCallback callback) override; void CreateNote(const std::string& title, - const std::string& content, - CreateNoteCallback callback) override; + const std::string& content, + CreateNoteCallback callback) override; + void AddNote(const std::string& content, AddNoteCallback callback) override; void EditNote(int32_t note_id, - const std::string& new_title, - const std::string& new_content, - EditNoteCallback callback) override; + const std::string& new_title, + const std::string& new_content, + EditNoteCallback callback) override; void DeleteNote(int32_t note_id, DeleteNoteCallback callback) override; void GetNoteContent(int32_t note_id, - GetNoteContentCallback callback) override; + GetNoteContentCallback callback) override; void GetAllNotes(GetAllNotesCallback callback) override; - void AddNote(const std::string& content, AddNoteCallback callback) override; + void SummarizeNoteContent(int32_t note_id, + SummarizeNoteContentCallback callback) override; + void RephraseNoteContent(int32_t note_id, + RephraseNoteContentCallback callback) override; private: + class APICallbackHelper; + void LoadNotesFromPrefs(); void SaveNotesToPrefs(); void UpdatePageWithNotes(); + + void OnSummarizeComplete(int32_t note_id, const std::string& summary); + void OnRephraseComplete(int32_t note_id, const std::string& rephrased); - // Pointer members raw_ptr profile_; raw_ptr web_contents_; mojo::Receiver receiver_; mojo::Remote page_; - std::vector notes_; std::unique_ptr api_handler_; - base::WeakPtrFactory weak_ptr_factory_{this}; - // Method declarations for API calls - void CallSummarizeAPI(const std::string& content, std::string* summary); - void CallRephraseAPI(const std::string& content, std::string* rephrased_content); + std::vector notes_; + + std::map pending_summarize_callbacks_; + std::map> pending_summaries_; + + std::map pending_rephrase_callbacks_; + std::map> pending_rephrased_; + + base::WeakPtrFactory weak_ptr_factory_; }; #endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_CUSTOM_NOTES_BRAVE_CUSTOM_NOTES_HANDLER_H_ \ No newline at end of file diff --git a/components/brave_custom_notes/resources/page/container.tsx b/components/brave_custom_notes/resources/page/container.tsx index 8e47d7077cc9..53fea58dd011 100644 --- a/components/brave_custom_notes/resources/page/container.tsx +++ b/components/brave_custom_notes/resources/page/container.tsx @@ -7,6 +7,7 @@ import { useState, useEffect } from 'react'; import styled from 'styled-components'; import getCustomNotesHandlerInstance from './api/brave_custom_notes_handler'; +// Styled Components const NotesContainer = styled.div` display: flex; flex-direction: column; @@ -46,7 +47,7 @@ const Button = styled.button` cursor: pointer; margin-right: 10px; &:hover { - background-color: #0056b3; + background-color: #0056b3; } `; @@ -65,6 +66,7 @@ const NoteItem = styled.li` box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); `; +// Note interface interface Note { id: number; title: string; @@ -77,27 +79,42 @@ const Notes: React.FC = () => { const [note, setNote] = useState(''); const [notesList, setNotesList] = useState([]); const [editingNote, setEditingNote] = useState(null); + const [isLoading, setIsLoading] = useState(false); // Fetch mojom instance const customNotesAPI = getCustomNotesHandlerInstance(); - // Load existing notes on component mount (from backend) + // Load existing notes on component mount useEffect(() => { loadNotes(); }, []); const loadNotes = () => { - customNotesAPI.pageHandler.getAllNotes().then((response: { notes: Note[] }) => { - setNotesList(response.notes || []); - }); + customNotesAPI.pageHandler.getAllNotes() + .then((response: { notes: Note[] }) => { + setNotesList(response.notes || []); + }) + .catch((err: Error) => { + console.error(err); + alert('Failed to load notes. Please try again.'); + }); }; const handleAddNote = () => { if (note.trim()) { - customNotesAPI.pageHandler.addNote(note).then(() => { - loadNotes(); - setNote(''); - }); + setIsLoading(true); + customNotesAPI.pageHandler.addNote(note) + .then(() => { + loadNotes(); + setNote(''); + }) + .catch((err: Error) => { + console.error(err); + alert('Failed to add note. Please try again.'); + }) + .finally(() => { + setIsLoading(false); + }); } }; @@ -108,47 +125,107 @@ const Notes: React.FC = () => { const handleUpdateNote = () => { if (editingNote && note.trim()) { - customNotesAPI.pageHandler.editNote(editingNote.id, editingNote.title, note).then(() => { - loadNotes(); - setNote(''); - setEditingNote(null); - }); + setIsLoading(true); + customNotesAPI.pageHandler.editNote(editingNote.id, editingNote.title, note) + .then(() => { + loadNotes(); + setNote(''); + setEditingNote(null); + }) + .catch((err: Error) => { + console.error(err); + alert('Failed to update note. Please try again.'); + }) + .finally(() => { + setIsLoading(false); + }); } }; const handleDeleteNote = (noteId: number) => { - customNotesAPI.pageHandler.deleteNote(noteId).then(() => { - loadNotes(); - }); + setIsLoading(true); + customNotesAPI.pageHandler.deleteNote(noteId) + .then(() => { + loadNotes(); + }) + .catch((err: Error) => { + console.error(err); + alert('Failed to delete note. Please try again.'); + }) + .finally(() => { + setIsLoading(false); + }); }; // Summarize the selected note const handleSummarizeNote = (noteId: number) => { + setIsLoading(true); customNotesAPI.pageHandler.summarizeNoteContent(noteId) .then((response: { success: boolean, summary: string }) => { if (response.success) { setNotesList(prevNotes => prevNotes.map(note => - note.id === noteId ? { ...note, summary: response.summary } : note + note.id === noteId + ? { + ...note, + summary: response.summary, // Store summary in note object + content: note.content // Preserve original content + } + : note ) ); + } else { + alert('Failed to summarize note. Please try again.'); } }) .catch((err: Error) => { console.error(err); + alert('Failed to summarize note. Please try again.'); + }) + .finally(() => { + setIsLoading(false); }); }; // Rephrase the currently typed note const handleRephraseNote = () => { - customNotesAPI.pageHandler.rephraseNoteContent(note) + if (!note.trim()) { + alert('Please enter some text to rephrase.'); + return; + } + + setIsLoading(true); + // If editing a note, use its ID, otherwise use a temporary ID + const noteId = editingNote ? editingNote.id : -1; + + customNotesAPI.pageHandler.rephraseNoteContent(noteId) .then((response: { success: boolean, rephrased_content: string }) => { if (response.success) { - setNote(response.rephrased_content); // Replace the note content with the rephrased version + if (editingNote) { + // If editing an existing note, update it in the list + setNotesList(prevNotes => + prevNotes.map(note => + note.id === editingNote.id + ? { + ...note, + content: response.rephrased_content + } + : note + ) + ); + } + // Update the note input field + setNote(response.rephrased_content); + } else { + alert('Failed to rephrase note. Please try again.'); } }) .catch((err: Error) => { console.error(err); + alert('Failed to rephrase note. Please try again.'); + }) + .finally(() => { + setIsLoading(false); }); }; @@ -160,13 +237,24 @@ const Notes: React.FC = () => { onChange={(e) => setNote(e.target.value)} placeholder={editingNote ? "Edit note..." : "Write a new note..."} /> - - {editingNote && ( - - )} - +
+ + {editingNote && ( + + )} + +
+ {notesList.length === 0 ? (

No notes added yet!

) : ( @@ -177,15 +265,30 @@ const Notes: React.FC = () => {

{note.content}

{new Date(note.timestamp).toLocaleString()} {note.summary && ( - <> +

Summary:

{note.summary}

- +
)} -
- - - +
+ + +
))} @@ -195,4 +298,4 @@ const Notes: React.FC = () => { ); }; -export default Notes; +export default Notes; \ No newline at end of file From 173ee6f7a59ad79a5f610df17181ef253bab8d16 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Sat, 16 Nov 2024 19:17:36 +0530 Subject: [PATCH 15/21] callbacks implemented successfully, asynchronous architecture is fully working for api calls. --- .../brave_custom_notes_api_handler.cc | 157 +++++------------- .../brave_custom_notes_api_handler.h | 14 +- .../brave_custom_notes_handler.cc | 145 ++++++++-------- .../brave_custom_notes_handler.h | 1 + 4 files changed, 117 insertions(+), 200 deletions(-) diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc index 6703801e2f62..91683dabc16f 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc @@ -113,133 +113,50 @@ std::unique_ptr CreateLoader( } // namespace -// Handle API response for both Summarize and Rephrase -void BraveCustomNotesAPIHandler::OnAPIResponse( - network::SimpleURLLoader* loader, - std::string* output_content, - std::unique_ptr response_body) { - LOG(INFO) << "Processing API response"; - - if (response_body) { - LOG(INFO) << "API response body: " << *response_body; - - // Attempt to read and parse the JSON response - auto json_result = base::JSONReader::Read(*response_body); - - if (!json_result) { - LOG(ERROR) << "Failed to parse JSON response."; - *output_content = "Failed to parse JSON response."; - return; - } - - if (!json_result->is_dict()) { - LOG(ERROR) << "Parsed JSON is not a dictionary."; - *output_content = "Parsed JSON is not a dictionary."; - return; - } - - // Get the list of choices - const base::Value::List* choices = json_result->GetDict().FindList("choices"); - if (!choices) { - LOG(ERROR) << "'choices' not found in the response."; - *output_content = "'choices' not found in the response."; - return; - } - - if (choices->empty()) { - LOG(ERROR) << "No choices found in the response."; - *output_content = "No choices found in the response."; - return; - } - - // Access the first choice - const base::Value::Dict& first_choice = choices->front().GetDict(); - // Log the entire first choice for debugging - LOG(INFO) << "First choice: " << first_choice.DebugString(); - - // Extract the message content - const base::Value::Dict* message = first_choice.FindDict("message"); - if (!message) { - LOG(ERROR) << "'message' not found in the first choice."; - *output_content = "'message' not found in the first choice."; - return; - } - - const std::string* api_result = message->FindString("content"); - if (api_result) { - *output_content = *api_result; // Set output_content to the extracted message - } else { - LOG(ERROR) << "'content' not found in 'message'."; - *output_content = "'content' not found in 'message'."; - } - - // Optionally log content filter results - const base::Value::Dict* content_filter_results = first_choice.FindDict("content_filter_results"); - if (content_filter_results) { - LOG(INFO) << "Content filter results: " << content_filter_results->DebugString(); - } else { - LOG(INFO) << "No content filter results found."; - } - } else { - LOG(ERROR) << "Failed to get a response."; - *output_content = "Failed to get a response."; - } - - // Log the output content for debugging - LOG(INFO) << "Output content: " << *output_content; - - // Remove completed loader from the active loaders list - auto it = std::find_if(loaders_.begin(), loaders_.end(), - [loader](const std::unique_ptr& l) { - return l.get() == loader; - }); - if (it != loaders_.end()) { - loaders_.erase(it); - } -} - - -// Function to call the Summarize API void BraveCustomNotesAPIHandler::CallSummarizeAPI( - const std::string& content, std::string* summary) { - - GURL api_url(kSummarizeAPIEndpoint); - LOG(INFO) << "Attempting to call Summarize API at: " << api_url.spec(); - auto loader = CreateLoader(api_url, content, "summarize"); - - // Check if loader was created successfully - if (!loader) { - LOG(ERROR) << "Failed to create loader for Summarize API."; - return; - } + const std::string& content, + base::OnceCallback callback) { + auto loader = CreateLoader(GURL(kSummarizeAPIEndpoint), content, "summarize"); - loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + loader->DownloadToString( url_loader_factory_.get(), - base::BindOnce(&BraveCustomNotesAPIHandler::OnAPIResponse, - base::Unretained(this), loader.get(), summary)); - - loaders_.push_back(std::move(loader)); + base::BindOnce( + [](std::unique_ptr loader, + base::OnceCallback callback, + std::unique_ptr response_body) { + if (response_body && !response_body->empty()) { + LOG(INFO) << "Summarize API response: " << *response_body; + std::move(callback).Run(*response_body); + } else { + LOG(ERROR) << "Failed to get response from Summarize API."; + std::move(callback).Run(""); + } + }, + std::move(loader), std::move(callback)), + 1024 * 1024); // Max response body size } -// Function to call the Rephrase API void BraveCustomNotesAPIHandler::CallRephraseAPI( - const std::string& content, std::string* rephrased_content) { - - GURL api_url(kRephraseAPIEndpoint); - LOG(INFO) << "Attempting to call Rephrase API at: " << api_url.spec(); - auto loader = CreateLoader(api_url, content, "rephrase"); - - // Check if loader was created successfully - if (!loader) { - LOG(ERROR) << "Failed to create loader for Rephrase API."; - return; - } + const std::string& content, + base::OnceCallback callback) { + auto loader = CreateLoader(GURL(kRephraseAPIEndpoint), content, "rephrase"); - loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + loader->DownloadToString( url_loader_factory_.get(), - base::BindOnce(&BraveCustomNotesAPIHandler::OnAPIResponse, - base::Unretained(this), loader.get(), rephrased_content)); - - loaders_.push_back(std::move(loader)); + base::BindOnce( + [](std::unique_ptr loader, + base::OnceCallback callback, + std::unique_ptr response_body) { + if (response_body && !response_body->empty()) { + LOG(INFO) << "Rephrase API response: " << *response_body; + std::move(callback).Run(*response_body); + } else { + LOG(ERROR) << "Failed to get response from Rephrase API."; + std::move(callback).Run(""); + } + }, + std::move(loader), std::move(callback)), + 1024 * 1024); // Max response body size } + diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h index 4d84ff30b80a..e4ab786453a0 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.h @@ -27,9 +27,13 @@ class BraveCustomNotesAPIHandler { BraveCustomNotesAPIHandler(const BraveCustomNotesAPIHandler&) = delete; BraveCustomNotesAPIHandler& operator=(const BraveCustomNotesAPIHandler&) = delete; - // Public methods to call the Summarize and Rephrase API endpoints - void CallSummarizeAPI(const std::string& content, std::string* summary); - void CallRephraseAPI(const std::string& content, std::string* rephrased_content); + void CallSummarizeAPI( + const std::string& content, + base::OnceCallback callback); + +void CallRephraseAPI( + const std::string& content, + base::OnceCallback callback); private: // Private method to handle the success response from Summarize API @@ -37,10 +41,6 @@ class BraveCustomNotesAPIHandler { std::string* summary, std::unique_ptr response_body); - void OnAPIResponse(network::SimpleURLLoader* loader, - std::string* output_content, - std::unique_ptr response_body); - // Private method to handle the success response from Rephrase API void OnRephraseAPIResponse(network::SimpleURLLoader* loader, std::string* rephrased_content, diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc index 65cb6778b545..db2359d0c30a 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc @@ -4,6 +4,8 @@ * you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "brave/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h" +#include "base/json/json_reader.h" +#include "base/values.h" #include #include @@ -129,110 +131,107 @@ void BraveCustomNotesPageHandler::EditNote(int32_t note_id, void BraveCustomNotesPageHandler::SummarizeNoteContent( int32_t note_id, SummarizeNoteContentCallback callback) { auto it = std::find_if(notes_.begin(), notes_.end(), - [note_id](const auto& note) { return note->id == note_id; }); + [note_id](const auto& note) { return note->id == note_id; }); if (it != notes_.end()) { - // Log the start of the summarization process - LOG(INFO) << "Starting to summarize note with ID: " << note_id; - - // Store the callback for later use + LOG(INFO) << "Starting async summarize for note ID: " << note_id; pending_summarize_callbacks_[note_id] = std::move(callback); - - // Create a string to store the summary - auto summary = std::make_unique(); - - // Create a helper to handle the API callback - auto helper = std::make_unique( - weak_ptr_factory_.GetWeakPtr(), note_id); - - // Log the note content being passed to the summarization API - LOG(INFO) << "Note content being summarized: " << (*it)->content; - - // Call the API with the note content - api_handler_->CallSummarizeAPI((*it)->content, summary.get()); - - // Store the output string - pending_summaries_[note_id] = std::move(summary); + api_handler_->CallSummarizeAPI( + (*it)->content, + base::BindOnce(&BraveCustomNotesPageHandler::OnSummarizeComplete, + weak_ptr_factory_.GetWeakPtr(), note_id)); } else { - LOG(WARNING) << "Failed to find note with ID: " << note_id; + LOG(WARNING) << "Note ID not found for summarize: " << note_id; std::move(callback).Run(false, "Note not found"); } } -// Inside the RephraseNoteContent function + void BraveCustomNotesPageHandler::RephraseNoteContent( int32_t note_id, RephraseNoteContentCallback callback) { auto it = std::find_if(notes_.begin(), notes_.end(), - [note_id](const auto& note) { return note->id == note_id; }); + [note_id](const auto& note) { return note->id == note_id; }); if (it != notes_.end()) { - // Log the start of the rephrasing process - LOG(INFO) << "Starting to rephrase note with ID: " << note_id; - - // Store the callback for later use + LOG(INFO) << "Starting async rephrase for note ID: " << note_id; pending_rephrase_callbacks_[note_id] = std::move(callback); - - // Create a string to store the rephrased content - auto rephrased = std::make_unique(); - - // Create a helper to handle the API callback - auto helper = std::make_unique( - weak_ptr_factory_.GetWeakPtr(), note_id); - - // Log the note content being passed to the rephrasing API - LOG(INFO) << "Note content being rephrased: " << (*it)->content; - - // Call the API with the note content - api_handler_->CallRephraseAPI((*it)->content, rephrased.get()); - - // Store the output string - pending_rephrased_[note_id] = std::move(rephrased); + + api_handler_->CallRephraseAPI( + (*it)->content, + base::BindOnce(&BraveCustomNotesPageHandler::OnRephraseComplete, + weak_ptr_factory_.GetWeakPtr(), note_id)); } else { - LOG(WARNING) << "Failed to find note with ID: " << note_id; + LOG(WARNING) << "Note ID not found for rephrase: " << note_id; std::move(callback).Run(false, "Note not found"); } } -// Inside the OnSummarizeComplete function +std::optional BraveCustomNotesPageHandler::ExtractContentFromJson( + const std::string& json_response) { + // Parse the JSON response + absl::optional parsed_json = base::JSONReader::Read(json_response); + if (!parsed_json || !parsed_json->is_dict()) { + LOG(ERROR) << "Failed to parse JSON or response is not a dictionary."; + return std::nullopt; + } + + const base::Value::Dict& json_dict = parsed_json->GetDict(); + const base::Value::List* choices = json_dict.FindList("choices"); + + if (!choices || choices->empty()) { + LOG(ERROR) << "No choices field found or it is empty."; + return std::nullopt; + } + + const base::Value::Dict* first_choice = (*choices)[0].GetIfDict(); + if (!first_choice) { + LOG(ERROR) << "First choice is not a dictionary."; + return std::nullopt; + } + + const base::Value::Dict* message = first_choice->FindDict("message"); + if (!message) { + LOG(ERROR) << "No message field found in the first choice."; + return std::nullopt; + } + + const std::string* content = message->FindString("content"); + if (!content) { + LOG(ERROR) << "No content field found in the message."; + return std::nullopt; + } + + return *content; +} + void BraveCustomNotesPageHandler::OnSummarizeComplete( - int32_t note_id, - const std::string& summary) { + int32_t note_id, const std::string& json_response) { + LOG(INFO) << "Raw JSON response for Summarizer: " << json_response; + + std::optional content = ExtractContentFromJson(json_response); + auto callback_it = pending_summarize_callbacks_.find(note_id); - auto summary_it = pending_summaries_.find(note_id); - - if (callback_it != pending_summarize_callbacks_.end() && - summary_it != pending_summaries_.end()) { - // Log the completion of the summarization process - LOG(INFO) << "Summarization complete for note with ID: " << note_id; - LOG(INFO) << "Summary: " << summary; - - std::move(callback_it->second).Run(true, summary); + if (callback_it != pending_summarize_callbacks_.end()) { + std::move(callback_it->second).Run(content.has_value(), content.value_or("")); pending_summarize_callbacks_.erase(callback_it); - pending_summaries_.erase(summary_it); } else { - LOG(WARNING) << "Summarization callback or summary not found for note with ID: " << note_id; + LOG(WARNING) << "No pending summarize callback for note ID: " << note_id; } } -// Inside the OnRephraseComplete function void BraveCustomNotesPageHandler::OnRephraseComplete( - int32_t note_id, - const std::string& rephrased) { + int32_t note_id, const std::string& json_response) { + LOG(INFO) << "Raw JSON response for Rephraser: " << json_response; + + std::optional content = ExtractContentFromJson(json_response); + auto callback_it = pending_rephrase_callbacks_.find(note_id); - auto rephrased_it = pending_rephrased_.find(note_id); - - if (callback_it != pending_rephrase_callbacks_.end() && - rephrased_it != pending_rephrased_.end()) { - // Log the completion of the rephrasing process - LOG(INFO) << "Rephrasing complete for note with ID: " << note_id; - LOG(INFO) << "Rephrased content: " << rephrased; - - std::move(callback_it->second).Run(true, rephrased); + if (callback_it != pending_rephrase_callbacks_.end()) { + std::move(callback_it->second).Run(content.has_value(), content.value_or("")); pending_rephrase_callbacks_.erase(callback_it); - pending_rephrased_.erase(rephrased_it); } else { - LOG(WARNING) << "Rephrasing callback or rephrased content not found for note with ID: " << note_id; + LOG(WARNING) << "No pending rephrase callback for note ID: " << note_id; } } diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h index 9891277ded41..437c69a943f0 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h @@ -59,6 +59,7 @@ class BraveCustomNotesPageHandler SummarizeNoteContentCallback callback) override; void RephraseNoteContent(int32_t note_id, RephraseNoteContentCallback callback) override; + std::optional ExtractContentFromJson(const std::string& json_response); private: class APICallbackHelper; From f17c3b0d538bcd5aaf549b787a3e47fdbfe91933 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Sat, 16 Nov 2024 23:23:40 +0530 Subject: [PATCH 16/21] improved code quality --- .../brave_custom_notes_api_handler.cc | 5 + .../brave_custom_notes_handler.cc | 127 ++++++++---------- .../brave_custom_notes_handler.h | 3 - 3 files changed, 64 insertions(+), 71 deletions(-) diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc index 91683dabc16f..890361a30400 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_api_handler.cc @@ -69,6 +69,10 @@ std::unique_ptr CreateLoader( std::move(resource_request), kTrafficAnnotation); + // Set timeout duration + constexpr base::TimeDelta kRequestTimeout = base::Seconds(60); + loader->SetTimeoutDuration(kRequestTimeout); + // Building JSON body for the request base::Value::Dict system_message; if (mode == "summarize") { @@ -111,6 +115,7 @@ std::unique_ptr CreateLoader( return loader; } + } // namespace diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc index db2359d0c30a..5a28316cc24b 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc @@ -30,6 +30,7 @@ namespace { const char kCustomNotesKey[] = "custom_notes"; } // namespace +// Helper class for handling API Callbacks class BraveCustomNotesPageHandler::APICallbackHelper { public: explicit APICallbackHelper(base::WeakPtr handler, @@ -37,21 +38,12 @@ class BraveCustomNotesPageHandler::APICallbackHelper { : handler_(handler), note_id_(note_id) {} - void OnSummarizeComplete(const std::string& summary) { - if (handler_) - handler_->OnSummarizeComplete(note_id_, summary); - } - - void OnRephraseComplete(const std::string& rephrased) { - if (handler_) - handler_->OnRephraseComplete(note_id_, rephrased); - } - private: base::WeakPtr handler_; int32_t note_id_; }; +// Constructor for initialising dependencies and loading notes from preferences BraveCustomNotesPageHandler::BraveCustomNotesPageHandler( Profile* profile, content::WebContents* web_contents, @@ -62,11 +54,12 @@ BraveCustomNotesPageHandler::BraveCustomNotesPageHandler( receiver_(this, std::move(receiver)), api_handler_(std::make_unique(url_loader_factory)), weak_ptr_factory_(this) { - LoadNotesFromPrefs(); + LoadNotesFromPrefs(); // Loads existing notes at startup time } BraveCustomNotesPageHandler::~BraveCustomNotesPageHandler() = default; +// Setting up the communication with the client page void BraveCustomNotesPageHandler::SetClientPage( mojo::PendingRemote page) { page_.Bind(std::move(page)); @@ -83,6 +76,7 @@ void BraveCustomNotesPageHandler::CreateNote(const std::string& title, notes_.push_back(std::move(new_note)); SaveNotesToPrefs(); + // Notifies client of success std::move(callback).Run(true); if (page_) { @@ -128,45 +122,6 @@ void BraveCustomNotesPageHandler::EditNote(int32_t note_id, } } -void BraveCustomNotesPageHandler::SummarizeNoteContent( - int32_t note_id, SummarizeNoteContentCallback callback) { - auto it = std::find_if(notes_.begin(), notes_.end(), - [note_id](const auto& note) { return note->id == note_id; }); - - if (it != notes_.end()) { - LOG(INFO) << "Starting async summarize for note ID: " << note_id; - pending_summarize_callbacks_[note_id] = std::move(callback); - - api_handler_->CallSummarizeAPI( - (*it)->content, - base::BindOnce(&BraveCustomNotesPageHandler::OnSummarizeComplete, - weak_ptr_factory_.GetWeakPtr(), note_id)); - } else { - LOG(WARNING) << "Note ID not found for summarize: " << note_id; - std::move(callback).Run(false, "Note not found"); - } -} - - -void BraveCustomNotesPageHandler::RephraseNoteContent( - int32_t note_id, RephraseNoteContentCallback callback) { - auto it = std::find_if(notes_.begin(), notes_.end(), - [note_id](const auto& note) { return note->id == note_id; }); - - if (it != notes_.end()) { - LOG(INFO) << "Starting async rephrase for note ID: " << note_id; - pending_rephrase_callbacks_[note_id] = std::move(callback); - - api_handler_->CallRephraseAPI( - (*it)->content, - base::BindOnce(&BraveCustomNotesPageHandler::OnRephraseComplete, - weak_ptr_factory_.GetWeakPtr(), note_id)); - } else { - LOG(WARNING) << "Note ID not found for rephrase: " << note_id; - std::move(callback).Run(false, "Note not found"); - } -} - std::optional BraveCustomNotesPageHandler::ExtractContentFromJson( const std::string& json_response) { // Parse the JSON response @@ -205,33 +160,69 @@ std::optional BraveCustomNotesPageHandler::ExtractContentFromJson( return *content; } -void BraveCustomNotesPageHandler::OnSummarizeComplete( - int32_t note_id, const std::string& json_response) { - LOG(INFO) << "Raw JSON response for Summarizer: " << json_response; +void BraveCustomNotesPageHandler::SummarizeNoteContent( + int32_t note_id, SummarizeNoteContentCallback callback) { + auto it = std::find_if(notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); - std::optional content = ExtractContentFromJson(json_response); + if (it != notes_.end()) { + LOG(INFO) << "Starting async summarize for note ID: " << note_id; - auto callback_it = pending_summarize_callbacks_.find(note_id); - if (callback_it != pending_summarize_callbacks_.end()) { - std::move(callback_it->second).Run(content.has_value(), content.value_or("")); - pending_summarize_callbacks_.erase(callback_it); + api_handler_->CallSummarizeAPI( + (*it)->content, + base::BindOnce( + [](int32_t note_id, + SummarizeNoteContentCallback callback, + BraveCustomNotesPageHandler* handler, + const std::string& json_response) { + LOG(INFO) << "Raw JSON response for Summarizer: " << json_response; + + std::optional content = handler->ExtractContentFromJson(json_response); + + if (content) { + std::move(callback).Run(true, *content); + } else { + LOG(WARNING) << "Summarization failed for note ID: " << note_id; + std::move(callback).Run(false, "Failed to extract summary"); + } + }, + note_id, std::move(callback), this)); } else { - LOG(WARNING) << "No pending summarize callback for note ID: " << note_id; + LOG(WARNING) << "Note ID not found for summarize: " << note_id; + std::move(callback).Run(false, "Note not found"); } } -void BraveCustomNotesPageHandler::OnRephraseComplete( - int32_t note_id, const std::string& json_response) { - LOG(INFO) << "Raw JSON response for Rephraser: " << json_response; +void BraveCustomNotesPageHandler::RephraseNoteContent( + int32_t note_id, RephraseNoteContentCallback callback) { + auto it = std::find_if(notes_.begin(), notes_.end(), + [note_id](const auto& note) { return note->id == note_id; }); - std::optional content = ExtractContentFromJson(json_response); + if (it != notes_.end()) { + LOG(INFO) << "Starting async rephrase for note ID: " << note_id; - auto callback_it = pending_rephrase_callbacks_.find(note_id); - if (callback_it != pending_rephrase_callbacks_.end()) { - std::move(callback_it->second).Run(content.has_value(), content.value_or("")); - pending_rephrase_callbacks_.erase(callback_it); + api_handler_->CallRephraseAPI( + (*it)->content, + base::BindOnce( + [](int32_t note_id, + RephraseNoteContentCallback callback, + BraveCustomNotesPageHandler* handler, + const std::string& json_response) { + LOG(INFO) << "Raw JSON response for Rephraser: " << json_response; + + std::optional content = handler->ExtractContentFromJson(json_response); + + if (content) { + std::move(callback).Run(true, *content); + } else { + LOG(WARNING) << "Rephrasing failed for note ID: " << note_id; + std::move(callback).Run(false, "Failed to extract rephrased content"); + } + }, + note_id, std::move(callback), this)); } else { - LOG(WARNING) << "No pending rephrase callback for note ID: " << note_id; + LOG(WARNING) << "Note ID not found for rephrase: " << note_id; + std::move(callback).Run(false, "Note not found"); } } diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h index 437c69a943f0..2314880bbffa 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.h @@ -67,9 +67,6 @@ class BraveCustomNotesPageHandler void LoadNotesFromPrefs(); void SaveNotesToPrefs(); void UpdatePageWithNotes(); - - void OnSummarizeComplete(int32_t note_id, const std::string& summary); - void OnRephraseComplete(int32_t note_id, const std::string& rephrased); raw_ptr profile_; raw_ptr web_contents_; From 1999dc0c4055362aad0a1bd1230621c1960ce934 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Thu, 28 Nov 2024 17:39:56 +0530 Subject: [PATCH 17/21] api call from internal page using javascript working --- .../resources/page/container.tsx | 89 ++++++++++++------- 1 file changed, 57 insertions(+), 32 deletions(-) diff --git a/components/brave_custom_notes/resources/page/container.tsx b/components/brave_custom_notes/resources/page/container.tsx index 53fea58dd011..121d268abd38 100644 --- a/components/brave_custom_notes/resources/page/container.tsx +++ b/components/brave_custom_notes/resources/page/container.tsx @@ -75,6 +75,9 @@ interface Note { timestamp: number; } +const AZURE_OPENAI_API_ENDPOINT = 'https://ping.openai.azure.com/openai/deployments/ai-summariser-gpt-35-turbo/chat/completions?api-version=2024-02-15-preview'; +const AZURE_OPENAI_API_KEY = 'b487c4dc0bc1490e801cb6220cf04039'; + const Notes: React.FC = () => { const [note, setNote] = useState(''); const [notesList, setNotesList] = useState([]); @@ -187,46 +190,68 @@ const Notes: React.FC = () => { }); }; - // Rephrase the currently typed note - const handleRephraseNote = () => { + const handleRephraseNote = async () => { if (!note.trim()) { alert('Please enter some text to rephrase.'); return; } setIsLoading(true); - // If editing a note, use its ID, otherwise use a temporary ID - const noteId = editingNote ? editingNote.id : -1; - customNotesAPI.pageHandler.rephraseNoteContent(noteId) - .then((response: { success: boolean, rephrased_content: string }) => { - if (response.success) { - if (editingNote) { - // If editing an existing note, update it in the list - setNotesList(prevNotes => - prevNotes.map(note => - note.id === editingNote.id - ? { - ...note, - content: response.rephrased_content - } - : note - ) - ); - } - // Update the note input field - setNote(response.rephrased_content); - } else { - alert('Failed to rephrase note. Please try again.'); + try { + const response = await fetch( + AZURE_OPENAI_API_ENDPOINT, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'api-key': AZURE_OPENAI_API_KEY + }, + body: JSON.stringify({ + messages: [ + { + role: 'system', + content: 'You are a helpful assistant that rephrases text while maintaining its original meaning.' + }, + { + role: 'user', + content: `Rephrase the following text: ${note}` + } + ], + max_tokens: 500, + temperature: 0.7, + top_p: 0.95, + frequency_penalty: 0, + presence_penalty: 0, + stream: false + }) } - }) - .catch((err: Error) => { - console.error(err); - alert('Failed to rephrase note. Please try again.'); - }) - .finally(() => { - setIsLoading(false); - }); + ); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + const data = await response.json(); + const rephrasedContent = data.choices[0].message.content.trim(); + if (editingNote) { + setNotesList(prevNotes => + prevNotes.map(note => + note.id === editingNote.id + ? { + ...note, + content: rephrasedContent + } + : note + ) + ); + } + setNote(rephrasedContent); + } catch (error) { + console.error('Rephrasing failed:', error); + alert('Failed to rephrase note. Please try again.'); + } finally { + setIsLoading(false); + } }; return ( From b471feb8e9cb1edfcaf4f4d3b7de9f1f723cb6f9 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Sat, 30 Nov 2024 18:52:38 +0530 Subject: [PATCH 18/21] override function for iswebuiallowedtomakenetworkrequests --- browser/ui/webui/brave_web_ui_controller_factory.cc | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/browser/ui/webui/brave_web_ui_controller_factory.cc b/browser/ui/webui/brave_web_ui_controller_factory.cc index d7778afea9f6..8c0884ea2047 100644 --- a/browser/ui/webui/brave_web_ui_controller_factory.cc +++ b/browser/ui/webui/brave_web_ui_controller_factory.cc @@ -271,6 +271,16 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return nullptr; } +bool ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests( + const GURL& url) { + std::string host = url.host_piece(); + if (host == kBraveCustomNotesHost) { + return true; + } + return ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests(url); +} + + bool ShouldBlockRewardsWebUI(content::BrowserContext* browser_context, const GURL& url) { if (url.host_piece() != kRewardsPageHost && From c27c74a0cc1a24aaa47b69bd73f9e02f8ca7b81f Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Sun, 29 Dec 2024 23:35:57 +0530 Subject: [PATCH 19/21] fix: merge conflict in resources mapping --- resources/resource_ids.spec | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/resources/resource_ids.spec b/resources/resource_ids.spec index f4e896951e51..eb905237e72c 100644 --- a/resources/resource_ids.spec +++ b/resources/resource_ids.spec @@ -233,13 +233,10 @@ "includes": [64550], }, "brave/components/ping_ai_copilot/resources.grd": { - "includes": [63100], + "includes": [64600], }, - # This file is generated during the build. "<(SHARED_INTERMEDIATE_DIR)/brave/web-ui-brave_custom_notes/brave_custom_notes.grd": { "META": {"sizes": {"includes": [10]}}, - "includes": [63200], - }, - "includes": [64600], + "includes": [64620] } } From 8efa9ca05267f255debeb51fce214b649af53496 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Mon, 30 Dec 2024 13:08:05 +0530 Subject: [PATCH 20/21] sync: migrating webui_url_constants --- chromium_src/chrome/common/webui_url_constants.cc | 9 --------- 1 file changed, 9 deletions(-) diff --git a/chromium_src/chrome/common/webui_url_constants.cc b/chromium_src/chrome/common/webui_url_constants.cc index 13a7cebf50e6..da853f0af490 100644 --- a/chromium_src/chrome/common/webui_url_constants.cc +++ b/chromium_src/chrome/common/webui_url_constants.cc @@ -4,22 +4,13 @@ * You can obtain one at https://mozilla.org/MPL/2.0/. */ #include "brave/components/constants/webui_url_constants.h" - -#include "brave/components/ipfs/buildflags/buildflags.h" #include "chrome/common/webui_url_constants.h" #define kChromeUIAttributionInternalsHost \ kChromeUIAttributionInternalsHost, kAdblockHost, kAdblockInternalsHost, \ kRewardsPageHost, kRewardsInternalsHost, kWelcomeHost, kWalletPageHost, \ kTorInternalsHost, kSkusInternalsHost, kBraveCustomNotesHost -#define kPerformanceSubPage kPerformanceSubPage_UnUsed - -#if BUILDFLAG(ENABLE_IPFS_INTERNALS_WEBUI) -#define kChromeUIBlobInternalsHost kChromeUIBlobInternalsHost, kIPFSWebUIHost -#endif - kTorInternalsHost, kSkusInternalsHost #include "src/chrome/common/webui_url_constants.cc" #undef kChromeUIAttributionInternalsHost - From 415e9d95722631f0254ff510a281f03cf15b24c9 Mon Sep 17 00:00:00 2001 From: MasterK0927 Date: Mon, 30 Dec 2024 16:01:01 +0530 Subject: [PATCH 21/21] fix: 130 sync is now fully merged, with all the features working --- .../ui/views/toolbar/brave_toolbar_view.cc | 5 -- .../brave_custom_notes_handler.cc | 2 +- .../webui/brave_web_ui_controller_factory.cc | 82 +++++++++---------- 3 files changed, 41 insertions(+), 48 deletions(-) diff --git a/browser/ui/views/toolbar/brave_toolbar_view.cc b/browser/ui/views/toolbar/brave_toolbar_view.cc index 664df46bbbe7..a4f1a30ecf0a 100644 --- a/browser/ui/views/toolbar/brave_toolbar_view.cc +++ b/browser/ui/views/toolbar/brave_toolbar_view.cc @@ -383,11 +383,6 @@ views::View* BraveToolbarView::GetAnchorView( return ToolbarView::GetAnchorView(type); } -views::View* BraveToolbarView::GetAnchorView( - std::optional type) { - return ToolbarView::GetAnchorView(type); -} - void BraveToolbarView::OnProfileAdded(const base::FilePath& profile_path) { Update(nullptr); } diff --git a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc index 5a28316cc24b..b7a9476d8435 100644 --- a/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc +++ b/browser/ui/webui/brave_custom_notes/brave_custom_notes_handler.cc @@ -125,7 +125,7 @@ void BraveCustomNotesPageHandler::EditNote(int32_t note_id, std::optional BraveCustomNotesPageHandler::ExtractContentFromJson( const std::string& json_response) { // Parse the JSON response - absl::optional parsed_json = base::JSONReader::Read(json_response); + std::optional parsed_json = base::JSONReader::Read(json_response); if (!parsed_json || !parsed_json->is_dict()) { LOG(ERROR) << "Failed to parse JSON or response is not a dictionary."; return std::nullopt; diff --git a/browser/ui/webui/brave_web_ui_controller_factory.cc b/browser/ui/webui/brave_web_ui_controller_factory.cc index 912892c58b8d..c9a4bf463a96 100644 --- a/browser/ui/webui/brave_web_ui_controller_factory.cc +++ b/browser/ui/webui/brave_web_ui_controller_factory.cc @@ -30,6 +30,7 @@ #include "brave/components/playlist/common/buildflags/buildflags.h" #include "brave/components/skus/common/features.h" #include "brave/components/tor/buildflags/buildflags.h" +#include "brave_web_ui_controller_factory.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" @@ -93,15 +94,12 @@ WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { auto host = url.host_piece(); Profile* profile = Profile::FromBrowserContext( web_ui->GetWebContents()->GetBrowserContext()); - if (host == kAdblockHost) { - return new BraveAdblockUI(web_ui, url.host()); - } else if (host == kAdblockInternalsHost) { - return new BraveAdblockInternalsUI(web_ui, url.host()); - } else if (host == kBraveCustomNotesHost) { - return new BraveCustomNotesUI(web_ui, url.host()); - } else if (host == kSkusInternalsHost) { if (host == kSkusInternalsHost) { return new SkusInternalsUI(web_ui, url.host()); + } else if (host == kBraveCustomNotesHost) { + return new BraveCustomNotesUI(web_ui, url.host()); + } else if (host == kSkusInternalsHost) { + return new SkusInternalsUI(web_ui, url.host()); #if !BUILDFLAG(IS_ANDROID) } else if (host == kWalletPageHost && brave_wallet::IsAllowedForContext(profile)) { @@ -219,44 +217,44 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return nullptr; } -bool ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests( - const GURL& url) { - std::string host = url.host_piece(); - if (host == kBraveCustomNotesHost) { - return true; - } - return ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests(url); -} +// bool ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests( +// const url::Origin& url) { +// std::string host = url.host_piece(); +// if (host == kBraveCustomNotesHost) { +// return true; +// } +// return ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests(url); +// } -bool ShouldBlockRewardsWebUI(content::BrowserContext* browser_context, - const GURL& url) { - if (url.host_piece() != kRewardsPageHost && -#if !BUILDFLAG(IS_ANDROID) - url.host_piece() != kBraveRewardsPanelHost && - url.host_piece() != kBraveTipPanelHost && -#endif // !BUILDFLAG(IS_ANDROID) - url.host_piece() != kRewardsInternalsHost) { - return false; - } +// bool ShouldBlockRewardsWebUI(content::BrowserContext* browser_context, +// const GURL& url) { +// if (url.host_piece() != kRewardsPageHost && +// #if !BUILDFLAG(IS_ANDROID) +// url.host_piece() != kBraveRewardsPanelHost && +// url.host_piece() != kBraveTipPanelHost && +// #endif // !BUILDFLAG(IS_ANDROID) +// url.host_piece() != kRewardsInternalsHost) { +// return false; +// } - Profile* profile = Profile::FromBrowserContext(browser_context); - if (profile) { - if (!brave_rewards::IsSupportedForProfile( - profile, url.host_piece() == kRewardsPageHost - ? brave_rewards::IsSupportedOptions::kSkipRegionCheck - : brave_rewards::IsSupportedOptions::kNone)) { - return true; - } -#if BUILDFLAG(IS_ANDROID) - auto* prefs = profile->GetPrefs(); - if (prefs && prefs->GetBoolean(kSafetynetCheckFailed)) { - return true; - } -#endif // BUILDFLAG(IS_ANDROID) - } - return false; -} +// Profile* profile = Profile::FromBrowserContext(browser_context); +// if (profile) { +// if (!brave_rewards::IsSupportedForProfile( +// profile, url.host_piece() == kRewardsPageHost +// ? brave_rewards::IsSupportedOptions::kSkipRegionCheck +// : brave_rewards::IsSupportedOptions::kNone)) { +// return true; +// } +// #if BUILDFLAG(IS_ANDROID) +// auto* prefs = profile->GetPrefs(); +// if (prefs && prefs->GetBoolean(kSafetynetCheckFailed)) { +// return true; +// } +// #endif // BUILDFLAG(IS_ANDROID) +// } +// return false; +// } #if BUILDFLAG(IS_ANDROID) bool ShouldBlockWalletWebUI(content::BrowserContext* browser_context,