-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.bs
2597 lines (2226 loc) · 121 KB
/
index.bs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<pre class='metadata'>
Status: CG-DRAFT
Title: URL Fragment Text Directives
ED: https://wicg.github.io/scroll-to-text-fragment/
Shortname: text-directive
Level: 1
Editor: Nick Burris, Google https://www.google.com, [email protected]
Editor: David Bokan, Google https://www.google.com, [email protected]
Abstract: Text directives add support for specifying a text snippet in the URL
fragment. When navigating to a URL with such a fragment, the user agent
can quickly emphasise and/or bring it to the user's attention.
Group: wicg
Repository: wicg/scroll-to-text-fragment
Markup Shorthands: markdown yes
WPT Display: inline
</pre>
<pre class='link-defaults'>
spec:css-cascade-5; type:dfn; text:computed value
spec:css-display-3; type:value; for:display; text:flex
spec:css-display-3; type:value; for:display; text:grid
spec:css-display-4; type:property; text:display
spec:css-display-4; type:property; text:visibility
spec:dom; type:dfn; for:/; text:element
spec:dom; type:dfn; for:range; text:end
spec:dom; type:dfn; for:range; text:start
spec:dom; type:dfn; text:parent element
spec:dom; type:dfn; text:range
spec:html; type:element; text:link
spec:html; type:element; text:script
spec:html; type:element; text:style
spec:url; type:dfn; text:fragment
</pre>
<pre class="anchors">
spec:html; type:dfn; for:browsing context; text:group; url: https://html.spec.whatwg.org/multipage/browsers.html#tlbc-group
spec:html; type:dfn; for:/; text:navigable; url: https://html.spec.whatwg.org/multipage/document-sequences.html#navigable
spec:html; type:dfn; for:/; text:origin; url: https://html.spec.whatwg.org/multipage/browsers.html#concept-origin
spec:html; type:dfn; text:user navigation involvement; url: https://html.spec.whatwg.org/multipage/browsing-the-web.html#user-navigation-involvement
spec:html; type:dfn; for:document state; text:initiator origin; url: https://html.spec.whatwg.org/multipage/browsing-the-web.html#document-state-initiator-origin
spec:html; type:dfn; for:/; text:document state; url: https://html.spec.whatwg.org/multipage/browsing-the-web.html#she-document-state
spec:html; type:dfn; for:she; text:document; url: https://html.spec.whatwg.org/multipage/browsing-the-web.html#she-document
</pre>
<pre class="biblio">
{
"document-policy": {
"authors": [
"Ian Clelland"
],
"href": "https://wicg.github.io/document-policy",
"title": "Document Policy",
"status": "ED",
"publisher": "W3C",
"deliveredBy": [
"https://www.w3.org/2011/webappsec/"
]
},
"fetch-metadata": {
"authors": [
"Mike West"
],
"href": "https://w3c.github.io/webappsec-fetch-metadata/",
"title": "Fetch Metadata Request Headers",
"status": "WD",
"publisher": "W3C",
"deliveredBy": [
"https://www.w3.org/TR/fetch-metadata/"
]
}
}
</pre>
<style>
.monkeypatch {
color: grey;
}
.monkeypatch .diff {
color: var(--text);
}
</style>
<h2 id=infrastructure>Infrastructure</h2>
<p>This specification depends on the Infra Standard. [[!INFRA]]
# Introduction # {#introduction}
<div class='note'>This section is non-normative</div>
## Use cases ## {#use-cases}
### Web text references ### {#web-text-references}
The core use case for text fragments is to allow URLs to serve as an exact text
reference across the web. For example, Wikipedia references could link to the
exact text they are quoting from a page. Similarly, search engines can serve
URLs that direct the user to the answer they are looking for in the page rather
than linking to the top of the page.
### User sharing ### {#user-sharing}
With text directives, browsers may implement an option to 'Copy URL to here'
when the user opens the context menu on a text selection. The browser can then
generate a URL with the text selection appropriately specified, and the
recipient of the URL will have the specified text conveniently indicated.
Without text fragments, if a user wants to share a passage of text from a page,
they would likely just copy and paste the passage, in which case the receiver
loses the context of the page.
## Link Lifetime ## {#link-lifetime}
This specification attempts to maximize the useful lifetime of text directive links, for example, by
using the actual text content as the URL payload, and allowing a fallback element-id fragment.
However, pages on the web often update and change their content. As such, links like this may "rot"
in that the text content they point to no longer exists on the destination page.
Text directive links can be useful despite this problem. In user sharing use cases, the link is
often transient, intended to be used only within a short time of sending. For longer duration use
cases, such as references and web page links, text directives are still valuable since they degrade
gracefully into an ordinary link. Additionally, the presence of a stale text directive can be useful
information to surface to a user, to help them understand the link creator's original intent and
that the page content may have changed since the link was created.
See [[#generating-text-fragment-directives]] for best practices on how to create robust text
directive links.
# Description # {#description}
## Indication ## {#indication}
<div class='note'>This section is non-normative</div>
This specification intentionally doesn't define what actions a user agent takes
to "indicate" a text match. There are different experiences and trade-offs a
user agent could make. Some examples of possible actions:
* Providing visual emphasis or highlight of the text passage
* Automatically scrolling the passage into view when the page is navigated
* Activating a UA's find-in-page feature on the text passage
* Providing a "Click to scroll to text passage" notification
* Providing a notification when the text passage isn't found in the page
<div class='note'>
The choice of action can have implications for user security and privacy. See
the [[#security-and-privacy]] section for details.
</div>
## Syntax ## {#syntax}
<div class='note'>This section is non-normative</div>
A [=text directive=] is specified in the [=/fragment directive=] (see
[[#the-fragment-directive]]) with the following format:
<pre>
#:~:text=[prefix-,]start[,end][,-suffix]
context |--match--| context
</pre>
<em>(Square brackets indicate an optional parameter)</em>
The text parameters are percent-decoded before matching. Dash (-), ampersand
(&), and comma (,) characters in text parameters are percent-encoded to avoid
being interpreted as part of the text directive syntax.
The only required parameter is <code>start</code>. If only <code>start</code> is specified, the
first instance of this exact text string is the target text.
<div class="example">
<code>#:~:text=an%20example%20text%20fragment</code> indicates that the
exact text "an example text fragment" is the target text.
</div>
If the <code>end</code> parameter is also specified, then the text directive refers to a
range of text in the page. The target text range is the text range starting at
the first instance of <code>start</code>, until the first instance of <code>end</code> that
appears after <code>start</code>. This is equivalent to specifying the entire text range
in the <code>start</code> parameter, but allows the URL to avoid being bloated with a
long text directive.
<div class="example">
<code>#:~:text=an%20example,text%20fragment</code> indicates that the first
instance of "an example" until the following first instance of "text fragment"
is the target text.
</div>
### Context Terms ### {#context-terms}
<div class='note'>This section is non-normative</div>
The other two optional parameters are context terms. They are specified by the
dash (-) character succeeding the prefix and preceding the suffix, to
differentiate them from the <code>start</code> and <code>end</code> parameters, as any
combination of optional parameters can be specified.
Context terms are used to disambiguate the target text fragment. The context
terms can specify the text immediately before (prefix) and immediately after
(suffix) the text fragment, allowing for whitespace.
<div class="note">
While a match succeeds only if the context terms surround the target text
fragment, any amount of whitespace is allowed between context terms and the text
fragment. This allows context terms to cross element boundaries, for example if
the target text fragment is at the beginning of a paragraph and needs
disambiguation by the previous element's text as a prefix.
</div>
The context terms are not part of the targeted text fragment and are not
visually indicated.
<div class="example">
<code>#:~:text=this%20is-,an%20example,-text%20fragment</code> would match
to "an example" in "this is an example text fragment", but not match to "an
example" in "here is an example text".
</div>
### BiDi Considerations ### {#bidi-considerations}
<div class='note'>This section is non-normative</div>
<div class='note'>
See <a
href="https://www.w3.org/International/articles/inline-bidi-markup/uba-basics.en">Unicode
Bidirectional Algorithm basics</a> for a good overview of how Bidirectional
text works.
</div>
Since URL strings are ASCII encoded, they provide no built-in support for
bi-directional text. However, the content that we wish to target on a page can
be LTR (left-to-right), RTL (right-to-left) or both (Bidirectional/BiDi). This
section provides an intuitive description the behavior implicitly described by
the normative sections further in this spec.
The characters of each term in the text fragment are in <em>logical order</em>,
that is, the order in which a native reader would read them in (and also the
order in which characters are stored in memory).
Similarly, the <code>prefix</code> and <code>start</code> terms identify
text coming before another term in logical order, while <code>suffix</code> and
<code>end</code> follow other terms in logical order.
Note: user agents can visually render URLs in a manner friendlier to a native
reader, for example, by converting the displayed string to Unicode. However, the
string representation of a URL remains plain ASCII characters.
<div class="example">
Suppose we want to select the text <code lang="ar">مِصر</code> (Egypt, in Arabic),
that's preceeded by <code lang="ar">البحرين</code> (Bahrain, in Arabic). We would
first percent encode each term:
<code lang="ar">مِصر</code> becomes "%D9%85%D8%B5%D8%B1" (Note: UTF-8 character
[0xD9,0x85] is the first (right-most) character of the Arabic word.)
<code lang="ar">البحرين</code> becomes "%D8%A7%D9%84%D8%A8%D8%AD%D8%B1%D9%8A%D9%86"
The text fragment would then become:
<code>
:~:text=%D8%A7%D9%84%D8%A8%D8%AD%D8%B1%D9%8A%D9%86-,%D9%85%D8%B5%D8%B1
</code>
When displayed in a browser's address bar, the browser can visually render the
text in its natural RTL direction, appearing to the user:
<code>
:~:text=<span lang="ar">البحرين</span>-,<span lang="ar">مِصر</span>
</code>
</div>
## The Fragment Directive ## {#the-fragment-directive}
To avoid compatibility issues with usage of existing URL fragments, this spec
introduces the concept of a <dfn>fragment directive</dfn>. It is the portion of
the URL [=url/fragment=] that follows the [=fragment directive delimiter=] and
may be null if the delimiter does not appear in the fragment.
The <dfn>fragment directive delimiter</dfn> is the string ":~:", that is the
three consecutive code points U+003A (:), U+007E (~), U+003A (:).
<div class="note">
The [=fragment directive=] is part of the URL fragment. This means it
always appears after a U+0023 (#) code point in a URL.
</div>
<div class="example">
To add a [=fragment directive=] to a URL like https://example.com, a fragment
is first appended to the URL: https://example.com#:~:text=foo.
</div>
The fragment directive is parsed and processed into individual
<dfn>directives</dfn>, which are instructions to the user agent to perform some
action. Multiple directives may appear in the fragment directive.
<div class="note">
The only directive introduced in this spec is the text directive but others
could be added in the future.
</div>
<div class="example">
<code>https://example.com#:~:text=foo&text=bar&unknownDirective</code>
<p>Contains 2 text directives and one unknown directive.</p>
</div>
To prevent impacting page operation, it is stripped from script-accessible APIs to prevent
interaction with author script. This also ensures future directives can be added without web
compatibility risk.
### Extracting the fragment directive ### {#extracting-the-fragment-directive}
This section describes the mechanism by which the fragment directive is hidden
from script and how it fits into [[HTML#navigation-and-session-history]].
<div class="note">
The summarized changes in this section:
* Session history entries now include a new "directive state" item
* All new entries are created with a directive state with an empty value. If the new URL includes
a fragment directive it will be written to the state's value (otherwise it remains null).
* Any time a URL potentially including a fragment directive is written to a session history entry,
extract the fragment directive from the URL and store it in a directive state item of the
entry. There are four such points where a URL can potentially include a directive:
* In the "navigate" steps for typical cross-document navigations
* In the "navigate to a fragment" steps for fragment based same-document navigations
* In the "URL and history update steps" for synchronous updates such as
pushState/replaceState.
* In the "create navigation params by fetching" steps for URLs coming from a redirect.
* Same-document navigations that change only the fragment, and the new URL doesn't specify a
directive, will create an entry whose directive state refers to the previous entry's directive
state.
</div>
In [[HTML#session-history-infrastructure]], define [=/directive state=]:
> <strong>Monkeypatching [[HTML#session-history-infrastructure]]:</strong>
>
> <dfn>directive state</dfn> holds the value of the [=fragment directive=] at the time the session
> history entry was created and is used to invoke directives, such as text highlighting, whenever
> the entry is traversed. It has:
> * <dfn for="directive state">value</dfn>, the [=fragment directive=] [=ASCII string=] or null,
> initially null.
>
> A [=/directive state=] may be shared by multiple session history entries.
>
> <div class="note">
> <p>The fragment directive is removed from the URL before the URL is set to the session
> history entry. It is instead stored in the directive state. This prevents it from being
> visible to script APIs so that a directive can be specified without interfering with a
> page's operation.</p>
>
> <p>The fragment directive is stored in the directive state object, rather than a raw string,
> since the same directive state can be shared across multiple contiguous session history
> entries. On a traversal, the directive is only processed (i.e. search text and highlight) if
> the directive state has changed between two entries.</p>
> </div>
To the definition of <a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#session-history-entry">session history entry</a>, add:
> <strong>Monkeypatching [[HTML#session-history-entries]]:</strong>
>
> <div class="monkeypatch">A session history entry is a struct with the following items:
> * ...
> * persisted user state, which is implementation-defined, initially null
> * <span class="diff"><dfn for=she>directive state</dfn>, a [=/directive state=],
> initially a new [=/directive state=]</span>
> </div>
Add a helper algorithm for removing and returning a fragment directive string from a [=/URL=]:
> <strong>Monkeypatching [[HTML]]:</strong>
>
> <div class="note">
> This algorithm makes a URL's fragment end at the [=fragment directive
> delimiter=]. The returned [=/fragment directive=] includes all characters that follow the
> delimiter but does not include the delimiter.
> </div>
>
> <div class="issue">
> TODO: If a URL's fragment ends with ':~:' (i.e. empty directive), this will return null which
> is treated as the URL not specifying an explicit directive (and avoids clobbering an existing
> one. But maybe in this case we should return the empty string? That way a page can explicitly
> clear directives/highlights by navigating/pushState to '#:~:'.
> </div>
>
> To <dfn>remove the fragment directive</dfn> from a [=/URL=] |url|, run these steps:
> 1. Let |raw fragment| be equal to |url|'s [=url/fragment=].
> 1. Let |fragment directive| be null.
> 1. If |raw fragment| is non-null and contains the [=fragment directive delimiter=] as a
> substring:
> 1. Let |position| be the [=string/position variable=] pointing to the first code
> point of the first instance, if one exists, of the [=fragment directive delimiter=] in
> |raw fragment|, or past the end of |raw fragment| otherwise.
> 1. Let |new fragment| be the [=code point substring by positions=] of |raw fragment| from
> the start of |raw fragment| to |position|.
> 1. Advance |position| by the [=string/code point length=] of the [=fragment directive
> delimiter=].
> 1. If |position| does not point past the end of |raw fragment|:
> 1. Set |fragment directive| to the [=code point substring to the end of the string=]
> |raw fragment| starting from |position|
> 1. Set |url|'s [=url/fragment=] to |new fragment|.
> 1. Return |fragment directive|.
>
> <div class="example">
> <code>https://example.org/#test:~:text=foo</code> will be parsed such that
> the fragment is the string "test" and the [=/fragment directive=] is the string
> "text=foo".
> </div>
The next four monkeypatches modify the creation of a session history entry, where the URL might
contain a fragment directive, to remove the fragment directive and store it in the [=/directive
state=].
In the definition of [=navigate=]:
> <strong>Monkeypatching [[HTML#beginning-navigation]]:</strong>
>
> <div class="monkeypatch">To navigate a navigable navigable to a URL |url|...:
> 1. ...
> <li value="14">Set navigable's ongoing navigation to navigationId.</li>
> 15. If url's scheme is "javascript", then...
> 16. In parallel, run these steps:
> 1. ...
> <li value="5">If url is about:blank, then set documentState's origin to documentState's initiator origin.</li>
> 6. Otherwise, if url is about:srcdoc, then set documentState's origin to navigable's parent's active document's origin.
> 7. <strike>Let historyEntry be a new session history entry, with its URL set to url and
> its document state set to documentState.</strike>
> <li value="7"><span class="diff">Let |fragment directive| be the result of running [=remove the
> fragment directive=] on |url|.</span></li>
> 8. <span class="diff">Let |directive state| be a new [=/directive
> state=] with [=directive state/value=] set to |fragment directive|.</span>
> 9. <span class="diff">Let historyEntry be a new session history entry, with its URL
> set to |url|, its document state set to documentState, and its [=she/directive state=]
> set to |directive state|.</span>
> 10. Let navigationParams be null.
> 11. ...
> </div>
In the definition of <a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-fragid">navigate to a fragment</a>:
> <strong>Monkeypatching [[HTML#scroll-to-fragid]]:</strong>
>
> <div class="monkeypatch">To navigate to a fragment given navigable |navigable|, ...:
> 1. <span class="diff">Let |directive state| be navigable's active session history
> entry's [=she/directive state=].</span>
> 1. <span class="diff">Let |fragment directive| be the result of running
> [=remove the fragment directive=] on |url|.</span>
> 1. <span class="diff">If |fragment directive| is not null:</span>
> <div class="note">Otherwise, when only the fragment has changed and it did not specify
> a directive, the active entry's directive state is reused. This prevents a fragment
> change from clobbering highlights.</div>
> 1. <span class="diff">Let |directive state| be a new [=/directive state=] with
> [=directive state/value=] set to |fragment directive|.
> 2. Let historyEntry be a new session history entry, with
> * URL url
> * document state navigable's active session history entry's document state
> * scroll restoration mode navigable's active session history entry's scroll restoration
> mode
> * <span class="diff">[=she/directive state=] |directive state|</span>
> 2. Let entryToReplace be navigable's active session history entry if historyHandling is
> "replace", otherwise null.
> 3. ...
> </div>
In the definition of <a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#url-and-history-update-steps">URL and history update steps</a>:
> <strong>Monkeypatching [[HTML#navigate-non-frag-sync]]:</strong>
>
> <div class="monkeypatch">The URL and history update steps, given a Document |document|, ...:
> 1. Let |navigable| be |document|'s node navigable.
> 2. Let |activeEntry| be |navigable|'s active session history entry.
> 3. <span class="diff">Let |fragment directive| be the result of running [=remove the
> fragment directive=] on |newUrl|.</span>
> 5. Let |historyEntry| be a new session history entry, with
> * URL |newUrl|
> * ...
> * <span class="diff">[=she/directive state=] |activeEntry|'s [=she/directive
> state=]</span>
> 6. If |document|'s is initial about:blank is true, then set historyHandling to "replace".
> 7. If historyHandling is "push", then:
> 1. Increment document's history object's index.
> 2. Set document's history object's length to its index + 1.
> 3. <span class="diff">If |newUrl| does not equal |activeEntry|'s URL with exclude
> fragments set to true OR |fragment directive| is not null, then:</span>
> <div class="note">Otherwise, when only the fragment has changed and it did not specify
> a directive, the active entry's directive state is reused. This prevents a fragment
> change from clobbering highlights.</div>
> 1. <span class="diff">Let |historyEntry|'s [=she/directive state=] be a new
> [=/directive state=] with [=directive state/value=] set to |fragment
> directive|.</span>
> 8. <span class="diff">Otherwise, if |fragment directive| is not null, set
> |historyEntry|'s [=she/directive state=]'s [=directive state/value=] to |fragment
> directive|.</span>
> 9. If serializedData is not null, then restore the history object state given document and
> newEntry.
> </div>
In the definition of <a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching">
create navigation params by fetching</a>:
> <strong>Monkeypatching [[HTML#populating-a-session-history-entry]]:</strong>
>
> <div class="monkeypatch">To create navigation params by fetching given a session history entry
> |entry|, ...:
> 1. Assert: this is running in parallel.
> 1. ...
> <li value="17">Let currentURL be request's current URL.</li>
> 1. Let commitEarlyHints be null.
> 1. While true:
> 1. If request's reserved client is not null and currentURL's origin is not the same as request's reserved client's creation URL's origin, then:
> 1. ...
> <li value="21">Set currentURL to |locationURL|.</li>
> 1. <span class="diff">Let |fragment directive| be the result of running
> [=remove the fragment directive=] on |locationURL|.</span>
> 1. <strike class="diff">Set |entry|'s URL to currentURL.</strike>
> 1. <span class="diff">Set |entry|'s URL to |locationURL|.</span>
> 1. <span class="diff">Set |entry|'s [=she/directive state=]'s [=directive state/value=] to
> |fragment directive|.
> 1. If |locationURL| is a URL whose scheme is not a fetch scheme, then return a new non-fetch
> scheme navigation params, with initiator origin request's current URL's origin
> 1. ...
> </div>
<div class="note">
<p>
Since a Document is populated from a history entry, its [=Document/URL=] will not include the
fragment directive. Similarly, since a window's {{Location}} object is a representation of the
[=/URL=] of the [=active document=], all getters on it will show a fragment-directive-stripped
version of the URL.
</p>
<p>
Additionally, since the {{HashChangeEvent}} is
<a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#updating-the-document">
fired in response to a changed fragment</a> between URLs of session history entries,
<code>hashchange</code> will not be fired if a navigation or traversal changes only the fragment
directive.
</p>
<p>
Some examples are provided to help clarify various edge cases.
</p>
</div>
<div class="example">
```
window.location = "https://example.com#page1:~:hello";
console.log(window.location.href); // 'https://example.com#page1'
console.log(window.location.hash); // '#page1'
```
The initial navigation created a new session history entry. The entry's URL is stripped of the
fragment directive: "https://example.com#page1". The entry's directive state value is set to
"hello". Since the document is populated from the entry, web APIs don't include the fragment
directive in URLs.
```
location.hash = "page2";
console.log(location.href); // 'https://example.com#page2'
```
A same document navigation changed only the fragment. This adds a new session history entry in the
<a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-fragid">navigate to
a fragment</a> steps. However, since only the fragment changed, the new entry's directive state
points to the same state as the first entry, with a value of "bar".
```
onhashchange = () => console.assert(false, "hashchange doesn't fire.");
location.hash = "page2:~:world";
console.log(location.href); // 'https://example.com#page2'
onhashchange = null;
```
A same document navigation changes only the fragment but includes a fragment directive. Since an
explicit directive was provided, the new entry includes its own directive state with a value of
"fizz".
The hashchange event is not fired since the page-visible fragment is unchanged; only the fragment
directive changed. This is because the comparison for hashchange is done on the URLs in the
session history entries, where the fragment directive has been removed.
```
history.pushState("", "", "page3");
console.log(location.href); // 'https://example.com/page3'
```
pushState creates a new session history entry for the same document. However, since the
non-fragment URL has changed, this entry has its own directive state with value currently null.
</div>
<div class="example">
In other cases where a URL is not set to a session history entry, there is no
fragment directive stripping.
For URL objects:
```
let url = new URL('https://example.com#foo:~:bar');
console.log(url.href); // 'https://example.com#foo:~:bar'
console.log(url.hash); // '#foo:~:bar'
document.url = url;
console.log(document.url.href); // 'https://example.com#foo:~:bar'
console.log(document.url.hash); // '#foo:~:bar'
```
The `<a>` or `<area>` elements:
```
<a id='anchor' href="https://example.com#foo:~:bar">Anchor</a>
<script>
console.log(anchor.href); // 'https://example.com#foo:~:bar'
console.log(anchor.hash); // '#foo:~:bar'
</script>
```
</div>
### Applying directives to a document ### {#applying-directives-to-a-document}
The section above described how the [=fragment directive=] is separated from the URL and stored in a
session history entry.
This section defines how and when navigations and traversals make use of history entry's [=she/directive
state=] to apply the directives associated with a session history entry to a [=/Document=].
> <strong>Monkeypatching [[DOM#interface-document]]:</strong>
>
> Each document has an associated <dfn for="Document">pending text directives</dfn> which is either
> null or an <a spec=infra>list</a> of [=text directives=]. It is initially null.
In the definition of <a spec="HTML">update document for history step application</a>:
> <strong>Monkeypatching [[HTML#updating-the-document]]:</strong>
>
> <div class="monkeypatch">To update document for history step application given a Document
> |document|, a session history entry |entry|,...
> 1. ...
> <li value="4">Set |document|'s history object's length to scriptHistoryLength</li>
> 5. If <var ignore>documentsEntryChanged</var> is true, then:
> 1. Let <var ignore>oldURL</var> be |document|'s latest entry's URL.
> 2. <div class="diff">If |document|'s latest entry's [=she/directive state=] is not
> |entry|'s [=she/directive state=] then:
> 1. Let |fragment directive| be |entry|'s [=she/directive state=]'s
> [=directive state/value=].
> 1. Set |document|'s [=Document/pending text directives=] to the result of [=parse the
> fragment directive|parsing=] |fragment directive|.
> </div>
> 3. Set |document|'s latest entry to |entry|
> 4. ...
> </div>
### Fragment directive grammar ### {#fragment-directive-grammar}
Note: This section is non-normative.
Note: This grammar is provided as a convenient reference; however, the rules and steps for parsing
are specified imperatively in the [[#text-directives]] section. Where this grammar differs in
behavior from the steps of that section, the steps there are to be taken as the authoritative source
of truth.
The [=FragmentDirective=] can contain multiple directives split by the "&" character. Currently this
means we allow multiple text directives to enable multiple indicated strings in the page, but this
also allows for future directive types to be added and combined. For extensibility, we do not fail
to parse if an unknown directive is in the &-separated list of directives.
A <a spec=infra>string</a> is a valid fragment directive if it matches the EBNF (Extended
Backus-Naur Form) production:
<dl>
<dt>
<dfn id="fragmentdirectiveproduction">`FragmentDirective`</dfn> `::=`
</dt>
<dd>
<code>([=TextDirective=] | [=UnknownDirective=]) ("&" [=FragmentDirective=])?</code>
</dd>
<dt>
<dfn>`TextDirective`</dfn> `::=`
</dt>
<dd>
<code>"text="[=CharacterString=]</code>
</dd>
<dt>
<dfn>`UnknownDirective`</dfn> `::=`
</dt>
<dd>
<code>[=CharacterString=] - [=TextDirective=]</code>
</dd>
<dt>
<dfn>`CharacterString`</dfn> `::=`
</dt>
<dd>
<code>([=ExplicitChar=] | [=PercentEncodedByte=])*</code>
</dd>
<dt>
<dfn>`ExplicitChar`</dfn> `::=`
</dt>
<dd>
<code>[a-zA-Z0-9] | "!" | "$" | "'" | "(" | ")" | "*" | "+" | "." | "/" | ":" |
";" | "=" | "?" | "@" | "_" | "~" | "," | "-"</code>
<div class = "note">
An [=ExplicitChar=] may be any [=URL code point=] other than "&".
</div>
</dd>
</dl>
A [=TextDirective=] is considered valid if it matches the following production:
<dl>
<dt><dfn>`ValidTextDirective`</dfn> `::=`</dt>
<dd><code>"text=" [=TextDirectiveParameters=]</code></dd>
<dt><dfn>`TextDirectiveParameters`</dfn> `::=`</dt>
<dd>
<code>
([=TextDirectivePrefix=] ",")? [=TextDirectiveString=]
("," [=TextDirectiveString=])? ("," [=TextDirectiveSuffix=])?
</code>
</dd>
<dt><dfn>`TextDirectivePrefix`</dfn> `::=`</dt>
<dd><code>[=TextDirectiveString=]"-"</code></dd>
<dt><dfn>`TextDirectiveSuffix`</dfn> `::=`</dt>
<dd><code>"-"[=TextDirectiveString=]</code></dd>
<dt><dfn>`TextDirectiveString`</dfn> `::=`</dt>
<dd><code>([=TextDirectiveExplicitChar=] | [=PercentEncodedByte=])+</code></dd>
<dt><dfn>`TextDirectiveExplicitChar`</dfn> `::=`</dt>
<dd>
<code>
[a-zA-Z0-9] | "!" | "$" | "'" | "(" | ")" | "*" | "+" | "." | "/" | ":" |
";" | "=" | "?" | "@" | "_" | "~"
</code>
<div class = "note">
A [=TextDirectiveExplicitChar=] is any [=URL code point=] that is not explicitly used in the
[=FragmentDirective=] or [=ValidTextDirective=] syntax, that is "&", "-", and ",". If a text
fragment refers to a "&", "-", or "," character in the document, it will be percent-encoded in
the fragment.
</div>
</dd>
<dt><dfn>`PercentEncodedByte`</dfn> `::=`</dt>
<dd><code>"%" [a-zA-Z0-9][a-zA-Z0-9]</code></dd>
</dl>
## Text Directives ## {#text-directives}
A <dfn>text directive</dfn> is a kind of [=/directive=] representing a range of
text to be indicated to the user. It is a <a spec=infra>struct</a> that consists of
four strings: <dfn for="text directive">start</dfn>,
<dfn for="text directive">end</dfn>,
<dfn for="text directive">prefix</dfn>, and
<dfn for="text directive">suffix</dfn>. [=text directive/start=]
is required to be non-null. The other three items may be set to null,
indicating they weren't provided. The empty string is not a valid value for any
of these items.
See [[#syntax]] for the what each of these components means and how they're
used.
<div algorithm="percent-decode a text directive term">
To <dfn>percent-decode a text directive term</dfn> given an input <a spec=infra>string</a> |term|:
<ol class="algorithm">
1. If |term| is null, return null.
1. <a spec=infra>Assert</a>: |term| is an <a spec=infra>ASCII string</a>.
1. Let |decoded bytes| be the result of <a spec=url for=string
lt="percent-decode">percent-decoding</a> |term|.
1. Return the result of running <a spec=encoding>UTF-8 decode without BOM</a> on |decoded
bytes|.
</ol>
</div>
<div algorithm="parse a text directive">
To <dfn>parse a text directive</dfn>, on an <a spec="infra">string</a> |text
directive value|, run these steps:
<div class="note">
<p>
This algorithm takes a single text directive value string as input (e.g. "prefix-,foo,bar") and
attempts to parse the string into the components of the directive (e.g. ("prefix", "foo", "bar",
null)). See [[#syntax]] for the what each of these components means and how they're used.
</p>
<p>
Returns null if the input is invalid. Otherwise, returns a [=text directive=].
</p>
</div>
<ol class="algorithm">
1. Let |prefix|, |suffix|, |start|, |end|, each be null.
1. <a spec="infra">Assert</a>: |text directive value| is an <a spec="infra">ASCII string</a>
with no code points in the <a spec="URL">fragment percent-encode set</a> and no instances of
U+0026 (&).
1. Let |tokens| be a <a for=/>list</a> of <a spec="infra">strings</a> that result from
<a lt="strictly split a string">strictly splitting</a> |text directive value| on U+002C (,).
1. If |tokens| has <a for=list>size</a> less than 1 or greater than 4, return null.
1. If the first item of |tokens| <a spec=infra for=string>ends with</a> U+002D (-):
1. Set |prefix| to the <a spec=infra lt="code point substring">substring</a> of |tokens|[0]
from 0 with length |tokens|[0]'s <a spec=infra for=string lt="code point
length">length</a> - 1.
1. Remove the first item of |tokens|.
1. If |prefix| is the empty string or contains any instances of U+002D (-), return null.
1. If |tokens| is <a spec="infra" for="list">empty</a>, return null.
1. If the last item of |tokens| <a spec=infra for=string>starts with</a> U+002D (-):
1. Set |suffix| to the <a spec=infra lt="code point substring to the end of the
string">substring</a> of the last item of |tokens| from 1 to the end of the string.
1. Remove the last item of |tokens|.
1. If |suffix| is the empty string or contains any instances of U+002D (-), return null.
1. If |tokens| is <a spec="infra" for="list">empty</a>, return null.
1. If |tokens| has <a spec=infra for=list>size</a> greater than 2, return null.
1. <a spec=infra>Assert</a>: |tokens| has <a spec=infra for=list>size</a> 1 or 2.
1. Set |start| to the first item in |tokens|.
1. Remove the first item in |tokens|.
1. If |start| is the empty string or contains any instances of U+002D (-), return null.
1. If |tokens| is not <a spec=infra for=list>empty</a>:
1. Set |end| to the first item in |tokens|.
1. If |end| is the empty string or contains any instances of U+002D (-), return null.
1. Return a new [=text directive=], with
<dl class="props">
<dt>[=text directive/prefix=]</dt>
<dd>The [=percent-decode a text directive term|percent-decoding=] of |prefix|</dd>
<dt>[=text directive/start=]</dt>
<dd>The [=percent-decode a text directive term|percent-decoding=] of |start|</dd>
<dt>[=text directive/end=]</dt>
<dd>The [=percent-decode a text directive term|percent-decoding=] of |end|</dd>
<dt>[=text directive/suffix=]</dt>
<dd>The [=percent-decode a text directive term|percent-decoding=] of |suffix|</dd>
</dl>
</ol>
</div>
<div algorithm="parse the fragment directive">
To <dfn>parse the fragment directive</dfn>, an an <a spec="infra">ASCII string</a> |fragment
directive|, run these steps:
<div class="note">
This algorithm takes the fragment directive string (i.e. the part that follows ":~:") and returns
a list of [=text directive=] objects parsed from that string. Can return an empty list.
</div>
<ol class="algorithm">
1. Let |directives| be the result of <a spec="infra" lt="strictly split a string">strictly
splitting</a> |fragment directive| on U+0026 (&).
1. Let |output| be an initially empty <a spec="infra">list</a> of [=text directives=].
1. <a spec="infra" for="list">For each</a> <a spec="infra">string</a> |directive| in |directives|:
1. If |directive| does not <a spec="infra" lt="starts with" for="string">start with</a>
"<code>text=</code>", then <a spec="infra" for="iteration">continue</a>.
1. Let |text directive value| be the <a spec="infra" lt="code point substring to the end of
the string">code point substring</a> from 5 to the end of |directive|.
<div class="note">Note: this may be the empty string.</div>
1. Let |parsed text directive| be the result of [=parse a text directive|parsing=] |text
directive value|.
1. If |parsed text directive| is non-null, <a spec="infra" for="list">append</a> it to
|output|.
1. Return |output|.
</ol>
</div>
### Invoking Text Directives ### {#invoking-text-directives}
This section describes how text directives in a document's [=Document/pending text directives=] are
processed and invoked to cause indication of the relevant text passages.
<div class="note">
The summarized changes in this section:
* Modify the indicated part processing model to try processing [=Document/pending text directives=]
into a [=range=] that will be returned as the indicated part.
* Modify "scrolling to a fragment" to correctly scroll and set the Document's target element in the case
of a [=range=] based indicated part.
* Ensure [=Document/pending text directives=] is reset to null when the user agent has finished the
fragment search for the current navigation/traversal.
* If the user agent finishes searching for a text directive, ensure it tries the regular
fragment as a fallback.
</div>
In <a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-indicated-part-of-the-document">
indicated part</a>, enable a fragment to indicate a [=range=]. Make the following changes:
> <strong>Monkeypatching [[HTML#scrolling-to-a-fragment]]:</strong>
>
> <div class="monkeypatch">
> For an HTML document |document|, the following processing model must be followed to determine
> its indicated part:
>
> 1. <span class="diff">Let |text directives| be the document's [=Document/pending text directives=].
> </span>
> 1. <span class="diff">If |text directives| is non-null then:</span>
> 1. <span class="diff">Let |ranges| be a <a spec=infra>list</a> that is the result of running
> the [=invoke text directives=] steps with |text directives| and the document.</span>
> 1. <span class="diff">If |ranges| is non-empty, then:</span>
> 1. <span class="diff">Let |firstRange| be the first item of |ranges|.</span>
> 1. <span class="diff">Visually indicate each [=range=] in |ranges| in an
> [=implementation-defined=] way. The indication must not be observable from author
> script. See [[#indicating-the-text-match]].</span>
> <div class="note">
> The first [=range=] in |ranges| is the one that gets scrolled into view but all
> ranges should be visually indicated to the user.
> </div>
> 1. <span class="diff">Set |firstRange| as |document|'s indicated part, return.</span>
> 1. Let fragment be document's URL's fragment.
> 1. If fragment is the empty string, then return the special value top of the document.
> 1. Let potentialIndicatedElement be the result of finding a potential indicated element given
> document and fragment.
> 1. ...
>
> </div>
In <a spec=HTML>scroll to the fragment</a>, handle an indicated part that is a [=range=] and also
prevent fragment scrolling if the force-load-at-top policy is enabled. Make the following changes:
> <strong>Monkeypatching [[HTML#scrolling-to-a-fragment]]:</strong>
>
> <div class="monkeypatch">
> 1. If document's indicated part is null, then set document's target element to null.
> 2. Otherwise, if document's indicated part is top of the document, then:
> 1. Set document's target element to null.
> 2. Scroll to the beginning of the document for document.
> 3. Return.
> 3. Otherwise:
> 1. Assert: document's indicated part is an element <span class="diff">or it is a [=range=].</span>
> 2. <span class="diff">Let |scrollTarget| be |document|'s indicated part.</span>
> 3. <span class="diff">Let |target| be |scrollTarget|.</span>
> 4. <span class="diff">If |target| is a [=range=], then:</span>
> 1. <span class="diff">Set |target| to be the [=first common ancestor=] of |target|'s
> [=range/start node=] and [=range/end node=].</span>
> 2. <span class="diff">While |target| is non-null and is not an [=element=], set |target| to
> |target|'s [=tree/parent=].</span>
> <div class="issue">
> What should be set as target if inside a shadow tree?
> <a href="https://github.com/WICG/scroll-to-text-fragment/issues/190">#190</a>
> </div>
> 5. <span class="diff">Assert: |target| is an [=element=].</span>
> 6. Set |document|'s target element to |target|.
> 7. Run the ancestor details revealing algorithm on |target|.
> 8. Run the ancestor hidden-until-found revealing algorithm on |target|.
> <div class="issue">
> These revealing algorithms currently wont work well since |target| could be an
> ancestor or even the root document node. Issue
> <a href="https://github.com/WICG/scroll-to-text-fragment/issues/89">#89</a> proposes
> restricting matches to `contain:style layout` blocks which would resolve this
> problem.
> </div>
> 9. <span class="diff">Let |blockPosition| be "center" if |scrollTarget| is a [=range=],
> "start" otherwise.</span>
> <div class="note">
> Scrolling to a text directive centers it in the block flow direction.
> </div>
> 10. <strike class="diff">Scroll |target| into view, with behavior set to "auto", block set to
> "start", and inline set to "nearest".</strike>
>
> <li value="10"><span class="diff">[=scroll a target into view=],
> with <em>target</em> set to |scrollTarget|, <em>behavior</em> set to "auto",
> <em>block</em> set to |blockPosition|, and <em>inline</em> set to "nearest".</span>
>
> <span class="diff">Implementations MAY avoid scrolling to the target if it is
> produced from a [=text directive=].</span></li>
> 11. Run the focusing steps for target, with the Document's viewport as the fallback target.
> <div class="issue">Implementation note: Blink doesn’t currently set focus for text
> fragments, it probably should? TODO: file crbug.</div>
> 12. Move the sequential focus navigation starting point to target.
>
> </div>
The next two monkeypatches ensure the user agent clears [=Document/pending text directives=] when
the fragment search is complete. In the case where a text directive search finishes because parsing
has stopped, it tries one more search for a non-text directive fragment.
In the definition of <a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#try-to-scroll-to-the-fragment">
try to scroll to the fragment</a>:
> <strong>Monkeypatching [[HTML#scrolling-to-a-fragment]]:</strong>
>
> <div class="monkeypatch">
> To try to scroll to the fragment for a Document |document|, perform the following steps in
> parallel:
> 1. Wait for an implementation-defined amount of time. (This is intended to allow the user agent
> to optimize the user experience in the face of performance concerns.)
> 2. Queue a global task on the navigation and traversal task source given document's relevant
> global object to run these steps:
> 1. <strike class="diff">If document has no parser, or its parser has stopped parsing, or the user agent
> has reason to believe the user is no longer interested in scrolling to the fragment, then
> abort these steps.</strike>
> <li value="1" class="diff">If the user agent has reason to believe the user is no longer interested in scrolling to
> the fragment, then:</span>
> 1. <span class="diff">Set [=Document/pending text directives=] to null.</span>
> 1. <span class="diff">Abort these steps.</span>
> 1. <span class="diff">If the document has no parser, or its parser has stopped parsing,
> then:</li>
> 1. <span class="diff">If [=Document/pending text directives=] is not null, then:</span>
> 1. <span class="diff">Set [=Document/pending text directives=] to null.</span>
> 1. <span class="diff"><a spec=HTML>Scroll to the fragment</a> given |document|.</span>
> 1. <span class="diff">Abort these steps.</span>
> 2. Scroll to the fragment given document.
> 3. If document's indicated part is still null, then try to scroll to the fragment for
> document. <span class="diff">Otherwise, set [=Document/pending text directives=] to
> null.</span>
In the definition of
<a href="https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-fragid">
navigate to a fragment</a>:
> <strong>Monkeypatching [[HTML#scroll-to-fragid]]:</strong>
>