TraversableNavigable.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibWeb/Bindings/MainThreadVM.h>
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/HTML/BrowsingContextGroup.h>
  10. #include <LibWeb/HTML/DocumentState.h>
  11. #include <LibWeb/HTML/Navigation.h>
  12. #include <LibWeb/HTML/NavigationParams.h>
  13. #include <LibWeb/HTML/Parser/HTMLParser.h>
  14. #include <LibWeb/HTML/SessionHistoryEntry.h>
  15. #include <LibWeb/HTML/TraversableNavigable.h>
  16. #include <LibWeb/HTML/Window.h>
  17. #include <LibWeb/Page/Page.h>
  18. #include <LibWeb/Platform/EventLoopPlugin.h>
  19. namespace Web::HTML {
  20. JS_DEFINE_ALLOCATOR(TraversableNavigable);
  21. TraversableNavigable::TraversableNavigable(JS::NonnullGCPtr<Page> page)
  22. : m_session_history_traversal_queue(vm().heap().allocate_without_realm<SessionHistoryTraversalQueue>())
  23. , m_page(page)
  24. {
  25. }
  26. TraversableNavigable::~TraversableNavigable() = default;
  27. void TraversableNavigable::visit_edges(Cell::Visitor& visitor)
  28. {
  29. Base::visit_edges(visitor);
  30. visitor.visit(m_page);
  31. for (auto& entry : m_session_history_entries)
  32. visitor.visit(entry);
  33. visitor.visit(m_session_history_traversal_queue);
  34. }
  35. static OrderedHashTable<TraversableNavigable*>& user_agent_top_level_traversable_set()
  36. {
  37. static OrderedHashTable<TraversableNavigable*> set;
  38. return set;
  39. }
  40. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-browsing-context
  41. WebIDL::ExceptionOr<BrowsingContextAndDocument> create_a_new_top_level_browsing_context_and_document(JS::NonnullGCPtr<Page> page)
  42. {
  43. // 1. Let group and document be the result of creating a new browsing context group and document.
  44. auto [group, document] = TRY(BrowsingContextGroup::create_a_new_browsing_context_group_and_document(page));
  45. // 2. Return group's browsing context set[0] and document.
  46. return BrowsingContextAndDocument { **group->browsing_context_set().begin(), document };
  47. }
  48. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-traversable
  49. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_new_top_level_traversable(JS::NonnullGCPtr<Page> page, JS::GCPtr<HTML::BrowsingContext> opener, String target_name)
  50. {
  51. auto& vm = Bindings::main_thread_vm();
  52. // 1. Let document be null.
  53. JS::GCPtr<DOM::Document> document = nullptr;
  54. // 2. If opener is null, then set document to the second return value of creating a new top-level browsing context and document.
  55. if (!opener) {
  56. document = TRY(create_a_new_top_level_browsing_context_and_document(page)).document;
  57. }
  58. // 3. Otherwise, set document to the second return value of creating a new auxiliary browsing context and document given opener.
  59. else {
  60. document = TRY(BrowsingContext::create_a_new_auxiliary_browsing_context_and_document(page, *opener)).document;
  61. }
  62. // 4. Let documentState be a new document state, with
  63. auto document_state = vm.heap().allocate_without_realm<DocumentState>();
  64. // document: document
  65. document_state->set_document(document);
  66. // initiator origin: null if opener is null; otherwise, document's origin
  67. document_state->set_initiator_origin(opener ? Optional<Origin> {} : document->origin());
  68. // origin: document's origin
  69. document_state->set_origin(document->origin());
  70. // navigable target name: targetName
  71. document_state->set_navigable_target_name(target_name);
  72. // about base URL: document's about base URL
  73. document_state->set_about_base_url(document->about_base_url());
  74. // 5. Let traversable be a new traversable navigable.
  75. auto traversable = vm.heap().allocate_without_realm<TraversableNavigable>(page);
  76. // 6. Initialize the navigable traversable given documentState.
  77. TRY_OR_THROW_OOM(vm, traversable->initialize_navigable(document_state, nullptr));
  78. // 7. Let initialHistoryEntry be traversable's active session history entry.
  79. auto initial_history_entry = traversable->active_session_history_entry();
  80. VERIFY(initial_history_entry);
  81. // 8. Set initialHistoryEntry's step to 0.
  82. initial_history_entry->set_step(0);
  83. // 9. Append initialHistoryEntry to traversable's session history entries.
  84. traversable->m_session_history_entries.append(*initial_history_entry);
  85. // FIXME: 10. If opener is non-null, then legacy-clone a traversable storage shed given opener's top-level traversable and traversable. [STORAGE]
  86. // 11. Append traversable to the user agent's top-level traversable set.
  87. user_agent_top_level_traversable_set().set(traversable);
  88. // 12. Return traversable.
  89. return traversable;
  90. }
  91. // https://html.spec.whatwg.org/multipage/document-sequences.html#create-a-fresh-top-level-traversable
  92. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_fresh_top_level_traversable(JS::NonnullGCPtr<Page> page, URL::URL const& initial_navigation_url, Variant<Empty, String, POSTResource> initial_navigation_post_resource)
  93. {
  94. // 1. Let traversable be the result of creating a new top-level traversable given null and the empty string.
  95. auto traversable = TRY(create_a_new_top_level_traversable(page, nullptr, {}));
  96. page->set_top_level_traversable(traversable);
  97. // AD-HOC: Mark the about:blank document as finished parsing if we're only going to about:blank
  98. // Skip the initial navigation as well. This matches the behavior of the window open steps.
  99. if (url_matches_about_blank(initial_navigation_url)) {
  100. Platform::EventLoopPlugin::the().deferred_invoke([traversable, initial_navigation_url] {
  101. // FIXME: We do this other places too when creating a new about:blank document. Perhaps it's worth a spec issue?
  102. HTML::HTMLParser::the_end(*traversable->active_document());
  103. // FIXME: If we perform the URL and history update steps here, we start hanging tests and the UI process will
  104. // try to load() the initial URLs passed on the command line before we finish processing the events here.
  105. // However, because we call this before the PageClient is fully initialized... that gets awkward.
  106. });
  107. }
  108. else {
  109. // 2. Navigate traversable to initialNavigationURL using traversable's active document, with documentResource set to initialNavigationPostResource.
  110. TRY(traversable->navigate({ .url = initial_navigation_url,
  111. .source_document = *traversable->active_document(),
  112. .document_resource = initial_navigation_post_resource }));
  113. }
  114. // 3. Return traversable.
  115. return traversable;
  116. }
  117. // https://html.spec.whatwg.org/multipage/document-sequences.html#top-level-traversable
  118. bool TraversableNavigable::is_top_level_traversable() const
  119. {
  120. // A top-level traversable is a traversable navigable with a null parent.
  121. return parent() == nullptr;
  122. }
  123. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-used-history-steps
  124. Vector<int> TraversableNavigable::get_all_used_history_steps() const
  125. {
  126. // FIXME: 1. Assert: this is running within traversable's session history traversal queue.
  127. // 2. Let steps be an empty ordered set of non-negative integers.
  128. OrderedHashTable<int> steps;
  129. // 3. Let entryLists be the ordered set « traversable's session history entries ».
  130. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>> entry_lists { session_history_entries() };
  131. // 4. For each entryList of entryLists:
  132. while (!entry_lists.is_empty()) {
  133. auto entry_list = entry_lists.take_first();
  134. // 1. For each entry of entryList:
  135. for (auto& entry : entry_list) {
  136. // 1. Append entry's step to steps.
  137. steps.set(entry->step().get<int>());
  138. // 2. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  139. for (auto& nested_history : entry->document_state()->nested_histories())
  140. entry_lists.append(nested_history.entries);
  141. }
  142. }
  143. // 5. Return steps, sorted.
  144. auto sorted_steps = steps.values();
  145. quick_sort(sorted_steps);
  146. return sorted_steps;
  147. }
  148. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-history-object-length-and-index
  149. TraversableNavigable::HistoryObjectLengthAndIndex TraversableNavigable::get_the_history_object_length_and_index(int step) const
  150. {
  151. // 1. Let steps be the result of getting all used history steps within traversable.
  152. auto steps = get_all_used_history_steps();
  153. // 2. Let scriptHistoryLength be the size of steps.
  154. auto script_history_length = steps.size();
  155. // 3. Assert: steps contains step.
  156. VERIFY(steps.contains_slow(step));
  157. // 4. Let scriptHistoryIndex be the index of step in steps.
  158. auto script_history_index = *steps.find_first_index(step);
  159. // 5. Return (scriptHistoryLength, scriptHistoryIndex).
  160. return HistoryObjectLengthAndIndex {
  161. .script_history_length = script_history_length,
  162. .script_history_index = script_history_index
  163. };
  164. }
  165. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-used-step
  166. int TraversableNavigable::get_the_used_step(int step) const
  167. {
  168. // 1. Let steps be the result of getting all used history steps within traversable.
  169. auto steps = get_all_used_history_steps();
  170. // 2. Return the greatest item in steps that is less than or equal to step.
  171. VERIFY(!steps.is_empty());
  172. Optional<int> result;
  173. for (size_t i = 0; i < steps.size(); i++) {
  174. if (steps[i] <= step) {
  175. if (!result.has_value() || (result.value() < steps[i])) {
  176. result = steps[i];
  177. }
  178. }
  179. }
  180. return result.value();
  181. }
  182. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#get-all-navigables-whose-current-session-history-entry-will-change-or-reload
  183. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_whose_current_session_history_entry_will_change_or_reload(int target_step) const
  184. {
  185. // 1. Let results be an empty list.
  186. Vector<JS::Handle<Navigable>> results;
  187. // 2. Let navigablesToCheck be « traversable ».
  188. Vector<JS::Handle<Navigable>> navigables_to_check;
  189. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  190. // 3. For each navigable of navigablesToCheck:
  191. while (!navigables_to_check.is_empty()) {
  192. auto navigable = navigables_to_check.take_first();
  193. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  194. auto target_entry = navigable->get_the_target_history_entry(target_step);
  195. // 2. If targetEntry is not navigable's current session history entry or targetEntry's document state's reload pending is true, then append navigable to results.
  196. if (target_entry != navigable->current_session_history_entry() || target_entry->document_state()->reload_pending()) {
  197. results.append(*navigable);
  198. }
  199. // 3. If targetEntry's document is navigable's document, and targetEntry's document state's reload pending is false, then extend navigablesToCheck with the child navigables of navigable.
  200. if (target_entry->document() == navigable->active_document() && !target_entry->document_state()->reload_pending()) {
  201. navigables_to_check.extend(navigable->child_navigables());
  202. }
  203. }
  204. // 4. Return results.
  205. return results;
  206. }
  207. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-navigables-that-only-need-history-object-length/index-update
  208. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_that_only_need_history_object_length_index_update(int target_step) const
  209. {
  210. // NOTE: Other navigables might not be impacted by the traversal. For example, if the response is a 204, the currently active document will remain.
  211. // Additionally, going 'back' after a 204 will change the current session history entry, but the active session history entry will already be correct.
  212. // 1. Let results be an empty list.
  213. Vector<JS::Handle<Navigable>> results;
  214. // 2. Let navigablesToCheck be « traversable ».
  215. Vector<JS::Handle<Navigable>> navigables_to_check;
  216. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  217. // 3. For each navigable of navigablesToCheck:
  218. while (!navigables_to_check.is_empty()) {
  219. auto navigable = navigables_to_check.take_first();
  220. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  221. auto target_entry = navigable->get_the_target_history_entry(target_step);
  222. // 2. If targetEntry is navigable's current session history entry and targetEntry's document state's reload pending is false, then:
  223. if (target_entry == navigable->current_session_history_entry() && !target_entry->document_state()->reload_pending()) {
  224. // 1. Append navigable to results.
  225. results.append(navigable);
  226. // 2. Extend navigablesToCheck with navigable's child navigables.
  227. navigables_to_check.extend(navigable->child_navigables());
  228. }
  229. }
  230. // 4. Return results.
  231. return results;
  232. }
  233. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-navigables-that-might-experience-a-cross-document-traversal
  234. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_that_might_experience_a_cross_document_traversal(int target_step) const
  235. {
  236. // NOTE: From traversable's session history traversal queue's perspective, these documents are candidates for going cross-document during the
  237. // traversal described by targetStep. They will not experience a cross-document traversal if the status code for their target document is
  238. // HTTP 204 No Content.
  239. // Note that if a given navigable might experience a cross-document traversal, this algorithm will return navigable but not its child navigables.
  240. // Those would end up unloaded, not traversed.
  241. // 1. Let results be an empty list.
  242. Vector<JS::Handle<Navigable>> results;
  243. // 2. Let navigablesToCheck be « traversable ».
  244. Vector<JS::Handle<Navigable>> navigables_to_check;
  245. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  246. // 3. For each navigable of navigablesToCheck:
  247. while (!navigables_to_check.is_empty()) {
  248. auto navigable = navigables_to_check.take_first();
  249. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  250. auto target_entry = navigable->get_the_target_history_entry(target_step);
  251. // 2. If targetEntry's document is not navigable's document or targetEntry's document state's reload pending is true, then append navigable to results.
  252. // NOTE: Although navigable's active history entry can change synchronously, the new entry will always have the same Document,
  253. // so accessing navigable's document is reliable.
  254. if (target_entry->document() != navigable->active_document() || target_entry->document_state()->reload_pending()) {
  255. results.append(navigable);
  256. }
  257. // 3. Otherwise, extend navigablesToCheck with navigable's child navigables.
  258. // Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop.
  259. // Child navigables are only checked if the navigable's active document will not change as part of this traversal.
  260. else {
  261. navigables_to_check.extend(navigable->child_navigables());
  262. }
  263. }
  264. // 4. Return results.
  265. return results;
  266. }
  267. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#deactivate-a-document-for-a-cross-document-navigation
  268. static void deactivate_a_document_for_cross_document_navigation(JS::NonnullGCPtr<DOM::Document> displayed_document, Optional<UserNavigationInvolvement>, JS::NonnullGCPtr<SessionHistoryEntry> target_entry, JS::SafeFunction<void()> after_potential_unloads)
  269. {
  270. // 1. Let navigable be displayedDocument's node navigable.
  271. auto navigable = displayed_document->navigable();
  272. // 2. Let potentiallyTriggerViewTransition be false.
  273. auto potentially_trigger_view_transition = false;
  274. // FIXME: 3. Let isBrowserUINavigation be true if userNavigationInvolvement is "browser UI"; otherwise false.
  275. // FIXME: 4. Set potentiallyTriggerViewTransition to the result of calling can navigation trigger a cross-document
  276. // view-transition? given displayedDocument, targetEntry's document, navigationType, and isBrowserUINavigation.
  277. // 5. If potentiallyTriggerViewTransition is false, then:
  278. if (!potentially_trigger_view_transition) {
  279. // FIXME 1. Let firePageSwapBeforeUnload be the following step
  280. // 1. Fire the pageswap event given displayedDocument, targetEntry, navigationType, and null.
  281. // 2. Set the ongoing navigation for navigable to null.
  282. navigable->set_ongoing_navigation({});
  283. // 3. Unload a document and its descendants given displayedDocument, targetEntry's document, afterPotentialUnloads, and firePageSwapBeforeUnload.
  284. displayed_document->unload_a_document_and_its_descendants(target_entry->document(), move(after_potential_unloads));
  285. }
  286. // FIXME: 6. Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
  287. else {
  288. // FIXME: 1. Let proceedWithNavigationAfterViewTransitionCapture be the following step:
  289. // 1. Append the following session history traversal steps to navigable's traversable navigable:
  290. // 1. Set the ongoing navigation for navigable to null.
  291. // 2. Unload a document and its descendants given displayedDocument, targetEntry's document, and afterPotentialUnloads.
  292. // FIXME: 2. Let viewTransition be the result of setting up a cross-document view-transition given displayedDocument,
  293. // targetEntry's document, navigationType, and proceedWithNavigationAfterViewTransitionCapture.
  294. // FIXME: 3. Fire the pageswap event given displayedDocument, targetEntry, navigationType, and viewTransition.
  295. // FIXME: 4. If viewTransition is null, then run proceedWithNavigationAfterViewTransitionCapture.
  296. TODO();
  297. }
  298. }
  299. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-history-step
  300. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_history_step(
  301. int step,
  302. bool check_for_cancelation,
  303. IGNORE_USE_IN_ESCAPING_LAMBDA Optional<SourceSnapshotParams> source_snapshot_params,
  304. JS::GCPtr<Navigable> initiator_to_check,
  305. Optional<UserNavigationInvolvement> user_involvement_for_navigate_events,
  306. IGNORE_USE_IN_ESCAPING_LAMBDA Optional<Bindings::NavigationType> navigation_type,
  307. IGNORE_USE_IN_ESCAPING_LAMBDA SynchronousNavigation synchronous_navigation)
  308. {
  309. auto& vm = this->vm();
  310. // FIXME: 1. Assert: This is running within traversable's session history traversal queue.
  311. // 2. Let targetStep be the result of getting the used step given traversable and step.
  312. auto target_step = get_the_used_step(step);
  313. // Note: Calling this early so we can re-use the same list in 3.2 and 6.
  314. auto change_or_reload_navigables = get_all_navigables_whose_current_session_history_entry_will_change_or_reload(target_step);
  315. // 3. If initiatorToCheck is not null, then:
  316. if (initiator_to_check != nullptr) {
  317. // 1. Assert: sourceSnapshotParams is not null.
  318. VERIFY(source_snapshot_params.has_value());
  319. // 2. For each navigable of get all navigables whose current session history entry will change or reload:
  320. // if initiatorToCheck is not allowed by sandboxing to navigate navigable given sourceSnapshotParams, then return "initiator-disallowed".
  321. for (auto const& navigable : change_or_reload_navigables) {
  322. if (!initiator_to_check->allowed_by_sandboxing_to_navigate(*navigable, *source_snapshot_params))
  323. return HistoryStepResult::InitiatorDisallowed;
  324. }
  325. }
  326. // 4. Let navigablesCrossingDocuments be the result of getting all navigables that might experience a cross-document traversal given traversable and targetStep.
  327. [[maybe_unused]] auto navigables_crossing_documents = get_all_navigables_that_might_experience_a_cross_document_traversal(target_step);
  328. // 5. FIXME: If checkForCancelation is true, and the result of checking if unloading is canceled given navigablesCrossingDocuments, traversable, targetStep,
  329. // and userInvolvementForNavigateEvents is not "continue", then return that result.
  330. (void)check_for_cancelation;
  331. // 6. Let changingNavigables be the result of get all navigables whose current session history entry will change or reload given traversable and targetStep.
  332. auto changing_navigables = move(change_or_reload_navigables);
  333. // 7. Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need history object length/index update given traversable and targetStep.
  334. auto non_changing_navigables_that_still_need_updates = get_all_navigables_that_only_need_history_object_length_index_update(target_step);
  335. // 8. For each navigable of changingNavigables:
  336. for (auto& navigable : changing_navigables) {
  337. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  338. auto target_entry = navigable->get_the_target_history_entry(target_step);
  339. // 2. Set navigable's current session history entry to targetEntry.
  340. navigable->set_current_session_history_entry(target_entry);
  341. // 3. Set navigable's ongoing navigation to "traversal".
  342. navigable->set_ongoing_navigation(Traversal::Tag);
  343. }
  344. // 9. Let totalChangeJobs be the size of changingNavigables.
  345. auto total_change_jobs = changing_navigables.size();
  346. // 10. Let completedChangeJobs be 0.
  347. IGNORE_USE_IN_ESCAPING_LAMBDA size_t completed_change_jobs = 0;
  348. struct ChangingNavigableContinuationState {
  349. JS::Handle<DOM::Document> displayed_document;
  350. JS::Handle<SessionHistoryEntry> target_entry;
  351. JS::Handle<Navigable> navigable;
  352. bool update_only = false;
  353. };
  354. // 11. Let changingNavigableContinuations be an empty queue of changing navigable continuation states.
  355. // NOTE: This queue is used to split the operations on changingNavigables into two parts. Specifically, changingNavigableContinuations holds data for the second part.
  356. IGNORE_USE_IN_ESCAPING_LAMBDA Queue<ChangingNavigableContinuationState> changing_navigable_continuations;
  357. // 12. For each navigable of changingNavigables, queue a global task on the navigation and traversal task source of navigable's active window to run the steps:
  358. for (auto& navigable : changing_navigables) {
  359. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&] {
  360. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  361. if (navigable->has_been_destroyed()) {
  362. completed_change_jobs++;
  363. return;
  364. }
  365. // 1. Let displayedEntry be navigable's active session history entry.
  366. auto displayed_entry = navigable->active_session_history_entry();
  367. // 2. Let targetEntry be navigable's current session history entry.
  368. auto target_entry = navigable->current_session_history_entry();
  369. // 3. Let changingNavigableContinuation be a changing navigable continuation state with:
  370. auto changing_navigable_continuation = ChangingNavigableContinuationState {
  371. .displayed_document = displayed_entry->document(),
  372. .target_entry = target_entry,
  373. .navigable = navigable,
  374. .update_only = false
  375. };
  376. // 4. If displayedEntry is targetEntry and targetEntry's document state's reload pending is false, then:
  377. if (synchronous_navigation == SynchronousNavigation::Yes && !target_entry->document_state()->reload_pending()) {
  378. // 1. Set changingNavigableContinuation's update-only to true.
  379. changing_navigable_continuation.update_only = true;
  380. // 2. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  381. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  382. // 3. Abort these steps.
  383. return;
  384. }
  385. // 5. Switch on navigationType:
  386. if (navigation_type.has_value()) {
  387. switch (navigation_type.value()) {
  388. case Bindings::NavigationType::Reload:
  389. // - "reload": Assert: targetEntry's document state's reload pending is true.
  390. VERIFY(target_entry->document_state()->reload_pending());
  391. break;
  392. case Bindings::NavigationType::Traverse:
  393. // - "traverse": Assert: targetEntry's document state's ever populated is true.
  394. VERIFY(target_entry->document_state()->ever_populated());
  395. break;
  396. case Bindings::NavigationType::Replace:
  397. // FIXME: Add ever populated check
  398. // - "replace": Assert: targetEntry's step is displayedEntry's step and targetEntry's document state's ever populated is false.
  399. VERIFY(target_entry->step() == displayed_entry->step());
  400. break;
  401. case Bindings::NavigationType::Push:
  402. // FIXME: Add ever populated check, and fix the bug where top level traversable's step is not updated when a child navigable navigates
  403. // - "push": Assert: targetEntry's step is displayedEntry's step + 1 and targetEntry's document state's ever populated is false.
  404. VERIFY(target_entry->step().get<int>() > displayed_entry->step().get<int>());
  405. break;
  406. }
  407. }
  408. // 6. Let oldOrigin be targetEntry's document state's origin.
  409. auto old_origin = target_entry->document_state()->origin();
  410. // FIXME: 7. If navigable is not traversable, and targetEntry is not navigable's current session history entry,
  411. // and oldOrigin is the same as navigable's current session history entry's document state's origin,
  412. // then fire a traverse navigate event given targetEntry and userInvolvementForNavigateEvents.
  413. auto after_document_populated = [old_origin, target_entry, changing_navigable_continuation, &changing_navigable_continuations, &vm, &navigable]() mutable {
  414. // 1. If targetEntry's document is null, then set changingNavigableContinuation's update-only to true.
  415. if (!target_entry->document()) {
  416. changing_navigable_continuation.update_only = true;
  417. }
  418. else {
  419. // 2. If targetEntry's document's origin is not oldOrigin, then set targetEntry's classic history API state to StructuredSerializeForStorage(null).
  420. if (target_entry->document()->origin() != old_origin) {
  421. target_entry->set_classic_history_api_state(MUST(structured_serialize_for_storage(vm, JS::js_null())));
  422. }
  423. // 3. If all of the following are true:
  424. // - navigable's parent is null;
  425. // - targetEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
  426. // - targetEntry's document's origin is not oldOrigin,
  427. // then set targetEntry's document state's navigable target name to the empty string.
  428. if (navigable->parent() != nullptr
  429. && target_entry->document()->browsing_context()->opener_browsing_context() == nullptr
  430. && target_entry->document_state()->origin() != old_origin) {
  431. target_entry->document_state()->set_navigable_target_name(String {});
  432. }
  433. }
  434. // 4. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  435. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  436. };
  437. // 8. If targetEntry's document is null, or targetEntry's document state's reload pending is true, then:
  438. if (!target_entry->document() || target_entry->document_state()->reload_pending()) {
  439. // FIXME: 1. Let navTimingType be "back_forward" if targetEntry's document is null; otherwise "reload".
  440. // 2. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  441. auto target_snapshot_params = navigable->snapshot_target_snapshot_params();
  442. // 3. Let potentiallyTargetSpecificSourceSnapshotParams be sourceSnapshotParams.
  443. Optional<SourceSnapshotParams> potentially_target_specific_source_snapshot_params = source_snapshot_params;
  444. // 4. If potentiallyTargetSpecificSourceSnapshotParams is null, then set it to the result of snapshotting source snapshot params given navigable's active document.
  445. if (!potentially_target_specific_source_snapshot_params.has_value()) {
  446. potentially_target_specific_source_snapshot_params = navigable->active_document()->snapshot_source_snapshot_params();
  447. }
  448. // 5. Set targetEntry's document state's reload pending to false.
  449. target_entry->document_state()->set_reload_pending(false);
  450. // 6. Let allowPOST be targetEntry's document state's reload pending.
  451. auto allow_POST = target_entry->document_state()->reload_pending();
  452. // 7. In parallel, attempt to populate the history entry's document for targetEntry, given navigable, potentiallyTargetSpecificSourceSnapshotParams,
  453. // targetSnapshotParams, with allowPOST set to allowPOST and completionSteps set to queue a global task on the navigation and traversal task source given
  454. // navigable's active window to run afterDocumentPopulated.
  455. Platform::EventLoopPlugin::the().deferred_invoke([target_entry, potentially_target_specific_source_snapshot_params, target_snapshot_params, this, allow_POST, navigable, after_document_populated] {
  456. navigable->populate_session_history_entry_document(target_entry, *potentially_target_specific_source_snapshot_params, target_snapshot_params, {}, Empty {}, CSPNavigationType::Other, allow_POST, [this, after_document_populated]() mutable {
  457. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [after_document_populated]() mutable {
  458. after_document_populated();
  459. });
  460. })
  461. .release_value_but_fixme_should_propagate_errors();
  462. });
  463. }
  464. // Otherwise, run afterDocumentPopulated immediately.
  465. else {
  466. after_document_populated();
  467. }
  468. });
  469. }
  470. auto check_if_document_population_tasks_completed = JS::SafeFunction<bool()>([&] {
  471. return changing_navigable_continuations.size() + completed_change_jobs == total_change_jobs;
  472. });
  473. if (synchronous_navigation == SynchronousNavigation::Yes) {
  474. // NOTE: Synchronous navigation should never require document population, so it is safe to process only NavigationAndTraversal source.
  475. main_thread_event_loop().spin_processing_tasks_with_source_until(Task::Source::NavigationAndTraversal, move(check_if_document_population_tasks_completed));
  476. } else {
  477. // NOTE: Process all task sources while waiting because reloading or back/forward navigation might require fetching to populate a document.
  478. main_thread_event_loop().spin_until(move(check_if_document_population_tasks_completed));
  479. }
  480. // 13. Let navigablesThatMustWaitBeforeHandlingSyncNavigation be an empty set.
  481. Vector<JS::GCPtr<Navigable>> navigables_that_must_wait_before_handling_sync_navigation;
  482. // 14. While completedChangeJobs does not equal totalChangeJobs:
  483. while (!changing_navigable_continuations.is_empty()) {
  484. // NOTE: Synchronous navigations that are intended to take place before this traversal jump the queue at this point,
  485. // so they can be added to the correct place in traversable's session history entries before this traversal
  486. // potentially unloads their document. More details can be found here (https://html.spec.whatwg.org/multipage/browsing-the-web.html#sync-navigation-steps-queue-jumping-examples)
  487. // 1. If traversable's running nested apply history step is false, then:
  488. if (!m_running_nested_apply_history_step) {
  489. // 1. While traversable's session history traversal queue's algorithm set contains one or more synchronous
  490. // navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation:
  491. // 1. Let steps be the first item in traversable's session history traversal queue's algorithm set
  492. // that is synchronous navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation.
  493. // 2. Remove steps from traversable's session history traversal queue's algorithm set.
  494. for (auto entry = m_session_history_traversal_queue->first_synchronous_navigation_steps_with_target_navigable_not_contained_in(navigables_that_must_wait_before_handling_sync_navigation);
  495. entry;
  496. entry = m_session_history_traversal_queue->first_synchronous_navigation_steps_with_target_navigable_not_contained_in(navigables_that_must_wait_before_handling_sync_navigation)) {
  497. // 3. Set traversable's running nested apply history step to true.
  498. m_running_nested_apply_history_step = true;
  499. // 4. Run steps.
  500. entry->execute_steps();
  501. // 5. Set traversable's running nested apply history step to false.
  502. m_running_nested_apply_history_step = false;
  503. }
  504. }
  505. // 2. Let changingNavigableContinuation be the result of dequeuing from changingNavigableContinuations.
  506. auto changing_navigable_continuation = changing_navigable_continuations.dequeue();
  507. // 3. If changingNavigableContinuation is nothing, then continue.
  508. // 4. Let displayedDocument be changingNavigableContinuation's displayed document.
  509. auto displayed_document = changing_navigable_continuation.displayed_document;
  510. // 5. Let targetEntry be changingNavigableContinuation's target entry.
  511. auto target_entry = changing_navigable_continuation.target_entry;
  512. // 6. Let navigable be changingNavigableContinuation's navigable.
  513. auto navigable = changing_navigable_continuation.navigable;
  514. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  515. if (navigable->has_been_destroyed())
  516. continue;
  517. // 7. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  518. auto history_object_length_and_index = get_the_history_object_length_and_index(target_step);
  519. auto script_history_length = history_object_length_and_index.script_history_length;
  520. auto script_history_index = history_object_length_and_index.script_history_index;
  521. // 8. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation.
  522. navigables_that_must_wait_before_handling_sync_navigation.append(*navigable);
  523. // 9. Let entriesForNavigationAPI be the result of getting session history entries for the navigation API given navigable and targetStep.
  524. auto entries_for_navigation_api = get_session_history_entries_for_the_navigation_api(*navigable, target_step);
  525. // 12. In both cases, let afterPotentialUnloads be the following steps:
  526. auto after_potential_unload = JS::SafeFunction<void()>([changing_navigable_continuation, target_entry, displayed_document, &completed_change_jobs, script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api)] {
  527. // 1. If changingNavigableContinuation's update-only is false, then activate history entry targetEntry for navigable.
  528. if (!changing_navigable_continuation.update_only)
  529. changing_navigable_continuation.navigable->activate_history_entry(*changing_navigable_continuation.target_entry);
  530. // 2. Let updateDocument be an algorithm step which performs update document for history step application given
  531. // targetEntry's document, targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength,
  532. // scriptHistoryIndex, navigationType, entriesForNavigationAPI, and displayedEntry.
  533. auto update_document = JS::SafeFunction<void()>([changing_navigable_continuation, script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api)] {
  534. changing_navigable_continuation.target_entry->document()->update_for_history_step_application(*changing_navigable_continuation.target_entry, changing_navigable_continuation.update_only, script_history_length, script_history_index, entries_for_navigation_api);
  535. });
  536. // 3. If targetEntry's document is equal to displayedDocument, then perform updateDocument.
  537. if (target_entry->document().ptr() == displayed_document.ptr()) {
  538. update_document();
  539. }
  540. // 5. Otherwise, queue a global task on the navigation and traversal task source given targetEntry's document's relevant global object to perform updateDocument
  541. else {
  542. queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*target_entry->document()), [update_document = move(update_document)]() {
  543. update_document();
  544. });
  545. }
  546. // 6. Increment completedChangeJobs.
  547. completed_change_jobs++;
  548. });
  549. // 10. If changingNavigableContinuation's update-only is true, or targetEntry's document is displayedDocument, then:
  550. if (changing_navigable_continuation.update_only || target_entry->document().ptr() == displayed_document.ptr()) {
  551. // 1. Set the ongoing navigation for navigable to null.
  552. navigable->set_ongoing_navigation({});
  553. // 2. Queue a global task on the navigation and traversal task source given navigable's active window to perform afterPotentialUnloads.
  554. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), move(after_potential_unload));
  555. }
  556. // 11. Otherwise:
  557. else {
  558. // 1. Assert: navigationType is not null.
  559. VERIFY(navigation_type.has_value());
  560. // 2. Deactivate displayedDocument, given userNavigationInvolvement, targetEntry, navigationType, and afterPotentialUnloads.
  561. deactivate_a_document_for_cross_document_navigation(*displayed_document, user_involvement_for_navigate_events, *target_entry, move(after_potential_unload));
  562. }
  563. }
  564. main_thread_event_loop().spin_processing_tasks_with_source_until(Task::Source::NavigationAndTraversal, [&] {
  565. return completed_change_jobs == total_change_jobs;
  566. });
  567. // 15. Let totalNonchangingJobs be the size of nonchangingNavigablesThatStillNeedUpdates.
  568. auto total_non_changing_jobs = non_changing_navigables_that_still_need_updates.size();
  569. // 16. Let completedNonchangingJobs be 0.
  570. IGNORE_USE_IN_ESCAPING_LAMBDA auto completed_non_changing_jobs = 0u;
  571. // 17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  572. auto length_and_index = get_the_history_object_length_and_index(target_step);
  573. IGNORE_USE_IN_ESCAPING_LAMBDA auto script_history_length = length_and_index.script_history_length;
  574. IGNORE_USE_IN_ESCAPING_LAMBDA auto script_history_index = length_and_index.script_history_index;
  575. // 18. For each navigable of nonchangingNavigablesThatStillNeedUpdates, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
  576. for (auto& navigable : non_changing_navigables_that_still_need_updates) {
  577. if (navigable->has_been_destroyed()) {
  578. ++completed_non_changing_jobs;
  579. continue;
  580. }
  581. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&] {
  582. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  583. if (navigable->has_been_destroyed()) {
  584. ++completed_non_changing_jobs;
  585. return;
  586. }
  587. // 1. Let document be navigable's active document.
  588. auto document = navigable->active_document();
  589. // 2. Set document's history object's index to scriptHistoryIndex.
  590. document->history()->m_index = script_history_index;
  591. // 3. Set document's history object's length to scriptHistoryLength.
  592. document->history()->m_length = script_history_length;
  593. // 4. Increment completedNonchangingJobs.
  594. ++completed_non_changing_jobs;
  595. });
  596. }
  597. // 19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.
  598. // AD-HOC: Since currently populate_session_history_entry_document does not run in parallel
  599. // we call spin_until to interrupt execution of this function and let document population
  600. // to complete.
  601. main_thread_event_loop().spin_processing_tasks_with_source_until(Task::Source::NavigationAndTraversal, [&] {
  602. return completed_non_changing_jobs == total_non_changing_jobs;
  603. });
  604. // 20. Set traversable's current session history step to targetStep.
  605. m_current_session_history_step = target_step;
  606. // 21. Return "applied".
  607. return HistoryStepResult::Applied;
  608. }
  609. Vector<JS::NonnullGCPtr<SessionHistoryEntry>> TraversableNavigable::get_session_history_entries_for_the_navigation_api(JS::NonnullGCPtr<Navigable> navigable, int target_step)
  610. {
  611. // 1. Let rawEntries be the result of getting session history entries for navigable.
  612. auto raw_entries = navigable->get_session_history_entries();
  613. if (raw_entries.is_empty())
  614. return {};
  615. // 2. Let entriesForNavigationAPI be a new empty list.
  616. Vector<JS::NonnullGCPtr<SessionHistoryEntry>> entries_for_navigation_api;
  617. // 3. Let startingIndex be the index of the session history entry in rawEntries who has the greatest step less than or equal to targetStep.
  618. // FIXME: Use min/max_element algorithm or some such here
  619. int starting_index = 0;
  620. auto max_step = 0;
  621. for (auto i = 0u; i < raw_entries.size(); ++i) {
  622. auto const& entry = raw_entries[i];
  623. if (entry->step().has<int>()) {
  624. auto step = entry->step().get<int>();
  625. if (step <= target_step && step > max_step) {
  626. starting_index = static_cast<int>(i);
  627. }
  628. }
  629. }
  630. // 4. Append rawEntries[startingIndex] to entriesForNavigationAPI.
  631. entries_for_navigation_api.append(raw_entries[starting_index]);
  632. // 5. Let startingOrigin be rawEntries[startingIndex]'s document state's origin.
  633. auto starting_origin = raw_entries[starting_index]->document_state()->origin();
  634. // 6. Let i be startingIndex − 1.
  635. auto i = starting_index - 1;
  636. // 7. While i > 0:
  637. while (i > 0) {
  638. auto& entry = raw_entries[static_cast<unsigned>(i)];
  639. // 1. If rawEntries[i]'s document state's origin is not same origin with startingOrigin, then break.
  640. auto entry_origin = entry->document_state()->origin();
  641. if (starting_origin.has_value() && entry_origin.has_value() && !entry_origin->is_same_origin(*starting_origin))
  642. break;
  643. // 2. Prepend rawEntries[i] to entriesForNavigationAPI.
  644. entries_for_navigation_api.prepend(entry);
  645. // 3. Set i to i − 1.
  646. --i;
  647. }
  648. // 8. Set i to startingIndex + 1.
  649. i = starting_index + 1;
  650. // 9. While i < rawEntries's size:
  651. while (i < static_cast<int>(raw_entries.size())) {
  652. auto& entry = raw_entries[static_cast<unsigned>(i)];
  653. // 1. If rawEntries[i]'s document state's origin is not same origin with startingOrigin, then break.
  654. auto entry_origin = entry->document_state()->origin();
  655. if (starting_origin.has_value() && entry_origin.has_value() && !entry_origin->is_same_origin(*starting_origin))
  656. break;
  657. // 2. Append rawEntries[i] to entriesForNavigationAPI.
  658. entries_for_navigation_api.append(entry);
  659. // 3. Set i to i + 1.
  660. ++i;
  661. }
  662. // 10. Return entriesForNavigationAPI.
  663. return entries_for_navigation_api;
  664. }
  665. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#clear-the-forward-session-history
  666. void TraversableNavigable::clear_the_forward_session_history()
  667. {
  668. // FIXME: 1. Assert: this is running within navigable's session history traversal queue.
  669. // 2. Let step be the navigable's current session history step.
  670. auto step = current_session_history_step();
  671. // 3. Let entryLists be the ordered set « navigable's session history entries ».
  672. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>&> entry_lists;
  673. entry_lists.append(session_history_entries());
  674. // 4. For each entryList of entryLists:
  675. while (!entry_lists.is_empty()) {
  676. auto& entry_list = entry_lists.take_first();
  677. // 1. Remove every session history entry from entryList that has a step greater than step.
  678. entry_list.remove_all_matching([step](auto& entry) {
  679. return entry->step().template get<int>() > step;
  680. });
  681. // 2. For each entry of entryList:
  682. for (auto& entry : entry_list) {
  683. // 1. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  684. for (auto& nested_history : entry->document_state()->nested_histories()) {
  685. entry_lists.append(nested_history.entries);
  686. }
  687. }
  688. }
  689. }
  690. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history-by-a-delta
  691. void TraversableNavigable::traverse_the_history_by_delta(int delta, Optional<DOM::Document&> source_document)
  692. {
  693. // 1. Let sourceSnapshotParams and initiatorToCheck be null.
  694. Optional<SourceSnapshotParams> source_snapshot_params = {};
  695. JS::GCPtr<Navigable> initiator_to_check = nullptr;
  696. // 2. Let userInvolvement be "browser UI".
  697. UserNavigationInvolvement user_involvement = UserNavigationInvolvement::BrowserUI;
  698. // 1. If sourceDocument is given, then:
  699. if (source_document.has_value()) {
  700. // 1. Set sourceSnapshotParams to the result of snapshotting source snapshot params given sourceDocument.
  701. source_snapshot_params = source_document->snapshot_source_snapshot_params();
  702. // 2. Set initiatorToCheck to sourceDocument's node navigable.
  703. initiator_to_check = source_document->navigable();
  704. // 3. Set userInvolvement to "none".
  705. user_involvement = UserNavigationInvolvement::None;
  706. }
  707. // 4. Append the following session history traversal steps to traversable:
  708. append_session_history_traversal_steps([this, delta, source_snapshot_params = move(source_snapshot_params), initiator_to_check, user_involvement] {
  709. // 1. Let allSteps be the result of getting all used history steps for traversable.
  710. auto all_steps = get_all_used_history_steps();
  711. // 2. Let currentStepIndex be the index of traversable's current session history step within allSteps.
  712. auto current_step_index = *all_steps.find_first_index(current_session_history_step());
  713. // 3. Let targetStepIndex be currentStepIndex plus delta
  714. auto target_step_index = current_step_index + delta;
  715. // 4. If allSteps[targetStepIndex] does not exist, then abort these steps.
  716. if (target_step_index >= all_steps.size()) {
  717. return;
  718. }
  719. // 5. Apply the traverse history step allSteps[targetStepIndex] to traversable, given sourceSnapshotParams,
  720. // initiatorToCheck, and userInvolvement.
  721. apply_the_traverse_history_step(all_steps[target_step_index], source_snapshot_params, initiator_to_check, user_involvement);
  722. });
  723. }
  724. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#update-for-navigable-creation/destruction
  725. TraversableNavigable::HistoryStepResult TraversableNavigable::update_for_navigable_creation_or_destruction()
  726. {
  727. // 1. Let step be traversable's current session history step.
  728. auto step = current_session_history_step();
  729. // 2. Return the result of applying the history step to traversable given false, null, null, null, and null.
  730. return apply_the_history_step(step, false, {}, {}, {}, {}, SynchronousNavigation::No);
  731. }
  732. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-reload-history-step
  733. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_reload_history_step()
  734. {
  735. // 1. Let step be traversable's current session history step.
  736. auto step = current_session_history_step();
  737. // 2. Return the result of applying the history step step to traversable given true, null, null, null, and "reload".
  738. return apply_the_history_step(step, true, {}, {}, {}, Bindings::NavigationType::Reload, SynchronousNavigation::No);
  739. }
  740. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_push_or_replace_history_step(int step, HistoryHandlingBehavior history_handling, SynchronousNavigation synchronous_navigation)
  741. {
  742. // 1. Return the result of applying the history step step to traversable given false, null, null, null, and historyHandling.
  743. auto navigation_type = history_handling == HistoryHandlingBehavior::Replace ? Bindings::NavigationType::Replace : Bindings::NavigationType::Push;
  744. return apply_the_history_step(step, false, {}, {}, {}, navigation_type, synchronous_navigation);
  745. }
  746. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_traverse_history_step(int step, Optional<SourceSnapshotParams> source_snapshot_params, JS::GCPtr<Navigable> initiator_to_check, UserNavigationInvolvement user_involvement)
  747. {
  748. // 1. Return the result of applying the history step step to traversable given true, sourceSnapshotParams, initiatorToCheck, userInvolvement, and "traverse".
  749. return apply_the_history_step(step, true, move(source_snapshot_params), initiator_to_check, user_involvement, Bindings::NavigationType::Traverse, SynchronousNavigation::No);
  750. }
  751. // https://html.spec.whatwg.org/multipage/document-sequences.html#close-a-top-level-traversable
  752. void TraversableNavigable::close_top_level_traversable()
  753. {
  754. VERIFY(is_top_level_traversable());
  755. // 1. Let toUnload be traversable's active document's inclusive descendant navigables.
  756. auto to_unload = active_document()->inclusive_descendant_navigables();
  757. // FIXME: 2. If the result of checking if unloading is user-canceled for toUnload is true, then return.
  758. // 3. Unload the active documents of each of toUnload.
  759. for (auto navigable : to_unload) {
  760. navigable->active_document()->unload();
  761. }
  762. // 4. Destroy traversable.
  763. destroy_top_level_traversable();
  764. }
  765. // https://html.spec.whatwg.org/multipage/document-sequences.html#destroy-a-top-level-traversable
  766. void TraversableNavigable::destroy_top_level_traversable()
  767. {
  768. VERIFY(is_top_level_traversable());
  769. // 1. Let browsingContext be traversable's active browsing context.
  770. auto browsing_context = active_browsing_context();
  771. // 2. For each historyEntry in traversable's session history entries:
  772. for (auto& history_entry : m_session_history_entries) {
  773. // 1. Let document be historyEntry's document.
  774. auto document = history_entry->document();
  775. // 2. If document is not null, then destroy document.
  776. if (document)
  777. document->destroy();
  778. }
  779. // 3. Remove browsingContext.
  780. if (!browsing_context) {
  781. dbgln("TraversableNavigable::destroy_top_level_traversable: No browsing context?");
  782. } else {
  783. browsing_context->remove();
  784. }
  785. // 4. Remove traversable from the user interface (e.g., close or hide its tab in a tabbed browser).
  786. page().client().page_did_close_top_level_traversable();
  787. // 5. Remove traversable from the user agent's top-level traversable set.
  788. user_agent_top_level_traversable_set().remove(this);
  789. // FIXME: Figure out why we need to do this... we shouldn't be leaking Navigables for all time.
  790. // However, without this, we can keep stale destroyed traversables around.
  791. set_has_been_destroyed();
  792. all_navigables().remove(this);
  793. }
  794. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-same-document-navigation
  795. void finalize_a_same_document_navigation(JS::NonnullGCPtr<TraversableNavigable> traversable, JS::NonnullGCPtr<Navigable> target_navigable, JS::NonnullGCPtr<SessionHistoryEntry> target_entry, JS::GCPtr<SessionHistoryEntry> entry_to_replace, HistoryHandlingBehavior history_handling)
  796. {
  797. // NOTE: This is not in the spec but we should not navigate destroyed navigable.
  798. if (target_navigable->has_been_destroyed())
  799. return;
  800. // FIXME: 1. Assert: this is running on traversable's session history traversal queue.
  801. // 2. If targetNavigable's active session history entry is not targetEntry, then return.
  802. if (target_navigable->active_session_history_entry() != target_entry) {
  803. return;
  804. }
  805. // 3. Let targetStep be null.
  806. Optional<int> target_step;
  807. // 4. Let targetEntries be the result of getting session history entries for targetNavigable.
  808. auto& target_entries = target_navigable->get_session_history_entries();
  809. // 5. If entryToReplace is null, then:
  810. // FIXME: Checking containment of entryToReplace should not be needed.
  811. // For more details see https://github.com/whatwg/html/issues/10232#issuecomment-2037543137
  812. if (!entry_to_replace || !target_entries.contains_slow(JS::NonnullGCPtr { *entry_to_replace })) {
  813. // 1. Clear the forward session history of traversable.
  814. traversable->clear_the_forward_session_history();
  815. // 2. Set targetStep to traversable's current session history step + 1.
  816. target_step = traversable->current_session_history_step() + 1;
  817. // 3. Set targetEntry's step to targetStep.
  818. target_entry->set_step(*target_step);
  819. // 4. Append targetEntry to targetEntries.
  820. target_entries.append(target_entry);
  821. } else {
  822. // 1. Replace entryToReplace with targetEntry in targetEntries.
  823. *(target_entries.find(*entry_to_replace)) = target_entry;
  824. // 2. Set targetEntry's step to entryToReplace's step.
  825. target_entry->set_step(entry_to_replace->step());
  826. // 3. Set targetStep to traversable's current session history step.
  827. target_step = traversable->current_session_history_step();
  828. }
  829. // 6. Apply the push/replace history step targetStep to traversable given historyHandling.
  830. traversable->apply_the_push_or_replace_history_step(*target_step, history_handling, TraversableNavigable::SynchronousNavigation::Yes);
  831. }
  832. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  833. void TraversableNavigable::set_system_visibility_state(VisibilityState visibility_state)
  834. {
  835. if (m_system_visibility_state == visibility_state)
  836. return;
  837. m_system_visibility_state = visibility_state;
  838. // When a user-agent determines that the system visibility state for
  839. // traversable navigable traversable has changed to newState, it must run the following steps:
  840. // 1. Let navigables be the inclusive descendant navigables of traversable's active document.
  841. auto navigables = active_document()->inclusive_descendant_navigables();
  842. // 2. For each navigable of navigables:
  843. for (auto& navigable : navigables) {
  844. // 1. Let document be navigable's active document.
  845. auto document = navigable->active_document();
  846. VERIFY(document);
  847. // 2. Queue a global task on the user interaction task source given document's relevant global object
  848. // to update the visibility state of document with newState.
  849. queue_global_task(Task::Source::UserInteraction, relevant_global_object(*document), [visibility_state, document] {
  850. document->update_the_visibility_state(visibility_state);
  851. });
  852. }
  853. }
  854. }