TraversableNavigable.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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/NavigationParams.h>
  12. #include <LibWeb/HTML/SessionHistoryEntry.h>
  13. #include <LibWeb/HTML/TraversableNavigable.h>
  14. #include <LibWeb/HTML/Window.h>
  15. #include <LibWeb/Page/Page.h>
  16. #include <LibWeb/Platform/EventLoopPlugin.h>
  17. namespace Web::HTML {
  18. TraversableNavigable::TraversableNavigable(Page& page)
  19. : m_page(page)
  20. {
  21. }
  22. TraversableNavigable::~TraversableNavigable() = default;
  23. void TraversableNavigable::visit_edges(Cell::Visitor& visitor)
  24. {
  25. Base::visit_edges(visitor);
  26. for (auto& entry : m_session_history_entries)
  27. visitor.visit(entry);
  28. }
  29. static OrderedHashTable<TraversableNavigable*>& user_agent_top_level_traversable_set()
  30. {
  31. static OrderedHashTable<TraversableNavigable*> set;
  32. return set;
  33. }
  34. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-browsing-context
  35. WebIDL::ExceptionOr<BrowsingContextAndDocument> create_a_new_top_level_browsing_context_and_document(Page& page)
  36. {
  37. // 1. Let group and document be the result of creating a new browsing context group and document.
  38. auto [group, document] = TRY(BrowsingContextGroup::create_a_new_browsing_context_group_and_document(page));
  39. // 2. Return group's browsing context set[0] and document.
  40. return BrowsingContextAndDocument { **group->browsing_context_set().begin(), document };
  41. }
  42. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-traversable
  43. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_new_top_level_traversable(Page& page, JS::GCPtr<HTML::BrowsingContext> opener, String target_name)
  44. {
  45. auto& vm = Bindings::main_thread_vm();
  46. // 1. Let document be null.
  47. JS::GCPtr<DOM::Document> document = nullptr;
  48. // 2. If opener is null, then set document to the second return value of creating a new top-level browsing context and document.
  49. if (!opener) {
  50. document = TRY(create_a_new_top_level_browsing_context_and_document(page)).document;
  51. }
  52. // 3. Otherwise, set document to the second return value of creating a new auxiliary browsing context and document given opener.
  53. else {
  54. document = TRY(BrowsingContext::create_a_new_auxiliary_browsing_context_and_document(page, *opener)).document;
  55. }
  56. // 4. Let documentState be a new document state, with
  57. auto document_state = vm.heap().allocate_without_realm<DocumentState>();
  58. // document: document
  59. document_state->set_document(document);
  60. // initiator origin: null if opener is null; otherwise, document's origin
  61. document_state->set_initiator_origin(opener ? Optional<Origin> {} : document->origin());
  62. // origin: document's origin
  63. document_state->set_origin(document->origin());
  64. // navigable target name: targetName
  65. document_state->set_navigable_target_name(target_name);
  66. // about base URL: document's about base URL
  67. document_state->set_about_base_url(document->about_base_url());
  68. // 5. Let traversable be a new traversable navigable.
  69. auto traversable = vm.heap().allocate_without_realm<TraversableNavigable>(page);
  70. // 6. Initialize the navigable traversable given documentState.
  71. TRY_OR_THROW_OOM(vm, traversable->initialize_navigable(document_state, nullptr));
  72. // 7. Let initialHistoryEntry be traversable's active session history entry.
  73. auto initial_history_entry = traversable->active_session_history_entry();
  74. VERIFY(initial_history_entry);
  75. // 8. Set initialHistoryEntry's step to 0.
  76. initial_history_entry->step = 0;
  77. // 9. Append initialHistoryEntry to traversable's session history entries.
  78. traversable->m_session_history_entries.append(*initial_history_entry);
  79. // FIXME: 10. If opener is non-null, then legacy-clone a traversable storage shed given opener's top-level traversable and traversable. [STORAGE]
  80. // 11. Append traversable to the user agent's top-level traversable set.
  81. user_agent_top_level_traversable_set().set(traversable);
  82. // 12. Return traversable.
  83. return traversable;
  84. }
  85. // https://html.spec.whatwg.org/multipage/document-sequences.html#create-a-fresh-top-level-traversable
  86. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_fresh_top_level_traversable(Page& page, AK::URL const& initial_navigation_url, Variant<Empty, String, POSTResource> initial_navigation_post_resource)
  87. {
  88. // 1. Let traversable be the result of creating a new top-level traversable given null and the empty string.
  89. auto traversable = TRY(create_a_new_top_level_traversable(page, nullptr, {}));
  90. // 2. Navigate traversable to initialNavigationURL using traversable's active document, with documentResource set to initialNavigationPostResource.
  91. TRY(traversable->navigate({ .url = initial_navigation_url,
  92. .source_document = *traversable->active_document(),
  93. .document_resource = initial_navigation_post_resource }));
  94. // 3. Return traversable.
  95. return traversable;
  96. }
  97. // https://html.spec.whatwg.org/multipage/document-sequences.html#top-level-traversable
  98. bool TraversableNavigable::is_top_level_traversable() const
  99. {
  100. // A top-level traversable is a traversable navigable with a null parent.
  101. return parent() == nullptr;
  102. }
  103. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-used-history-steps
  104. Vector<int> TraversableNavigable::get_all_used_history_steps() const
  105. {
  106. // FIXME: 1. Assert: this is running within traversable's session history traversal queue.
  107. // 2. Let steps be an empty ordered set of non-negative integers.
  108. OrderedHashTable<int> steps;
  109. // 3. Let entryLists be the ordered set « traversable's session history entries ».
  110. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>> entry_lists { session_history_entries() };
  111. // 4. For each entryList of entryLists:
  112. while (!entry_lists.is_empty()) {
  113. auto entry_list = entry_lists.take_first();
  114. // 1. For each entry of entryList:
  115. for (auto& entry : entry_list) {
  116. // 1. Append entry's step to steps.
  117. steps.set(entry->step.get<int>());
  118. // 2. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  119. for (auto& nested_history : entry->document_state->nested_histories())
  120. entry_lists.append(nested_history.entries);
  121. }
  122. }
  123. // 5. Return steps, sorted.
  124. auto sorted_steps = steps.values();
  125. quick_sort(sorted_steps);
  126. return sorted_steps;
  127. }
  128. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-history-object-length-and-index
  129. TraversableNavigable::HistoryObjectLengthAndIndex TraversableNavigable::get_the_history_object_length_and_index(int step) const
  130. {
  131. // 1. Let steps be the result of getting all used history steps within traversable.
  132. auto steps = get_all_used_history_steps();
  133. // 2. Let scriptHistoryLength be the size of steps.
  134. auto script_history_length = steps.size();
  135. // 3. Assert: steps contains step.
  136. VERIFY(steps.contains_slow(step));
  137. // 4. Let scriptHistoryIndex be the index of step in steps.
  138. auto script_history_index = *steps.find_first_index(step);
  139. // 5. Return (scriptHistoryLength, scriptHistoryIndex).
  140. return HistoryObjectLengthAndIndex {
  141. .script_history_length = script_history_length,
  142. .script_history_index = script_history_index
  143. };
  144. }
  145. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-used-step
  146. int TraversableNavigable::get_the_used_step(int step) const
  147. {
  148. // 1. Let steps be the result of getting all used history steps within traversable.
  149. auto steps = get_all_used_history_steps();
  150. // 2. Return the greatest item in steps that is less than or equal to step.
  151. VERIFY(!steps.is_empty());
  152. Optional<int> result;
  153. for (size_t i = 0; i < steps.size(); i++) {
  154. if (steps[i] <= step) {
  155. if (!result.has_value() || (result.value() < steps[i])) {
  156. result = steps[i];
  157. }
  158. }
  159. }
  160. return result.value();
  161. }
  162. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#get-all-navigables-whose-current-session-history-entry-will-change-or-reload
  163. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_whose_current_session_history_entry_will_change_or_reload(int target_step) const
  164. {
  165. // 1. Let results be an empty list.
  166. Vector<JS::Handle<Navigable>> results;
  167. // 2. Let navigablesToCheck be « traversable ».
  168. Vector<JS::Handle<Navigable>> navigables_to_check;
  169. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  170. // 3. For each navigable of navigablesToCheck:
  171. while (!navigables_to_check.is_empty()) {
  172. auto navigable = navigables_to_check.take_first();
  173. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  174. auto target_entry = navigable->get_the_target_history_entry(target_step);
  175. // 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.
  176. if (target_entry != navigable->current_session_history_entry() || target_entry->document_state->reload_pending()) {
  177. results.append(*navigable);
  178. }
  179. // 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.
  180. if (target_entry->document_state->document() == navigable->active_document() && !target_entry->document_state->reload_pending()) {
  181. navigables_to_check.extend(navigable->child_navigables());
  182. }
  183. }
  184. // 4. Return results.
  185. return results;
  186. }
  187. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-history-step
  188. void TraversableNavigable::apply_the_history_step(int step, Optional<SourceSnapshotParams> source_snapshot_params)
  189. {
  190. // FIXME: 1. Assert: This is running within traversable's session history traversal queue.
  191. // 2. Let targetStep be the result of getting the used step given traversable and step.
  192. auto target_step = get_the_used_step(step);
  193. // FIXME: 3. If initiatorToCheck is given, then:
  194. // FIXME: 4. Let navigablesCrossingDocuments be the result of getting all navigables that might experience a cross-document traversal given traversable and targetStep.
  195. // FIXME: 5. If checkForUserCancelation is true, and the result of checking if unloading is user-canceled given navigablesCrossingDocuments given traversable and targetStep is true, then return.
  196. // 6. Let changingNavigables be the result of get all navigables whose current session history entry will change or reload given traversable and targetStep.
  197. auto changing_navigables = get_all_navigables_whose_current_session_history_entry_will_change_or_reload(target_step);
  198. // FIXME: 7. Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need history object length/index update given traversable and targetStep.
  199. // 8. For each navigable of changingNavigables:
  200. for (auto& navigable : changing_navigables) {
  201. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  202. auto target_entry = navigable->get_the_target_history_entry(target_step);
  203. // 2. Set navigable's current session history entry to targetEntry.
  204. navigable->set_current_session_history_entry(target_entry);
  205. // 3. Set navigable's ongoing navigation to "traversal".
  206. navigable->set_ongoing_navigation(Traversal::Tag);
  207. }
  208. // 9. Let totalChangeJobs be the size of changingNavigables.
  209. auto total_change_jobs = changing_navigables.size();
  210. // 10. Let completedChangeJobs be 0.
  211. size_t completed_change_jobs = 0;
  212. struct ChangingNavigableContinuationState {
  213. JS::Handle<DOM::Document> displayed_document;
  214. JS::Handle<SessionHistoryEntry> target_entry;
  215. JS::Handle<Navigable> navigable;
  216. bool update_only;
  217. };
  218. // 11. Let changingNavigableContinuations be an empty queue of changing navigable continuation states.
  219. Queue<ChangingNavigableContinuationState> changing_navigable_continuations;
  220. // 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:
  221. for (auto& navigable : changing_navigables) {
  222. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&] {
  223. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  224. if (navigable->has_been_destroyed())
  225. return;
  226. // 1. Let displayedEntry be navigable's active session history entry.
  227. auto displayed_entry = navigable->active_session_history_entry();
  228. // 2. Let targetEntry be navigable's current session history entry.
  229. auto target_entry = navigable->current_session_history_entry();
  230. // 3. Let changingNavigableContinuation be a changing navigable continuation state with:
  231. auto changing_navigable_continuation = ChangingNavigableContinuationState {
  232. .displayed_document = displayed_entry->document_state->document(),
  233. .target_entry = target_entry,
  234. .navigable = navigable,
  235. .update_only = false
  236. };
  237. // 4. If displayedEntry is targetEntry and targetEntry's document state's reload pending is false, then:
  238. if (displayed_entry == target_entry && !target_entry->document_state->reload_pending()) {
  239. // 1. Set changingNavigableContinuation's update-only to true.
  240. changing_navigable_continuation.update_only = true;
  241. // 2. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  242. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  243. // 3. Abort these steps.
  244. return;
  245. }
  246. // 5. Let oldOrigin be targetEntry's document state's origin.
  247. [[maybe_unused]] auto old_origin = target_entry->document_state->origin();
  248. auto after_document_populated = [target_entry, changing_navigable_continuation, &changing_navigable_continuations]() mutable {
  249. // 1. If targetEntry's document is null, then set changingNavigableContinuation's update-only to true.
  250. if (!target_entry->document_state->document()) {
  251. changing_navigable_continuation.update_only = true;
  252. }
  253. // FIXME: 2. If targetEntry's document's origin is not oldOrigin, then set targetEntry's serialized state to StructuredSerializeForStorage(null).
  254. // FIXME: 3. If all of the following are true:
  255. // 4. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  256. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  257. };
  258. // 6. If targetEntry's document is null, or targetEntry's document state's reload pending is true, then:
  259. if (!target_entry->document_state->document() || target_entry->document_state->reload_pending()) {
  260. // FIXME: 1. Let navTimingType be "back_forward" if targetEntry's document is null; otherwise "reload".
  261. // 2. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  262. auto target_snapshot_params = navigable->snapshot_target_snapshot_params();
  263. // 3. Let potentiallyTargetSpecificSourceSnapshotParams be sourceSnapshotParams.
  264. Optional<SourceSnapshotParams> potentially_target_specific_source_snapshot_params = source_snapshot_params;
  265. // 4. If potentiallyTargetSpecificSourceSnapshotParams is null, then set it to the result of snapshotting source snapshot params given navigable's active document.
  266. if (!potentially_target_specific_source_snapshot_params.has_value()) {
  267. potentially_target_specific_source_snapshot_params = navigable->active_document()->snapshot_source_snapshot_params();
  268. }
  269. // 5. Set targetEntry's document state's reload pending to false.
  270. target_entry->document_state->set_reload_pending(false);
  271. // 6. Let allowPOST be targetEntry's document state's reload pending.
  272. auto allow_POST = target_entry->document_state->reload_pending();
  273. // 7. In parallel, attempt to populate the history entry's document for targetEntry, given navigable, potentiallyTargetSpecificSourceSnapshotParams,
  274. // targetSnapshotParams, with allowPOST set to allowPOST and completionSteps set to queue a global task on the navigation and traversal task source given
  275. // navigable's active window to run afterDocumentPopulated.
  276. 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 {
  277. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [after_document_populated]() mutable {
  278. after_document_populated();
  279. });
  280. })
  281. .release_value_but_fixme_should_propagate_errors();
  282. }
  283. // Otherwise, run afterDocumentPopulated immediately.
  284. else {
  285. after_document_populated();
  286. }
  287. });
  288. }
  289. // FIXME: 13. Let navigablesThatMustWaitBeforeHandlingSyncNavigation be an empty set.
  290. // FIXME: 14. While completedChangeJobs does not equal totalChangeJobs:
  291. while (completed_change_jobs != total_change_jobs) {
  292. // FIXME: 1. If traversable's running nested apply history step is false, then:
  293. // AD-HOC: Since currently populate_session_history_entry_document does not run in parallel
  294. // we call spin_until to interrupt execution of this function and let document population
  295. // to complete.
  296. Platform::EventLoopPlugin::the().spin_until([&] {
  297. return !changing_navigable_continuations.is_empty() || completed_change_jobs == total_change_jobs;
  298. });
  299. if (changing_navigable_continuations.is_empty()) {
  300. continue;
  301. }
  302. // 2. Let changingNavigableContinuation be the result of dequeuing from changingNavigableContinuations.
  303. auto changing_navigable_continuation = changing_navigable_continuations.dequeue();
  304. // 3. If changingNavigableContinuation is nothing, then continue.
  305. // 4. Let displayedDocument be changingNavigableContinuation's displayed document.
  306. auto displayed_document = changing_navigable_continuation.displayed_document;
  307. // 5. Let targetEntry be changingNavigableContinuation's target entry.
  308. auto target_entry = changing_navigable_continuation.target_entry;
  309. // 6. Let navigable be changingNavigableContinuation's navigable.
  310. auto navigable = changing_navigable_continuation.navigable;
  311. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  312. if (navigable->has_been_destroyed())
  313. continue;
  314. // 7. Set navigable's ongoing navigation to null.
  315. navigable->set_ongoing_navigation({});
  316. // 8. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  317. auto history_object_length_and_index = get_the_history_object_length_and_index(target_step);
  318. auto script_history_length = history_object_length_and_index.script_history_length;
  319. auto script_history_index = history_object_length_and_index.script_history_index;
  320. // FIXME: 9. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation.
  321. // 10. Queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
  322. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&, target_entry, navigable, displayed_document, update_only = changing_navigable_continuation.update_only, script_history_length, script_history_index] {
  323. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  324. if (navigable->has_been_destroyed())
  325. return;
  326. // 1. If changingNavigableContinuation's update-only is false, then:
  327. if (!update_only) {
  328. // 1. Unload displayedDocument given targetEntry's document.
  329. displayed_document->unload(target_entry->document_state->document());
  330. // 2. For each childNavigable of displayedDocument's descendant navigables, queue a global task on the navigation and traversal task source given
  331. // childNavigable's active window to unload childNavigable's active document.
  332. for (auto child_navigable : displayed_document->descendant_navigables()) {
  333. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [child_navigable] {
  334. child_navigable->active_document()->unload();
  335. });
  336. }
  337. // 3. Activate history entry targetEntry for navigable.
  338. navigable->activate_history_entry(*target_entry);
  339. }
  340. // FIXME: 2. If targetEntry's document is not equal to displayedDocument, then queue a global task on the navigation and traversal task source given targetEntry's document's
  341. // relevant global object to perform the following step. Otherwise, continue onward to perform the following step within the currently-queued task.
  342. // 3. Update document for history step application given targetEntry's document, targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength, and
  343. // scriptHistoryIndex and entriesForNavigationAPI.
  344. // FIXME: Pass entriesForNavigationAPI
  345. target_entry->document_state->document()->update_for_history_step_application(*target_entry, update_only, script_history_length, script_history_index);
  346. // 4. Increment completedChangeJobs.
  347. completed_change_jobs++;
  348. });
  349. }
  350. // FIXME: 15. Let totalNonchangingJobs be the size of nonchangingNavigablesThatStillNeedUpdates.
  351. // FIXME: 16. Let completedNonchangingJobs be 0.
  352. // FIXME: 17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  353. // FIXME: 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:
  354. // FIXME: 19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.
  355. // 20. Set traversable's current session history step to targetStep.
  356. m_current_session_history_step = target_step;
  357. }
  358. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#clear-the-forward-session-history
  359. void TraversableNavigable::clear_the_forward_session_history()
  360. {
  361. // FIXME: 1. Assert: this is running within navigable's session history traversal queue.
  362. // 2. Let step be the navigable's current session history step.
  363. auto step = current_session_history_step();
  364. // 3. Let entryLists be the ordered set « navigable's session history entries ».
  365. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>&> entry_lists;
  366. entry_lists.append(session_history_entries());
  367. // 4. For each entryList of entryLists:
  368. while (!entry_lists.is_empty()) {
  369. auto& entry_list = entry_lists.take_first();
  370. // 1. Remove every session history entry from entryList that has a step greater than step.
  371. entry_list.remove_all_matching([step](auto& entry) {
  372. return entry->step.template get<int>() > step;
  373. });
  374. // 2. For each entry of entryList:
  375. for (auto& entry : entry_list) {
  376. // 1. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  377. for (auto& nested_history : entry->document_state->nested_histories()) {
  378. entry_lists.append(nested_history.entries);
  379. }
  380. }
  381. }
  382. }
  383. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history-by-a-delta
  384. void TraversableNavigable::traverse_the_history_by_delta(int delta)
  385. {
  386. // FIXME: 1. Let sourceSnapshotParams and initiatorToCheck be null.
  387. // FIXME: 2. If sourceDocument is given, then:
  388. // 3. Append the following session history traversal steps to traversable:
  389. append_session_history_traversal_steps([this, delta] {
  390. // 1. Let allSteps be the result of getting all used history steps for traversable.
  391. auto all_steps = get_all_used_history_steps();
  392. // 2. Let currentStepIndex be the index of traversable's current session history step within allSteps.
  393. auto current_step_index = *all_steps.find_first_index(current_session_history_step());
  394. // 3. Let targetStepIndex be currentStepIndex plus delta
  395. auto target_step_index = current_step_index + delta;
  396. // 4. If allSteps[targetStepIndex] does not exist, then abort these steps.
  397. if (target_step_index >= all_steps.size()) {
  398. return;
  399. }
  400. // 5. Apply the history step allSteps[targetStepIndex] to traversable, with checkForUserCancelation set to true,
  401. // sourceSnapshotParams set to sourceSnapshotParams, and initiatorToCheck set to initiatorToCheck.
  402. apply_the_history_step(all_steps[target_step_index]);
  403. });
  404. }
  405. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#update-for-navigable-creation/destruction
  406. void TraversableNavigable::update_for_navigable_creation_or_destruction()
  407. {
  408. // 1. Let step be traversable's current session history step.
  409. auto step = current_session_history_step();
  410. // 2. Return the result of applying the history step step to traversable given false, false, null, null, and null.
  411. // FIXME: Pass false, false, null, null, and null as arguments.
  412. apply_the_history_step(step);
  413. }
  414. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-reload-history-step
  415. void TraversableNavigable::apply_the_reload_history_step()
  416. {
  417. // 1. Let step be traversable's current session history step.
  418. auto step = current_session_history_step();
  419. // 2. Return the result of applying the history step step to traversable given true, false, null, null, and null.
  420. // FIXME: Pass true, false, null, null, and null as arguments.
  421. apply_the_history_step(step);
  422. }
  423. void TraversableNavigable::apply_the_push_or_replace_history_step(int step)
  424. {
  425. // 1. Return the result of applying the history step step to traversable given false, false, null, null, and null.
  426. // FIXME: Pass false, false, null, null, and null as arguments.
  427. // FIXME: Return result of history application.
  428. apply_the_history_step(step);
  429. }
  430. // https://html.spec.whatwg.org/multipage/document-sequences.html#close-a-top-level-traversable
  431. void TraversableNavigable::close_top_level_traversable()
  432. {
  433. VERIFY(is_top_level_traversable());
  434. // 1. Let toUnload be traversable's active document's inclusive descendant navigables.
  435. auto to_unload = active_document()->inclusive_descendant_navigables();
  436. // FIXME: 2. If the result of checking if unloading is user-canceled for toUnload is true, then return.
  437. // 3. Unload the active documents of each of toUnload.
  438. for (auto navigable : to_unload) {
  439. navigable->active_document()->unload();
  440. }
  441. // 4. Destroy traversable.
  442. destroy_top_level_traversable();
  443. }
  444. // https://html.spec.whatwg.org/multipage/document-sequences.html#destroy-a-top-level-traversable
  445. void TraversableNavigable::destroy_top_level_traversable()
  446. {
  447. VERIFY(is_top_level_traversable());
  448. // 1. Let browsingContext be traversable's active browsing context.
  449. auto browsing_context = active_browsing_context();
  450. // 2. For each historyEntry in traversable's session history entries:
  451. for (auto& history_entry : m_session_history_entries) {
  452. // 1. Let document be historyEntry's document.
  453. auto document = history_entry->document_state->document();
  454. // 2. If document is not null, then destroy document.
  455. if (document)
  456. document->destroy();
  457. }
  458. // 3. Remove browsingContext.
  459. browsing_context->remove();
  460. // FIXME: 4. Remove traversable from the user interface (e.g., close or hide its tab in a tabbed browser).
  461. // 5. Remove traversable from the user agent's top-level traversable set.
  462. user_agent_top_level_traversable_set().remove(this);
  463. }
  464. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-same-document-navigation
  465. 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)
  466. {
  467. // NOTE: This is not in the spec but we should not navigate destroyed navigable.
  468. if (target_navigable->has_been_destroyed())
  469. return;
  470. // FIXME: 1. Assert: this is running on traversable's session history traversal queue.
  471. // 2. If targetNavigable's active session history entry is not targetEntry, then return.
  472. if (target_navigable->active_session_history_entry() != target_entry) {
  473. return;
  474. }
  475. // 3. Let targetStep be null.
  476. Optional<int> target_step;
  477. // 4. Let targetEntries be the result of getting session history entries for targetNavigable.
  478. auto& target_entries = target_navigable->get_session_history_entries();
  479. // 5. If entryToReplace is null, then:
  480. if (!entry_to_replace) {
  481. // 1. Clear the forward session history of traversable.
  482. traversable->clear_the_forward_session_history();
  483. // 2. Set targetStep to traversable's current session history step + 1.
  484. target_step = traversable->current_session_history_step() + 1;
  485. // 3. Set targetEntry's step to targetStep.
  486. target_entry->step = *target_step;
  487. // 4. Append targetEntry to targetEntries.
  488. target_entries.append(target_entry);
  489. } else {
  490. // 1. Replace entryToReplace with targetEntry in targetEntries.
  491. *(target_entries.find(*entry_to_replace)) = target_entry;
  492. // 2. Set targetEntry's step to entryToReplace's step.
  493. target_entry->step = entry_to_replace->step;
  494. // 3. Set targetStep to traversable's current session history step.
  495. target_step = traversable->current_session_history_step();
  496. }
  497. // 6. Apply the push/replace history step targetStep to traversable.
  498. traversable->apply_the_push_or_replace_history_step(*target_step);
  499. }
  500. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  501. void TraversableNavigable::set_system_visibility_state(VisibilityState visibility_state)
  502. {
  503. if (m_system_visibility_state == visibility_state)
  504. return;
  505. m_system_visibility_state = visibility_state;
  506. // When a user-agent determines that the system visibility state for
  507. // traversable navigable traversable has changed to newState, it must run the following steps:
  508. // 1. Let navigables be the inclusive descendant navigables of traversable's active document.
  509. auto navigables = active_document()->inclusive_descendant_navigables();
  510. // 2. For each navigable of navigables:
  511. for (auto& navigable : navigables) {
  512. // 1. Let document be navigable's active document.
  513. auto document = navigable->active_document();
  514. VERIFY(document);
  515. // 2. Queue a global task on the user interaction task source given document's relevant global object
  516. // to update the visibility state of document with newState.
  517. queue_global_task(Task::Source::UserInteraction, relevant_global_object(*document), [visibility_state, document] {
  518. document->update_the_visibility_state(visibility_state);
  519. });
  520. }
  521. }
  522. }