TraversableNavigable.cpp 36 KB

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