forked from w3c/edit-context
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1274 lines (1178 loc) · 66.5 KB
/
index.html
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
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>EditContext API</title>
<script src='https://www.w3.org/Tools/respec/respec-w3c' defer class='remove'></script>
<script class='remove'>
var respecConfig = {
github: "w3c/edit-context"
,specStatus: "ED"
,shortName: "edit-context"
,editors: [{ name: "Shih-ling Keng",
mailto: "shihken@microsoft.com",
company: "Microsoft",
w3cid: 126951},
{ name: "Anupam Snigdha",
mailto: "snianu@microsoft.com",
company: "Microsoft",
w3cid: 126950},
{ name: "Bo Cupp",
mailto: "pcupp@microsoft.com",
company: "Microsoft",
w3cid: 126951},
{ name: "Dan Clark",
mailto: "daniec@microsoft.com",
company: "Microsoft",
w3cid: 113024},]
, wgPublicList: "public-editing-tf"
, otherLinks: [{
key: 'Participate',
data: [{
value: 'We are on GitHub.',
href: 'https://github.com/w3c/edit-context'
}, {
value: 'File a bug.',
href: 'https://github.com/w3c/edit-context/issues'
}, {
value: 'Commit history.',
href: 'https://github.com/w3c/edit-context/commits/gh-pages'
}, {
value: 'Mailing list.',
href: 'http://lists.w3.org/Archives/Public/public-editing-tf/'
}]
}]
, group: "webediting"
, edDraftURI: "https://w3c.github.io/edit-context/"
, xref: ["WebIDL"
, "DOM"
, "HTML"
, "geometry-1"
, "uievents"
, "infra"
, "input-events"]
};
</script>
</head>
<body>
<section id='abstract'>
<p>The {{EditContext}} is a new API that allows authors to more directly participate in the text input process.</p>
</section>
<section id='sotd'>
<p>
</p>
</section>
<section>
<h2>Introduction</h2>
<section id="background" class="informative">
<h3>Background and Motivation</h3>
<p>Modern operating systems provide mechanisms to produce text in a variety of ways: speech-to-text, virtual keyboards, handwriting recognition and many more. When an app wants to consume text input from these various sources, it must first provide a view of its currently editable text to the operating system. The view of editable text provides a common language that apps (having a variety of different document models) and sources of text (having a variety of different input methods) can both understand. Both the apps and input sources communicate with one another by expressing their desired changes to the state of the common view as an event that the other can handle to facilitate the text input process.</p>
<p>For the purposes of this document, a producer of text is known as a <dfn>Text Input Method</dfn>. The view provided by an app which wants to consume text is called a <dfn>Text Edit Context</dfn>. The service provided by the OS to facilitate the editing of text in the [=Text Edit Context=] by the [=Text Input Methods=] is called a <dfn>Text Input Service</dfn>.</p>
<figure id="many-input-methods">
<img src="images/many-input-methods.jpg" alt="">
<figcaption>Many [=Text Input Methods=] using a [=Text Input Service=] to communicate with many apps through their [=Text Edit Contexts=].</figcaption>
</figure>
<p>Here’s a typical flow for the text input process in more detail:</p>
<ol>
<li>A user places focus into an editable region of the app.</li>
<li>The app produces a [=Text Edit Context=] describing its editable region according to the standards set forth by the [=Text Input Service=] and provides that [=Text Edit Context=] to the [=Text Input Service=].</li>
<li>The [=Text Input Service=] triggers a [=Text Input Method=] to provide some user interface for capturing text input from the user and provides the [=Text Input Method=] the app generated [=Text Edit Context=].</li>
<li>The [=Text Input Method=] reads the location of selection and nearby text from the [=Text Edit Context=] to help tailor its user experience.</li>
<li>The [=Text Input Method=] may also read screen coordinates for where the selection and editable region are located so that it can properly position its user interface next to the text being edited.</li>
<li>The user interacts with the [=Text Input Method=] user interface to input text in some [=Text Input Method=]-specific way.</li>
<li>The [=Text Input Method=] describes its desired modifications to the text and selection in the [=Text Edit Context=] in response to the user’s input.</li>
<li>The app handles an event describing the desired modifications to its [=Text Edit Context=] and renders the result to the user.</li>
</ol>
<figure id="text-input-process">
<img src="images/text-input-process.jpg" alt="">
<figcaption>A sequence diagram illustrating a typical flow for text input.</figcaption>
</figure>
<p>Existing user agents handle the details of this text input process so that the author’s responsibility ends at declaring what elements of the document represent an editable region. Authors express which regions are editable using input elements, textarea elements, contenteditable elements, or by setting the {{Document/designMode}} attribute to "<code>on</code>" to mark an entire document as editable. </p>
<p>As an editable region of the document is <a href="https://html.spec.whatwg.org/multipage/interaction.html#focused">focused</a>, the user agent automatically produces the [=Text Edit Context=] from the contents of the editable region and the position of the selection within it. When a [=Text Input Method=] produces text, the user agent translates the events against its [=Text Edit Context=] into a set of DOM and style modifications – only some of which are described using existing events that an author can handle. </p>
<p>Authors that want to produce sophisticated editing experiences may be challenged by the current approach. If, for example, the text and selection are rendered to a canvas, user agents are unable to produce a [=Text Edit Context=] to drive the text input process. Authors compensate by resorting to offscreen editable elements, but this approach comes with negative implications for accessibility, it deteriorates the input experience, and requires complex code to synchronize the position of the text in the offscreen editable element with the corresponding text in the canvas. </p>
<p>With the introduction of this EditContext API, authors can more directly participate in the protocol for text input and avoid the pitfalls described above.</p>
</section>
<section id="editcontext-model">
<h3>The EditContext Model</h3>
<p>
The [=Text Input Service=] and [=Text Edit Context=] are abstractions representing the common aspects of text input across many operating systems.
An {{EditContext}} is a JavaScript reflection of the [=Text Edit Context=].
When changes are made to the [=Text Edit Context=] by the [=Text Input Service=], those changes are reflected to the author asynchronously in the form of events which are dispatched against the [=active EditContext=].
When the author makes changes to the [=active EditContext=], those changes will be reflected in the [=Text Edit Context=] during the next lifecycle update.
</p>
<h4>EditContext state</h4>
<p>
Both the [=Text Edit Context=] and {{EditContext}} have a [=text state=] which holds the information exchanged in the aforementioned updates. The <dfn>text state</dfn> consists of:
</p>
<ul>
<li><dfn>text</dfn> which is a {{DOMString}} representing editable content. The initial value is the empty string.</li>
<li><dfn>selection start</dfn> which refers to the offset in [=text=] where the selection starts. The initial value is 0.</li>
<li><dfn>selection end</dfn> which refers to the offset in [=text=] where the selection ends. The initial value is 0. [=selection end=] may be less than [=selection start=] in the case of a "backwards" selection (in reverse of document order).</li>
<li><dfn>is composing</dfn> which indicates if there is an active composition. The initial value is false.</li>
<li><dfn>composition start</dfn> which refers to the offset in [=text=] representing the start position of the text being actively composed. The initial value is 0.</p></li>
<li><dfn>composition end</dfn> which refers to the offset in [=text=] representing the end position of the text being actively composed. The initial value is 0. [=composition end=] must always be greater than or equal to [=composition start=].</li>
<li><dfn>text formats</dfn> which is an array of [=text format=]. The array is initially empty.</li>
<li><dfn>control bounds</dfn> is a {{DOMRect}} describing the area of the viewport in which [=text=] is displayed. It is in the [=client coordinate system=] and the initial x, y, width, and height are all 0.</li>
<li><dfn>selection bounds</dfn> is a {{DOMRect}} describing the position of selection. It is in the [=client coordinate system=] and the initial x, y, width, and height are all 0.</li>
<li><dfn>codepoint rects start index</dfn> which is an offset into [=text=] that respresents the position before the first codepoint whose location is reported by the first member of [=codepoint rects=] array.</li>
<li><dfn>codepoint rects</dfn> is an array of {{DOMRect}} defining the bounding box of each codepoint. The array is initially empty.</li>
</ul>
<p><dfn>text format</dfn> is a struct that indicates decorative properties that should be applied to the ranges of [=text=]. The struct contains:</p>
<ul>
<li><dfn>range start</dfn> which is an offset into [=text=] that respresents the position before the first codepoint that should be decorated.</li>
<li><dfn>range end</dfn> which is an offset into [=text=] that respresents the position after the last codepoint that should be decorated.</li>
<li><dfn>underline style</dfn>, a {{UnderlineStyle}} which is the preferred underline style of the decorated [=text=] range.</li>
<li><dfn>underline thickness</dfn>, a {{UnderlineThickness}} which is the preferred underline thickness of the decorated [=text=] range.</li>
</ul>
<p class="note">
[=Codepoint rects=] provides the means for the user agent to query a range of
[=text=] for positioning information. The [=Text Input Service=] will use this
information, in tandem with the [=control bounds=] and [=selection bounds=], to
support the Text Input Method in properly displaying its user interface. For example,
the info can be used to position an IME window adjacent to text being composed.
Different platforms may require different positions to be cached to fulfill queries
from the [=Text Input Service=]. The user agent will indicate which positions are
required by firing {{CharacterBoundsUpdateEvent}}.
</p>
<p>
[=Control bounds=], [=selection bounds=], and [=codepoint rects=] are given in the
<dfn>client coordinate system</dfn>, which is defined as a two-dimensional Cartesian
coordinate system (x, y) where the origin is the top-left corner of the
<a href="https://drafts.csswg.org/cssom-view/#layout-viewport">layout viewport</a>,
the x-axis points towards the top-right of the
<a href="https://drafts.csswg.org/cssom-view/#layout-viewport">layout viewport</a>,
and the y-axis points towards the bottom-left of the
<a href="https://drafts.csswg.org/cssom-view/#layout-viewport">layout viewport</a>.
The units of the client coordinate system are
<a href="https://drafts.csswg.org/css-values/#px">CSS pixels</a>.
</p>
<div class="note">
<p>
Since EditContext bounds are defined in
<a data-lt="client coordinate system">client coordinates</a>, the coordinates
indicating a given piece of content on a page will change as the user scrolls the
document even if the content itself does not change position in the document. A
scenario where authors may want to take this into account is the case where the user
scrolls the page where the user has an active composition. If the author does not
update the EditContext's bounds information (e.g. during a scroll event listener),
the IME window may no longer line up with the text being composed for the duration
of the composition.
</p>
<p>
However, some platforms do not adjust IME windows during an active composition,
so updating bounds information mid-composition does not guarantee that the IME
window will be repositioned until it's closed and reopened.
</p>
</div>
<h4>Association and activation</h4>
<p>
An {{EditContext}} has an <dfn data-for="edit-context">associated element</dfn>, an {{HTMLElement}}.
An element becomes an {{EditContext}}'s <a>associated element </a>by assigning
the {{EditContext}} to the element's {{HTMLElement/editContext}} property.
An {{HTMLElement}} can be <a data-lt="associated element">associated</a> with at most one {{EditContext}}.
</p>
<p class="note">
An {{EditContext}} keeps its [=associated element=] alive, so developers
should be aware that assigning an {{EditContext}} to an element's
{{HTMLElement/editContext}} property will prevent the element from being garbage
collected until the property is cleared or the {{EditContext}} is garbage collected.
</p>
</p>
<p>
If an {{EditContext}}'s <a>associated element</a>'s
<a href="https://dom.spec.whatwg.org/#concept-tree-parent">parent</a> is not
<a href="https://w3c.github.io/editing/docs/execCommand/#editable">editable</a> and
is not a [=Document=] whose {{Document/designMode}} attribute is "<code>on</code>",
then the <a>associated element</a> becomes an <dfn class="export">EditContext editing host</dfn>.
An <a>EditContext editing host</a> is a type of [=editing host=] whose behaviors
are described in [[[#edit-context-differences]]].
</p>
<div class="note">
<p>
There are a couple implications of this. Firstly, if an element that is already
an [=editing host=] due to [^html-global/contenteditable^]
becomes an {{EditContext}}'s <a>associated element</a>, then that element
becomes an <a>EditContext editing host</a>. In other words, if both {{EditContext}}
and [^html-global/contenteditable^] are set on an element, the EditContext
behavior "wins".
</p>
<p>
Secondly, if an element is
<a href="https://w3c.github.io/editing/docs/execCommand/#editable">editable</a>
but not an [=editing host=] (i.e. it is a child in the subtree of an
[=editing host=]), then becoming an {{EditContext}}'s <a>associated element</a>
has no effect on that element. This is analogous to the behavior of
[^html-global/contenteditable^], where setting [^html-global/contenteditable^]
to "<code>true</code>" on an
<a href="https://w3c.github.io/editing/docs/execCommand/#editable">editable</a>
element that is not an [=editing host=] has no effect. Taken together, these
rules imply that an editable tree of nodes will follow either the
{{EditContext}} behavior or non-{{EditContext}} behavior, but the behaviors
cannot be mixed.
</p>
</div>
<p>
A {{Document}} has an <dfn>active EditContext</dfn>, which may be null.
</p>
<p class="issue">
The following paragraph can be removed once the behavior change lands
in [[input-events]].
</p>
<p>
When an [=EditContext editing host=] receives text input from the
[=Text Input Service=], as the
<a href="https://www.w3.org/TR/uievents/#default-action">default action</a> for the
<a href="https://www.w3.org/TR/uievents/#event-type-beforeinput">beforeinput</a>
event fired as a result of that input the user agent must run
[=Handle Input for EditContext=] given the [=EditContext editing host=] .
</p>
<h4 id="edit-context-differences">Differences for an EditContext editing host</h4>
<p>
<p>
In many ways, an <a>EditContext editing host</a> behaves in the same way as other types of [=editing host=],
e.g. for a [^html-global/contenteditable^] element. Notable similarities include:
</p>
<ul>
<li>
Each child node of the <a>EditContext editing host</a> becomes <a href="https://w3c.github.io/editing/docs/execCommand/#editable">editable</a>,
unless that node has a [^html-global/contenteditable^] attribute set to "<code>false</code>".
</li>
<li>The user agent handles focus and caret navigation for any editable element in the <a>EditContext editing host</a>.</li>
<li>
The <a>EditContext editing host</a> receives key events and the <a href="https://www.w3.org/TR/uievents/#event-type-beforeinput">beforeinput</a>
event as specified in [[uievents]].
</li>
</ul>
<p>
There are also some ways that an <a>EditContext editing host</a>
differs from other types of [=editing hosts=]:
</p>
<ul>
<li>
When the {{Document}} being edited has an [=active EditContext=], the user agent must not update the DOM
as a direct result of a user action in the <a>EditContext editing host</a>
(e.g., keyboard input in an editable region, deleting or formatting text, ...).
</li>
<li>
When the {{Document}} being edited has an [=active EditContext=], the user agent must not fire the
<a href="https://www.w3.org/TR/uievents/#event-type-input">input</a> event
against the <a>EditContext editing host</a> as a direct result of user action
event as specified in [[uievents]].
</li>
</ul>
</p>
<h4>EditContext events</h4>
<p>
The user agent fires several types of events against the {{EditContext}} in order to
inform the author when they must update the state of the DOM in response to changes
from the [=Text Input Service=], or respond to a query from the [=Text Input Service=].
Since the timings of [=Text Input Service=]s are platform-specific, authors should
avoid taking dependencies on the timing of these events.
</p>
<ul>
<li>
The user agent must fire {{TextUpdateEvent}} when the [=Text Input Service=] indicates
that the user has made changes to the text, the selection, or the composition range
properties of the EditContext. When the author receives this event, they must render
the changes back to the page's view so the user can see what they are typing.
</li>
<li>
The user agent must fire {{TextFormatUpdateEvent}} when the [=Text Input Service=]
indicates that certain formats should be applied to the text being composed. When
the author receives this event, they must render the formatting change back to
the page's view to aid the user with their IME composition.</li>
<li>
<p>
The user agent must fire {{CharacterBoundsUpdateEvent}} when the
[=Text Input Service=] indicates that it requires character bounds information
to support the [=Text Input Method=] in properly displaying its user interface.
After receiving {{CharacterBoundsUpdateEvent}}, the author must compute the
requested character bounds and call {{EditContext/updateCharacterBounds}} to
update the character bounds in the EditContext's [=text state=]. The author
should perform the {{EditContext/updateCharacterBounds}} call synchronously
within the {{CharacterBoundsUpdateEvent}} event handler if possible; if not,
it is permissible to call it asynchronously.
Upon receiving {{EditContext/updateCharacterBounds}}, the user agent must
pass the character bounds information on to the [=Text Input Service=].
</p>
<p class="note">
The longer the author delays the {{EditContext/updateCharacterBounds}} call,
the higher the likelihood that the user will observe a visual stutter as the
IME window repositions itself in the middle of a composition.
</p>
</li>
</ul>
<h4>Event loop changes</h4>
<p>
A new step will be introduced as a substep within the [=Update the rendering=] step
in the HTML Event Loops Processing Model, immediately following step 15 (which runs
the focusing steps for {{Document}}s whose
<a href="https://html.spec.whatwg.org/#focused-area-of-the-document">focused area</a>s
become non-focusable). The step is: For each
<a href="https://html.spec.whatwg.org/multipage/document-sequences.html#fully-active">fully active</a>
{{Document}} |doc|, [=queue a global task=] on the [=DOM manipulation task source=]
given |doc|'s [=relevant global object=] to run
the [=Update the Text Edit Context=] steps given |doc|.
</p>
<section id="examples" class="informative">
<h4>Examples</h4>
<p>Using an {{EditContext}}, an author can mark a region of the document editable by <a data-lt="associated element">associating</a> an {{EditContext}} object with an element as shown in the example below: </p>
<aside class="example" title="Associate an EditContext with an Element">
<pre><xmp><script type="module">
let canvas = document.querySelector("canvas")
canvas.editContext = new EditContext()
// When the associated element is focused, the EditContext is automatically activated.
canvas.focus();
</script>
<canvas></canvas></xmp></pre></aside>
<p>In the example below, the author is using a canvas to draw an editable region that allows the user to input a single line of text rendered with a monospace font. The text for the editable region is maintained by the author as a String. The text offsets for the selection in the editable region are maintained by the author as a pair of Numbers: selectionStart and selectionEnd. The Numbers refer to the count of the number of UTF-16 codepoints to the left of the start and end of the selection respectively. For the sake of communicating the bounding boxes for the current selection and the editable region of the document to Text Input Services, the author also computes the bounding rectangle in CSS pixels for the selection and the editable region of the document. The offset of the rectangle is expressed relative to the origin of the canvas element since that is the element to which the author has <a data-lt="associated element">associated</a> an EditContext. Since the model for the author’s representation of text and selection location matches the form expected by the EditContext API, the author can simply assign those properties to the EditContext <a data-lt="associated element">associated</a> with the canvas whenever those values change. </p>
<aside class="example" title="Using EditContext with editing model, view, and controller">
<pre><xmp><script type="module">
// This example is built on top of example 1.
// Only the added logic is shown here for brevity.
class EditingModel {
constructor(text, selectionStart, selectionEnd) {
this.text = text
this.selectionStart = selectionStart
this.selectionEnd = selectionEnd
}
}
class EditingView {
constructor(canvas, model) {
this.canvas = canvas
this.model = model
}
render() {
// render the text
let canvasContext2D = this.canvas.getContext("2d");
canvasContext2D.strokeText(this.model.text);
// render the selection (implementation omitted for brevity)
}
computeSelectionBound() {
// implementation omitted for brevity
}
computeControlBound() {
// implementation omitted for brevity
}
}
class EditingController {
constructor(model, view, editContext) {
this.view = view
this.model = model
this.editContext = editContext
}
render() {
view.render()
// keep EditContext in sync, which essentially means
// rendering the plain text view of the model.
let editContext = this.canvas.editContext
this.editContext.updateText(0, this.model.text.length, this.model.text)
this.editContext.updateSelection(this.model.selectionStart, this.model.selectionEnd)
let selectionBounds = view.computeSelectionBound()
let controlBounds = view.computeControlBound()
// These bounds have x, y, width and height members
// so they can be assigned directly to EditContext.
editContext.updateSelectionBounds(selectionBounds)
editContext.updateControlBounds(controlBounds)
}
}
let canvas = document.querySelector("canvas")
canvas.editContext = new EditContext()
let editingModel = new EditingModel("", 0, 0, 0, 0)
let editingView = new EditingView(canvas, editingModel)
let editingController = new EditingController(editingModel,
editingView, canvas.editContext);
editingController.render()
</script>
<canvas></canvas></xmp></pre>
</aside>
<p>Building on the previous example, in response to user input, authors should handle the events of both the editable element (in this case a canvas) and the EditContext.</p>
<p>Input events against the DOM continue to describe the user’s intent</p>
<p>The below example shows how to handle {{TextUpdateEvent}}, {{TextFormatUpdateEvent}}, and {{CharacterBoundsUpdateEvent}} to update the model and render the result to the canvas.</p>
<aside class="example" title="Event handlers for TextUpdateEvent, TextFormatUpdateEvent, and CharacterBoundsUpdateEvent">
<pre><xmp><script>
// This example is built on top of example 1 and example 2.
// Only the added logic is shown here for brevity.
class EditingModel {
updateText(updateRangeStart, updateRangeEnd, updateText) {
this.text = this.text.substring(0, updateRangeStart) + updateText
+ this.text.substring(updateRangeEnd)
}
updateSelection(selectionStart, selectionEnd) {
this.selectionStart = selectionStart
this.selectionEnd = selectionEnd
}
updateTextFormats(textFormats) {
this.textFormats = textFormats
}
}
class EditingView {
render() {
// render the text (implementation omitted for brevity)
// render the selection (implementation omitted for brevity)
// render the IME decoration
this.model.textFormats.forEach( textFormat => {
// For brevity, these variables' initialization are omitted:
// anchorX: the x coordinate of the beginning of the string
// lineY: the y coordinate of the underline
// charWidth: the width of the character (here we are using a mono-spaced font)
// thickWidth/thinWidth: pre-defined width for thick/thin lines.
let lineStartX = anchorX + textFormat.rangeStart * charWidth;
let lineEndX = anchorX + textFormat.rangeEnd * charWidth;
canvasContext2D.lineWidth = (textFormat.underlineThickness == 'Thick')?
thickWidth : thinWidth;
canvasContext2D.beginPath();
canvasContext2D.moveTo(lineStartX, lineY);
canvasContext2D.lineTo(lineEndX, lineY);
canvasContext2D.stroke();
})
}
computeCharacterBounds(rangeStart, rangeEnd) {
// implementation omitted for brevity
}
}
class EditingController {
handleTextUpdate(updateRangeStart, updateRangeEnd, text,
selectionStart, selectionEnd) {
this.model.updateText(updateRangeStart, updateRangeEnd, text)
this.model.updateSelection(selectionStart, selectionEnd)
}
handleTextFormatUpdate(textFormats) {
this.model.updateTextFormats(textFormats);
}
handleCharacterBoundsUpdate(rangeStart, rangeEnd) {
characterBounds = this.view.computeCharacterBounds(rangeStart, rangeEnd);
this.editContext.updateCharacterBounds(rangeStart, characterBounds);
}
}
// When the user is typing, EditContext will receive textupdate events,
// which can be used to update the editor's model.
editContext.addEventListener("textupdate", e => {
editingController.handleTextUpdate(e.updateRangeStart, e.updateRangeEnd, e.text,
e.selectionStart, e.selectionEnd)
});
// EditContext will also receive textformatupdate event for IME decoration.
// Ex. thin/thick underline for the "phrase mode" in Japanese IME.
editContext.addEventListener("textformatupdate", e => {
editingcontroller.handleTextFormatUpdate(e.getTextFormats());
});
// When receiving CharacterBoundsUpdate event, the author is responsible to compute
// the bounds of characters from rangeStart to rangeEnd, and call
// EditContext.updateCharacterBounds to update the character bounds in EditContext.
editContext.addEventListener("characterboundsupdate", e => {
editingcontroller.handleCharacterBoundsUpdate(e.rangeStart, e.rangeEnd);
});
</script></xmp></pre>
</aside>
</section>
</section>
<section id="interactions" class="informative">
<h3>Interactions with Other Editing Primitives </h3>
<p>An author doesn’t have to use a canvas element with an EditContext. In the example below the author uses a div to establish an editable region of the document and renders the contents into that editable region using various other styled elements, images and text. This allows the author to leverage other built-in editing primitives from the user agent such as selection and spellcheck. </p>
<aside class="example" title="How native selection can be leveraged to handle caret navigation.">
<pre><xmp><div></div>
<script>
// This example reuses EditModel and EditController in Example 2 and 3.
let div = document.querySelector("div")
div.editContext = new EditContext()
div.focus();
class EditingView {
constructor(div, model) {
this.div = div
this.model = model
}
render() {
// render the text
this.div.innerText = this.model.text
// render the selection (implementation omitted for brevity)
}
computeSelectionBound() {
// implementation omitted for brevity
}
computeControlBound() {
// implementation omitted for brevity
}
computeCharacterBounds(rangeStart, rangeEnd) {
// implementation omitted for brevity
}
}
class EditingController {
handleSelectionChange() {
// Authors are responsible to map the selection from the DOM space to the
// plain text space. One approach is to use range.toString() to get the plain text
// before the selection start/end, and use the text length as the selection index.
let s = document.getSelection()
let range = new Range()
range.setEnd(s.anchorNode, s.anchorOffset)
range.setStartBefore(parentContainer)
let selectionStart = range.toString().length
range.setEnd(s.focusNode, s.focusOffset)
range.setStartBefore(parentContainer)
let selectionEnd = range.toString().length
// Update model
this.model.updateSelection(selectionStart, selectionEnd)
this.render()
}
}
document.addEventListener("selectionchange", e => {
editingController.handleSelectionChange()
});
</script></xmp></pre>
</aside>
<aside class="example" title="How beforeinput can be used to catch insertReplacementText to apply spelling changes">
<pre><xmp><script>
// This example is built on top of example 4.
// Only the added logic is shown here for brevity.
class EditingController {
handleSpellCheck(newText, range) {
let updateRangeStart = range.startOffset
let updateRangeEnd = range.endOffset
// Update model
this.model.updateText(updateRangeStart, updateRangeEnd, newText)
let newCaretPosition = updateRangeStart + newText.length
this.model.updateSelection(newCaretPosition, newCaretPosition)
this.render()
}
}
div.spellcheck = true;
div.addEventListener("beforeinput", e => {
if (e.inputType === "insertReplacementText") { // for spellcheck
let newText = e.dataTransfer.getData("text");
let range = e.getTargetRanges()[0];
editingController.handleSpellCheck(newText, range)
}
})
</script></xmp></pre>
</aside>
<aside class="example" title="How beforeinput can be used to catch deleteByDrag and insertFromDrop to apply drag and drop changes">
<pre><xmp><script>
// This example is built on top of example 4.
// Only the added logic is shown here for brevity.
class EditingController {
handleDeleteByDrag() {
// Update model
this.model.updateText(this.model.selectionStart, this.model.selectionEnd, "")
this.render()
}
handleInsertFromDrop(newText, caretPosition) {
// Update model
editingModel.updateText(caretPosition, caretPosition, newText)
editingModel.updateSelection(caretPosition, caretPosition + newText.length)
this.render()
}
}
div.addEventListener("beforeinput", e => {
if (e.inputType === "deleteByDrag") {
editingController.handleDeleteByDrag()
}
if (e.inputType === "insertFromDrop") {
newText = e.dataTransfer.getData('text/plain');
let selection = document.getSelection();
let caretPosition = selection.anchorOffset;
editingController.handleInsertFromDrop(newText, caretPosition)
}
})
</script></xmp></pre>
</aside>
</section>
</section>
<section id="conformance">
<p>
This specification defines conformance criteria that apply to a single
product: the user agent that implements the interfaces that
it contains.
</p>
<p>
Conformance requirements phrased as algorithms or specific steps may be
implemented in any manner, so long as the end result is equivalent. (In
particular, the algorithms defined in this specification are intended
to be easy to follow, and not intended to be performant.)
</p>
</section>
<section data-dfn-for="EditContext">
<h2>EditContext API</h2>
<section data-dfn-for="Element">
<h3>Extensions to the HTMLElement interface</h3>
<pre class="idl">
partial interface HTMLElement {
attribute EditContext? editContext;
};
</pre>
<p>An {{HTMLElement}} has an internal slot [[\EditContext]], which is a reference to an {{EditContext}} and is intially null.</p>
<dl>
<dt>editContext</dt>
<dd>The {{HTMLElement/editContext}} getter steps are to return the value of [=this=]'s internal [[\EditContext]] slot.</dd>
<dd>The {{HTMLElement/editContext}} setter must follow these steps:
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|editContext|</dd>
<dt>Output</dt>
<dd>None</dd>
</dl>
<ol>
<li>If [=this=]'s [=Element/local name=] is neither a [=valid shadow host name=] nor "<code>canvas</code>", then [=exception/throw=] a {{"NotSupportedError"}} {{DOMException}}.</li>
<li>If |editContext| is not null, then:
<ol>
<li>If |editContext|'s <a>associated element</a> is equal to [=this=], then terminate these steps.</li>
<li>If |editContext|'s <a>associated element</a> is not null, then [=exception/throw=] a {{"NotSupportedError"}} {{DOMException}}.</li>
<li>Set |editContext|'s <a>associated element</a> to [=this=].</li>
</ol>
</li>
<li>Let |oldEditContext| be the value of [=this=]'s internal [[\EditContext]] slot.</li>
<li>If |oldEditContext| is not null, then:
<ol>
<li>[=Assert=]: |oldEditContext|'s <a>associated element</a> is equal to [=this=].</li>
<li>Set |oldEditContext|'s <a>associated element</a> to null.</li>
</ol>
</li>
<li>Set [=this=]'s internal [[\EditContext]] slot to be |editContext|.</li>
<li>
If |oldEditContext| is not null and |oldEditContext| is [=this=]'s
<a href="https://dom.spec.whatwg.org/#concept-node-document">node document</a>'s
[=active EditContext=], then run the steps to [=deactivate an EditContext=]
with |oldEditContext|.
</li>
</ol>
</div><!-- algorithm -->
</dd>
</dl>
<h4><dfn class="export">Handle input for EditContext</dfn></h4>
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|element|, the {{HTMLElement}} receiving the input</dd>
<dt>Output</dt>
<dd>None</dd>
</dl>
<ol>
<li>
Let |editContext| be |element|'s
<a href="https://dom.spec.whatwg.org/#concept-node-document">node document</a>'s
[=active EditContext=]
</li>
<li>
If |editContext| is null, return.
</li>
<li>
<p>
Run the steps to [=Update the EditContext=] given |editContext| and the
[=Text Edit Context=]'s [=text state=]'s [=text=], [=text formats=],
[=selection start=], [=selection end=], [=is composing=], [=composition start=],
and [=composition end=].
</p>
<p class="note">
Since [=Text Edit Context=] is an abstraction over the common aspects
of text input across different operating systems, the determination of
the values in the [=Text Edit Context=] is explicitly not given in this
specification. They will vary across different operating systems and
input devices.
</p>
</li>
</ol>
</div><!-- algorithm -->
<h4><dfn>Update the EditContext</dfn></h4>
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|editContext|, an {{EditContext}}</dd>
<dd>|text|, a string</dd>
<dd>|textFormats|, an array of [=text format=]s from the [=Text Input Service=]</dd>
<dd>|selectionStart|, the new position for the start of the selection</dd>
<dd>|selectionEnd|, the new position for the end of the selection</dd>
<dd>|isComposing|, a boolean indicating whether composition should be active at the end of the update</dd>
<dd>|replacementRangeStart|, the start position of the current composition (0 if there is no composition)</dd>
<dd>|replacementRangeEnd|, the end position of the current composition (0 if there is no composition)</dd>
<dt>Output</dt>
<dd>None</dd>
</dl>
<ol>
<li>
If |isComposing| is true, |text| is not empty, and |editContext|'s [=is composing=] is false.
<ol>
<li>[=Fire an event=] named <a href="https://w3c.github.io/uievents/#event-type-compositionstart">compositionstart</a> at |editContext| using {{CompositionEvent}}.
</li>
<li>set |editContext|'s [=is composing=] to true.</li>
</ol>
</li>
<li>
If |text| is empty:
<ol>
<li>If |editContext|'s [=is composing=] is false, return.</li>
<li>
If |editContext|'s [=is composing=] is true and |isComposing| is false, then:
<ol>
<li>Set |editContext|'s [=is composing=] to false.</li>
<li>
[=Fire an event=] named
<a href="https://w3c.github.io/uievents/#event-type-compositionend">compositionend</a>
at |editContext| using {{CompositionEvent}}.
</li>
<li>Return.</li>
</ol>
</li>
</ol>
</li>
<li>If |editContext|'s [=is composing=] is true, then:
<ol>Let |insertionStart| be |replacementRangeStart|.</ol>
<ol>Let |insertionEnd| be |replacementRangeEnd|.</ol>
</li>
<li>Otherwise:
<ol>Let |insertionStart| be |selectionStart|.</ol>
<ol>Let |insertionEnd| be |selectionEnd|.</ol>
</li>
<li>
Replace the substring of |editContext|'s [=text=] in the range of |insertionStart| and |insertionEnd| with |text|
</li>
<li>Set |editContext|'s [=selection start=] to |selectionStart|.</li>
<li>Set |editContext|'s [=selection end=] to |selectionEnd|.</li>
<li>Set |editContext|'s [=composition start=] to |insertionStart|.</li>
<li>Set |editContext|'s [=composition end=] to |editContext|'s [=composition start=] plus the length of |text|.</li>
<li>[=Dispatch text update event=] given |editContext| and |text|.</li>
<li>
If |editContext|'s [=is composing=] is true, then:
<ol>
<li>[=Dispatch text format update event=] given |editContext| and |textFormats|.</li>
<li>[=Dispatch character bounds update event=] given |editContext|.</li>
<li>If |isComposing| is false, then:
<ol>
<li>Set |editContext|'s [=is composing=] to false.</li>
<li>
[=Fire an event=] named
<a href="https://w3c.github.io/uievents/#event-type-compositionend">compositionend</a>
at |editContext| using {{CompositionEvent}}.
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div><!-- algorithm -->
<h4><dfn>Update the Text Edit Context</dfn></h4>
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|document|, a {{Document}}</dd>
<dt>Output</dt>
<dd>None</dd>
</dl>
<ol>
<li>Let |oldActiveEditContext| be |document|'s [=active EditContext=].</li>
<li>Let |newActiveEditContext| be the result of running the steps to [=determine the active EditContext=] given |document|.</li>
<li>If |oldActiveEditContext| is not null, then run the steps to [=deactivate an EditContext=] given |oldActiveEditContext|.</li>
<li>If |newActiveEditContext| is not null, then:
<ol>
<li>Update the [=Text Edit Context=]'s [=text state=] to match the values in |editContext|'s [=text state=].</li>
</ol>
</li>
<li>Set the |document|'s [=active EditContext=] to |newActiveEditContext|.</li>
</ol>
<p class="note">
Note that the steps to update the [=Text Edit Context=]'s [=text state=] are dependent on the nature of the abstraction created over a platform-specific [=Text Input Service=].
Those details are not part of this specification.
</p>
</div><!-- algorithm -->
<h4><dfn>Dispatch text update event</dfn></h4>
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|editContext|, an {{EditContext}}</dd>
<dd>|text|, a string</dd>
<dt>Output</dt>
<dd>None</dd>
</dl>
<ol>
<li>
[=Fire an event=] named "textupdate" at |editContext| using {{TextUpdateEvent}}, with
{{TextUpdateEvent/text}} initialized to |text|,
{{TextUpdateEvent/selectionStart}} initialized to ||editContext|'s [=selection start=], and
{{TextUpdateEvent/selectionEnd}} initialized to |editContext|'s [=selection end=].
</li>
</ol>
</div><!-- algorithm -->
<h4><dfn>Dispatch text format update event</dfn></h4>
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|editContext|, an {{EditContext}}</dd>
<dd>|textFormats|, an array of [=text format=]s from the [=Text Input Service=]</dd>
<dt>Output</dt>
<dd>None</dd>
</dl>
<ol>
<li>
Let |formats| be an array of {{TextFormat}}, initially empty.
</li>
<li>
For each [=text format=] |format| in |textFormats|,
<ol>
<li>Let |textFormat| be a new {{TextFormat}}. with |rangeStart|, |rangeEnd|, |underlineStyle|, |underlineThickness|.</li>
<li>Set |textFormat|'s {{TextFormat/rangeStart}} to |format|'s [=range start=].</li>
<li>Set |textFormat|'s {{TextFormat/rangeEnd}} to |format|'s [=range end=].</li>
<li>Set |textFormat|'s {{TextFormat/underlineStyle}} to |format|'s [=underline style=].</li>
<li>Set |textFormat|'s {{TextFormat/underlineThickness}} to |format|'s [=underline thickness=].</li>
<li>Append |textFormat| to |formats|</li>
</ol>
</li>
<li>
[=Fire an event=] named "textformatupdate" at |editContext| using {{TextFormatUpdateEvent}} with
the {{TextFormatUpdateEvent}}'s [=text format list=] initialized to |formats|.
</li>
</ol>
</div><!-- algorithm -->
<h4><dfn>Dispatch character bounds update event</dfn></h4>
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|editContext|, an {{EditContext}}</dd>
<dt>Output</dt>
<dd>None</dd>
</dl>
<ol>
<li>
[=Fire an event=] named "characterboundsupdate" at |editContext| using {{CharacterBoundsUpdateEvent}} with
{{CharacterBoundsUpdateEvent/rangeStart}} initialized to |editContext|'s [=composition start=] and
{{CharacterBoundsUpdateEvent/rangeEnd}} initialized to |editContext|'s [=composition end=].
</li>
</ol>
</div><!-- algorithm -->
<h4><dfn>Deactivate an EditContext</dfn></h4>
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|editContext|, an {{EditContext}}</dd>
<dt>Output</dt>
<dd>None</dd>
</dl>
<ol>
<li>Set |editContext|'s [=is composing=] to false.</li>
<li>
[=Fire an event=] named
<a href="https://w3c.github.io/uievents/#event-type-compositionend">compositionend</a>
at |editContext| using {{CompositionEvent}}.
</li>
</ol>
</div><!-- algorithm -->
<h4><dfn>Determine the active EditContext</dfn></h4>
<div class="algorithm">
<dl>
<dt>Input</dt>
<dd>|document|, a {{Document}}</dd>
<dt>Output</dt>
<dd>An {{EditContext}}, or null.</dd>
</dl>
<ol>
<li>Let |traversable| be |document|'s [=node navigable=]'s [=top-level traversable=].</li>
<li>If |traversable| is null, return null.</li>
<li>
Let |focused| be the <a href="https://html.spec.whatwg.org/multipage/interaction.html#dom-anchor">DOM anchor</a>
of the <a href="https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-traversable">currently focused area of a top-level traversable</a>
given |traversable|.
</li>
<li>
<p>If |focused| is null or if the [=shadow-including root=] of |focused| is not |document|, return null.</p>
<p class="note">
The purpose of getting |focusable| through the [=top-level traversable=] is that
we want there to be only one [=active EditContext=] at a time per
[=top-level traversable=]. So if system focus is in some other document, this
document can't have an [=active EditContext=].
</p>
</li>
<li>Let |editContext| be null.</li>
<li>While |focused| is not null and |focused| is <a href="https://w3c.github.io/editing/docs/execCommand/#editable">editable</a>:
<ol>
<li>Set |editContext| to the value of |focused|'s internal [[\EditContext]] slot.</li>
<li>Let |parent| be |focused|'s <a href="https://dom.spec.whatwg.org/#concept-tree-parent">parent</a>.</li>
<li>
If |parent| is null and |focused|'s <a href="https://dom.spec.whatwg.org/#concept-tree-root">root</a>
is a [=shadow root=], let |parent| be |focused|'s
<a href="https://dom.spec.whatwg.org/#concept-tree-root">root</a>'s
<a href="https://dom.spec.whatwg.org/#concept-documentfragment-host">host</a>.
</li>
<li>Set |focused| to |parent|.</li>
</ol>
</li>
<li>Return |editContext|.</li>
</ol>
<p class="note">
If an {{EditContext}}'s [=associated element=]'s parent is editable, that {{EditContext}}
can't become the [=active EditContext=]. This is the case regardless of whether that
parent is editable due to another {{EditContext}} or due to [^html-global/contenteditable^].
</p>
</div><!-- algorithm -->
</section>
<h3 id="editcontext-interface">EditContext Interface</h3>
<pre class="idl"><xmp>dictionary EditContextInit {
DOMString text;
unsigned long selectionStart;
unsigned long selectionEnd;
};
[Exposed=Window]
interface EditContext : EventTarget {
constructor(optional EditContextInit options = {});
undefined updateText(unsigned long rangeStart, unsigned long rangeEnd,
DOMString text);
undefined updateSelection(unsigned long start, unsigned long end);
undefined updateControlBounds(DOMRect controlBounds);
undefined updateSelectionBounds(DOMRect selectionBounds);
undefined updateCharacterBounds(unsigned long rangeStart, sequence<DOMRect> characterBounds);
sequence<HTMLElement> attachedElements();
readonly attribute DOMString text;
readonly attribute unsigned long selectionStart;
readonly attribute unsigned long selectionEnd;
readonly attribute unsigned long characterBoundsRangeStart;
sequence<DOMRect> characterBounds();
attribute EventHandler ontextupdate;
attribute EventHandler ontextformatupdate;