-
-
Notifications
You must be signed in to change notification settings - Fork 281
/
mathfield-element.ts
1197 lines (1135 loc) · 38.6 KB
/
mathfield-element.ts
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
import { MathfieldOptions } from './options';
import { Selector } from './commands';
import {
Mathfield,
InsertOptions,
OutputFormat,
Offset,
Range,
Selection,
FindOptions,
ReplacementFunction,
} from './mathfield';
import { MathfieldErrorCode, ParseMode, ParserErrorCode, Style } from './core';
import {
get as getOptions,
getDefault as getDefaultOptions,
update as updateOptions,
} from '../editor/options';
import { MathfieldPrivate } from '../editor-mathfield/mathfield-private';
import { isOffset, isRange, isSelection } from '../editor/model';
//
// Custom Events
//
/*
## Event retargeting
Some events bubble up through the DOM tree, so that they are detectable by
any element on the page.
Bubbling events fired from within shadow DOM are retargeted so that, to any
listener external to your component, they appear to come from your component itself.
## Custom Event Bubbling
By default, a bubbling custom event fired inside shadow DOM will stop
bubbling when it reaches the shadow root.
To make a custom event pass through shadow DOM boundaries, you must set
both the `composed` and `bubbles` flags to true.
*/
/**
* The `math-error` custom event signals an error while parsing an expression.
*
* ```javascript
* document.getElementById('mf').addEventListener('math-error', (ev) => {
* const err = ev.detail;
* console.warn(err.code + (err.arg ? ': ' + err.arg : '') +
* '\n%c| ' + err.before + '%c' + err.after +
* '\n%c| ' + String(' ').repeat(err.before.length) +
* '▲',
* 'font-weight: bold',
* 'font-weight: normal; color: rgba(160, 160, 160)',
* 'font-weight: bold; color: hsl(4deg, 90%, 50%)'
* );
* });
* ```
*/
export type MathErrorEvent = {
code: ParserErrorCode | MathfieldErrorCode;
arg?: string;
latex?: string;
before?: string;
after?: string;
};
/**
* The `keystroke` event is fired when a keystroke is about to be procesed.
* The event is cancellable, which wills suprress further handling of the event.
*
*/
export type KeystrokeEvent = {
/** A string descring the keystroke, for example `"Alt-KeyU". See [W3C UIEvents](https://www.w3.org/TR/uievents/#keys-keyvalues)
* for more information on the format of the descriptor.
*
*/
keystroke: string;
/** The native keyboard event */
event?: KeyboardEvent;
};
/**
* The `focus-out` event signals that the mathfield has lost focus through keyboard
* navigation with arrow keys or the tab key.
*
* The event `detail.direction` property indicates the direction the cursor
* was moving which can be useful to decide which element to focus next.
*
* The event is cancelable, which will prevent the field from losing focus.
*
* ```javascript
* mfe.addEventListener('focus-out', (ev) => {
* console.log("Losing focus ", ev.detail.direction);
* });
* ```
*/
export type FocusOutEvent = {
direction: 'forward' | 'backward' | 'upward' | 'downward';
};
declare global {
/**
* Map the custom event names to types
* @internal
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface DocumentEventMap {
['math-error']: CustomEvent<MathErrorEvent>;
['keystroke']: CustomEvent<KeystrokeEvent>;
['focus-out']: CustomEvent<FocusOutEvent>;
}
}
const MATHFIELD_TEMPLATE = document.createElement('template');
MATHFIELD_TEMPLATE.innerHTML = `<style>
:host {
display: block;
}
:host([hidden]) {
display: none;
}
:host([disabled]) {
opacity: .5;
}
:host(:focus), :host(:focus-within) {
outline: Highlight auto 1px; /* For Firefox */
outline: -webkit-focus-ring-color auto 1px;
}
</style>
<div></div><slot style="display:none"></slot>`;
//
// Deferred State
//
// Methods such as `setOptions()` or `getOptions()` could be called before
// the element has been connected (i.e. `mf = new MathfieldElement(); mf.setConfig()`...)
// and therefore before the matfield instance has been created.
// So we'll stash any deferred operations on options (and value) here, and
// will apply them to the element when it gets connected to the DOM.
//
const gDeferredState = new WeakMap<
MathfieldElement,
{
value: string;
selection: Selection;
options: Partial<MathfieldOptions>;
}
>();
export interface MathfieldElementAttributes {
'default-mode': string;
'fonts-directory': string;
'horizontal-spacing-scale': string;
'ignore-spacebar-in-math-mode': boolean;
'inline-shortcut-timeout': string;
'keypress-vibration': boolean;
'letter-shape-style': string;
locale: string;
'read-only': boolean;
'remove-extraneous-parentheses': boolean;
'smart-fence': boolean;
'smart-mode': boolean;
'smart-superscript': boolean;
'speech-engine': string;
'speech-engine-rate': string;
'speech-engine-voice': string;
'text-to-speech-markup': string;
'text-to-speech-rules': string;
'virtual-keyboard-layout': string;
'virtual-keyboard-mode': string;
'virtual-keyboard-theme': string;
'virtual-keyboards': string;
'use-shared-virtual-keyboard': boolean;
'shared-virtual-keyboard-target-origin': string;
// Allow for global aria attributes, data- attributes, micro-data attributes
// and global element attributes
[key: string]: number | string | boolean | undefined;
}
/**
* The `MathfieldElement` class provides special properties and
* methods to control the display and behavior of `<math-field>`
* elements.
*
* It inherits many useful properties and methods from [[`HTMLElement`]] such
* as `style`, `tabIndex`, `addEventListener()`, `getAttribute()`, etc...
*
* To create a new `MathfieldElement`:
*
* ```javascript
* // 1. Create a new MathfieldElement
* const mfe = new MathfieldElement();
* // 2. Attach it to the DOM
* document.body.appendChild(mfe);
* ```
*
* The `MathfieldElement` constructor has an optional argument of
* [[`MathfieldOptions`]] to configure the element. The options can also
* be modified later:
*
* ```javascript
* // Setting options during construction
* const mfe = new MathfieldElement({smartFence: false});
* // Modifying options after construction
* mfe.setOptions({smartFence: true});
* ```
*
* ### CSS Variables
*
* To customize the appearance of the mathfield, declare the following CSS
* variables (custom properties) in a ruleset that applied to the mathfield.
* ```css
* math-field {
* --hue: 10 // Set the highlight color and caret to a reddish hue
* }
* ```
*
* | CSS Variable | Usage |
* |:---|:---|
* | `--hue` | Hue of the highlight color and the caret |
* | `--highlight` | Color of the selection |
* | `--highlight-inactive` | Color of the selection, when the mathfield is not focused |
* | `--caret` | Color of the caret/insertion point |
* | `--primary` | Primary accent color, used for example in the virtual keyboard |
* | `--text-font-family` | The font stack used in text mode |
* | `--keyboard-zindex` | The z-index attribute of the virtual keyboard panel |
*
* ### CSS Parts
*
* To style the virtual keyboard toggle, use the `virtual-keyboard-toggle` CSS
* part. To use it, define a CSS rule with a `::part()` selector
* for example:
* ```css
* math-field::part(virtual-keyboard-toggle) {
* color: red;
* }
* ```
*
*
* ### Attributes
*
* An attribute is a key-value pair set as part of the tag:
*
* ```html
* <math-field locale="fr"></math-field>
* ```
*
* The supported attributes are listed in the table below with their correspnding
* property.
*
* The property can be changed either directly on the
* `MathfieldElement` object, or using `setOptions()` if it is prefixed with
* `options.`, for example
* ```javascript
* getElementById('mf').value = '\\sin x';
* getElementById('mf').setOptions({horizontalSpacingScale: 1.1});
* ```
*
* The values of attributes and properties are reflected, which means you can change one or the
* other, for example:
* ```javascript
* getElementById('mf').setAttribute('virtual-keyboard-mode', 'manual');
* console.log(getElementById('mf').getOption('virtualKeyboardMode'));
* // Result: "manual"
* getElementById('mf').setOptions({virtualKeyboardMode: 'onfocus');
* console.log(getElementById('mf').getAttribute('virtual-keyboard-mode');
* // Result: 'onfocus'
* ```
*
* An exception is the `value` property, which is not reflected on the `value`
* attribute: the `value` attribute remains at its initial value.
*
*
* | Attribute | Property |
* |:---|:---|
* | `disabled` | `disabled` |
* | `default-mode` | `options.defaultMode` |
* | `fonts-directory` | `options.fontsDirectory` |
* | `sounds-directory` | `options.soundsDirectory` |
* | `horizontal-spacing-scale` | `options.horizontalSpacingScale` |
* | `ignore-spacebar-in-math-mode` | `options.ignoreSpacbarInMathMode` |
* | `inline-shortcut-timeout` | `options.inlineShortcutTimeout` |
* | `keypress-vibration` | `options.keypressVibration` |
* | `letter-shape-style` | `options.letterShapeStyle` |
* | `locale` | `options.locale` |
* | `read-only` | `options.readOnly` |
* | `remove-extraneous-parentheses` | `options.removeExtraneousParentheses` |
* | `smart-fence` | `options.smartFence` |
* | `smart-mode` | `options.smartMode` |
* | `smart-superscript` | `options.superscript` |
* | `speech-engine` | `options.speechEngine` |
* | `speech-engine-rate` | `options.speechEngineRate` |
* | `speech-engine-voice` | `options.speechEngineVoice` |
* | `text-to-speech-markup` | `options.textToSpeechMarkup` |
* | `text-to-speech-rules` | `options.textToSpeechRules` |
* | `value` | value |
* | `virtual-keyboard-layout` | `options.keyboardLayout` |
* | `virtual-keyboard-mode` | `options.keyboardMode` |
* | `virtual-keyboard-theme` | `options.keyboardTheme` |
* | `virtual-keyboards` | `options.keyboards` |
*
* See [[`MathfieldOptions`]] for more details about these options.
*
* In addition, the following [global attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes)
* can also be used:
* - `class`
* - `data-*`
* - `hidden`
* - `id`
* - `item*`
* - `style`
* - `tabindex`
*
*
* ### Events
*
* Listen to these events by using `addEventListener()`. For events with additional
* arguments, the arguments are availble in `event.detail`.
*
* | Event Name | Description |
* |:---|:---|
* | `input` | The value of the mathfield has been modified. This happens on almost every keystroke in the mathfield. |
* | `change` | The user has commited the value of the mathfield. This happens when the user presses **Return** or leaves the mathfield. |
* | `selection-change` | The selection (or caret position) in the mathfield has changed |
* | `mode-change` | The mode (`math`, `text`) of the mathfield has changed |
* | `undo-state-change` | The state of the undo stack has changed |
* | `read-aloud-status-change` | The status of a read aloud operation has changed |
* | `virtual-keyboard-toggle` | The visibility of the virtual keyboard panel has changed |
* | `blur` | The mathfield is losing focus |
* | `focus` | The mathfield is gaining focus |
* | `focus-out` | The user is navigating out of the mathfield, typically using the keyboard<br> `detail: {direction: 'forward' | 'backward' | 'upward' | 'downward'}` **cancellable**|
* | `math-error` | A parsing or configuration error happened <br> `detail: ErrorListener<ParserErrorCode | MathfieldErrorCode>` |
* | `keystroke` | The user typed a keystroke with a physical keyboard <br> `detail: {keystroke: string, event: KeyboardEvent}` |
* | `mount` | The element has been attached to the DOM |
* | `unmount` | The element is about to be removed from the DOM |
*
*/
export class MathfieldElement extends HTMLElement implements Mathfield {
/**
* Private lifecycle hooks
* @internal
*/
static get optionsAttributes(): {
[attribute: string]: 'number' | 'boolean' | 'string';
} {
return {
'default-mode': 'string',
'fonts-directory': 'string',
'horizontal-spacing-scale': 'string',
'ignore-spacebar-in-math-mode': 'boolean',
'inline-shortcut-timeout': 'string',
'keypress-vibration': 'boolean',
'letter-shape-style': 'string',
locale: 'string',
'read-only': 'boolean',
'remove-extraneous-parentheses': 'boolean',
'smart-fence': 'boolean',
'smart-mode': 'boolean',
'smart-superscript': 'boolean',
'speech-engine': 'string',
'speech-engine-rate': 'string',
'speech-engine-voice': 'string',
'text-to-speech-markup': 'string',
'text-to-speech-rules': 'string',
'virtual-keyboard-layout': 'string',
'virtual-keyboard-mode': 'string',
'virtual-keyboard-theme': 'string',
'virtual-keyboards': 'string',
'use-shared-virtual-keyboard': 'boolean',
'shared-virtual-keyboard-target-origin': 'string',
};
}
/**
* Custom elements lifecycle hooks
* @internal
*/
static get observedAttributes(): string[] {
return [...Object.keys(MathfieldElement.optionsAttributes), 'disabled'];
}
private _mathfield: MathfieldPrivate;
/**
* To create programmatically a new mahfield use:
* ```javascript
let mfe = new MathfieldElement();
// Set initial value and options
mfe.value = "\\frac{\\sin(x)}{\\cos(x)}";
// Options can be set either as an attribute (for simple options)...
mfe.setAttribute('virtual-keyboard-layout', 'dvorak');
// ... or using `setOptions()`
mfe.setOptions({
virtualKeyboardMode: 'manual',
});
// Attach the element to the DOM
document.body.appendChild(mfe);
* ```
*/
constructor(options?: Partial<MathfieldOptions>) {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(MATHFIELD_TEMPLATE.content.cloneNode(true));
const slot = this.shadowRoot.querySelector<HTMLSlotElement>(
'slot:not([name])'
);
// When the elements get focused (through tabbing for example)
// focus the mathfield
this.shadowRoot.host.addEventListener(
'focus',
(_event) => this._mathfield?.focus(),
true
);
this.shadowRoot.host.addEventListener(
'blur',
(_event) => this._mathfield?.blur(),
true
);
// Inline options (as a JSON structure in the markup)
try {
const json = slot
.assignedElements()
.filter((x) => x['type'] === 'application/json')
.map((x) => x.textContent)
.join('');
if (json) {
this.setOptions(JSON.parse(json));
}
} catch (e) {
console.log(e);
}
// Record the (optional) configuration options, as a deferred state
if (options) {
this.setOptions(options);
}
// Check if there is a `value` attribute and set the initial value
// of the mathfield from it
if (this.hasAttribute('value')) {
this.value = this.getAttribute('value');
} else {
this.value =
slot
?.assignedNodes()
.map((x) => (x.nodeType === 3 ? x.textContent : ''))
.join('')
.trim() ?? '';
}
slot.addEventListener('slotchange', (e) => {
if (e.target !== slot) return;
const value = slot
.assignedNodes()
.map((x) => (x.nodeType === 3 ? x.textContent : ''))
.join('')
.trim();
if (!this._mathfield) {
this.value = value;
} else {
// Don't suppress notification changes. We need to know
// if the value has changed indirectly through slot manipulation
this._mathfield.setValue(value, {
insertionMode: 'replaceAll',
});
}
});
}
get mode(): ParseMode {
return this._mathfield?.mode;
}
set mode(value: ParseMode) {
if (!this._mathfield) return;
this._mathfield.mode = value;
}
/**
* @category Options
*/
getOptions<K extends keyof MathfieldOptions>(
keys: K[]
): Pick<MathfieldOptions, K>;
getOptions(): MathfieldOptions;
getOptions(
keys?: keyof MathfieldOptions | (keyof MathfieldOptions)[]
): any | Partial<MathfieldOptions> {
if (this._mathfield) {
return getOptions(this._mathfield.options, keys);
}
if (!gDeferredState.has(this)) return null;
return getOptions(
updateOptions(
getDefaultOptions(),
gDeferredState.get(this).options
),
keys
);
}
/**
* @category Options
*/
getOption<K extends keyof MathfieldOptions>(key: K): MathfieldOptions[K] {
return (this.getOptions([key]) as unknown) as MathfieldOptions[K];
}
/**
* @category Options
*/
setOptions(options: Partial<MathfieldOptions>): void {
if (this._mathfield) {
this._mathfield.setOptions(options);
} else {
if (gDeferredState.has(this)) {
gDeferredState.set(this, {
value: gDeferredState.get(this).value,
selection: { ranges: [[0, -1]] },
options: {
...gDeferredState.get(this).options,
...options,
},
});
} else {
gDeferredState.set(this, {
value: '',
selection: { ranges: [[0, 0]] },
options: options,
});
}
}
// Reflect options to attributes
reflectAttributes(this);
}
/**
* Execute a [[`Commands`|command]] defined by a selector.
* ```javascript
* mfe.executeCommand('add-column-after');
* mfe.executeCommand(['switch-mode', 'math']);
* ```
*
* @param command - A selector, or an array whose first element
* is a selector, and whose subsequent elements are arguments to the selector.
*
* Selectors can be passed either in camelCase or kebab-case.
*
* ```javascript
* // Both calls do the same thing
* mfe.executeCommand('selectAll');
* mfe.executeCommand('select-all');
* ```
*/
executeCommand(command: Selector | [Selector, ...any[]]): boolean {
return this._mathfield?.executeCommand(command) ?? false;
}
/**
* @category Accessing and changing the content
*/
getValue(): string;
getValue(format: OutputFormat): string;
getValue(start: Offset, end: Offset, format?: OutputFormat): string;
getValue(range: Range, format?: OutputFormat): string;
getValue(selection: Selection, format?: OutputFormat): string;
getValue(
arg1?: Offset | Range | Selection | OutputFormat,
arg2?: Offset | OutputFormat,
arg3?: OutputFormat
): string {
if (this._mathfield) {
return this._mathfield.getValue(arg1 as any, arg2 as any, arg3);
}
if (gDeferredState.has(this)) {
let start: Offset;
let end: Offset;
let format: OutputFormat;
if (isSelection(arg1)) {
[start, end] = arg1.ranges[0];
format = arg2 as OutputFormat;
} else if (isRange(arg1)) {
[start, end] = arg1;
format = arg2 as OutputFormat;
} else if (isOffset(arg1) && isOffset(arg2)) {
start = arg1;
end = arg2;
format = arg3 as OutputFormat;
} else {
start = 0;
end = -1;
format = arg1 as OutputFormat;
}
if (format === 'latex' && start === 0 && end === -1) {
return gDeferredState.get(this).value;
}
}
return undefined;
}
/**
* @category Accessing and changing the content
*/
setValue(value?: string, options?: InsertOptions): void {
if (this._mathfield) {
this._mathfield.setValue(value, options);
return;
}
if (gDeferredState.has(this)) {
gDeferredState.set(this, {
value,
selection: { ranges: [[0, -1]], direction: 'forward' },
options: gDeferredState.get(this).options,
});
return;
}
gDeferredState.set(this, {
value,
selection: { ranges: [[0, -1]], direction: 'forward' },
options: getOptionsFromAttributes(this),
});
}
/**
* Return true if the mathfield is currently focused (responds to keyboard
* input).
*
* @category Focus
*
*/
hasFocus(): boolean {
return this._mathfield?.hasFocus() ?? false;
}
/**
* Sets the focus to the mathfield (will respond to keyboard input).
*
* @category Focus
*
*/
focus(): void {
super.focus();
// if (this._mathfield) {
// // Don't call this._mathfield.focus(): it checks the focus state,
// // but super.focus() just changed it...
// this._mathfield.keyboardDelegate.focus();
// this._mathfield.model.announce('line');
// }
}
/**
* Remove the focus from the mathfield (will no longer respond to keyboard
* input).
*
* @category Focus
*
*/
blur(): void {
super.blur();
// if (this._mathfield) {
// // Don't call this._mathfield.focs(): it checks the focus state,
// // but super.blur() just changed it...
// this._mathfield.keyboardDelegate.blur();
// }
}
/**
* Select the content of the mathfield.
* @category Selection
*/
select(): void {
this._mathfield?.select();
}
/**
* Inserts a block of text at the current insertion point.
*
* This method can be called explicitly or invoked as a selector with
* `executeCommand("insert")`.
*
* After the insertion, the selection will be set according to the
* `options.selectionMode`.
*
* @category Accessing and changing the content
*/
insert(s: string, options?: InsertOptions): boolean {
return this._mathfield?.insert(s, options) ?? false;
}
/**
* Updates the style (color, bold, italic, etc...) of the selection or sets
* the style to be applied to future input.
*
* If there is no selection and no range is specified, the style will
* apply to the next character typed.
*
* If a range is specified, the style is applied to the range, otherwise,
* if there is a selection, the style is applied to the selection.
*
* If the operation is 'toggle' and the range already has this style,
* remove it. If the range
* has the style partially applied (i.e. only some sections), remove it from
* those sections, and apply it to the entire range.
*
* If the operation is 'set', the style is applied to the range,
* whether it already has the style or not.
*
* The default operation is 'set'.
*
* @category Accessing and changing the content
*/
applyStyle(
style: Style,
options?: Range | { range?: Range; operation?: 'set' | 'toggle' }
): void {
return this._mathfield?.applyStyle(style, options);
}
/**
* The bottom location of the caret (insertion point) in viewport
* coordinates.
*
* See also [[`setCaretPoint`]]
* @category Selection
*/
get caretPoint(): { x: number; y: number } {
return this._mathfield?.getCaretPoint() ?? null;
}
set caretPoint(point: { x: number; y: number }) {
this._mathfield?.setCaretPoint(point.x, point.y);
}
/**
* `x` and `y` are in viewport coordinates.
*
* Return true if the location of the point is a valid caret location.
*
* See also [[`caretPoint`]]
* @category Selection
*/
setCaretPoint(x: number, y: number): boolean {
return this._mathfield?.setCaretPoint(x, y) ?? false;
}
/**
* Return an array of ranges matching the argument.
*
* An array is always returned, but it has no element if there are no
* matching items.
*/
find(pattern: string | RegExp, options?: FindOptions): Range[] {
return this._mathfield?.find(pattern, options) ?? [];
}
/**
* Replace the pattern items matching the **pattern** with the
* **replacement** value.
*
* If **replacement** is a function, the function is called
* for each match and the function return value will be
* used as the replacement.
*/
replace(
pattern: string | RegExp,
replacement: string | ReplacementFunction,
options?: FindOptions
): void {
this._mathfield?.replace(pattern, replacement, options);
}
/**
* Custom elements lifecycle hooks
* @internal
*/
connectedCallback(): void {
if (!this.hasAttribute('role')) this.setAttribute('role', 'textbox');
// this.setAttribute('aria-multiline', 'false');
if (!this.hasAttribute('tabindex')) this.setAttribute('tabindex', '0');
this._mathfield = new MathfieldPrivate(
this.shadowRoot.querySelector(':host > div'),
{
onBlur: () => {
this.dispatchEvent(
new Event('blur', {
cancelable: false,
bubbles: false, // 'focus' and 'blur' don't bubble
})
);
},
onContentDidChange: () => {
this.dispatchEvent(
new Event('input', {
cancelable: false,
bubbles: true,
})
);
},
onError: (err: {
code: ParserErrorCode | MathfieldErrorCode;
arg?: string;
latex?: string;
before?: string;
after?: string;
}) => {
this.dispatchEvent(
new CustomEvent<MathErrorEvent>('math-error', {
detail: {
code: err.code,
arg: err.arg,
latex: err.latex,
before: err.before,
after: err.after,
},
cancelable: false,
bubbles: true,
})
);
},
onFocus: () => {
this.dispatchEvent(
new Event('focus', {
cancelable: false,
bubbles: false, // 'focus' and 'blur' don't bubble
})
);
},
onKeystroke: (
_sender: Mathfield,
keystroke: string,
ev: KeyboardEvent
): boolean => {
return this.dispatchEvent(
new CustomEvent<KeystrokeEvent>('keystroke', {
detail: {
keystroke,
event: ev,
},
cancelable: true,
bubbles: true,
})
);
},
onModeChange: (_sender: Mathfield, _mode: ParseMode) => {
this.dispatchEvent(
new Event('mode-change', {
cancelable: false,
bubbles: true,
})
);
},
onCommit: (_sender: Mathfield) => {
// Match the DOM event sent by `<input>`, `<textarea>`, etc...
// Sent when the [Return] or [Enter] key is pressed, or on
// focus loss if the content has changed.
this.dispatchEvent(
new Event('change', {
cancelable: false,
bubbles: true,
})
);
},
onMoveOutOf: (
_sender: Mathfield,
direction: 'forward' | 'backward' | 'upward' | 'downward'
): boolean => {
return this.dispatchEvent(
new CustomEvent<FocusOutEvent>('focus-out', {
detail: { direction },
cancelable: true,
bubbles: true,
})
);
},
onTabOutOf: (
_sender: Mathfield,
direction: 'forward' | 'backward'
): boolean => {
return this.dispatchEvent(
new CustomEvent<FocusOutEvent>('focus-out', {
detail: { direction },
cancelable: true,
bubbles: true,
})
);
},
onReadAloudStatus: () => {
this.dispatchEvent(
new Event('read-aloud-status-change', {
cancelable: false,
bubbles: true,
})
);
},
onSelectionDidChange: () => {
this.dispatchEvent(
new Event('selection-change', {
cancelable: false,
bubbles: true,
})
);
},
onUndoStateDidChange: () => {
this.dispatchEvent(
new Event('undo-state-change', {
cancelable: false,
bubbles: true,
})
);
},
...getOptionsFromAttributes(this),
...(gDeferredState.has(this)
? gDeferredState.get(this).options
: {}),
}
);
this.upgradeProperty('disabled');
// The mathfield creation could have failed
if (!this._mathfield || !this._mathfield.model) {
this._mathfield = null;
return;
}
// this._mathfield.field.parentElement.addEventListener(
// 'focus',
// (_event) => this._mathfield.focus(),
// true
// );
// this._mathfield.field.parentElement.addEventListener(
// 'blur',
// (_event) => this._mathfield.blur(),
// true
// );
if (gDeferredState.has(this)) {
this._mathfield.model.deferNotifications(
{ content: false, selection: false },
() => {
this._mathfield.setValue(gDeferredState.get(this).value);
this._mathfield.selection = gDeferredState.get(
this
).selection;
gDeferredState.delete(this);
}
);
}
// Notify listeners that we're mounted and ready
this.dispatchEvent(
new Event('mount', {
cancelable: false,
bubbles: true,
})
);
}
/**
* Custom elements lifecycle hooks
* @internal
*/
disconnectedCallback(): void {
// Notify listeners that we're about to be unmounted
this.dispatchEvent(
new Event('unmount', {
cancelable: false,
bubbles: true,
})
);
if (!this._mathfield) return;
// Save the state (in case the elements get reconnected later)
const options = {};
Object.keys(MathfieldElement.optionsAttributes).forEach((x) => {
options[toCamelCase(x)] = this._mathfield.getOption(
toCamelCase(x) as any
);
});
gDeferredState.set(this, {
value: this._mathfield.getValue(),
selection: this._mathfield.selection,
options,
});
// Dispose of the mathfield
this._mathfield.dispose();
this._mathfield = null;
}
/**
* Private lifecycle hooks
* @internal
*/
upgradeProperty(prop: string): void {
if (this.hasOwnProperty(prop)) {
const value: unknown = this[prop];
// A property may have already been set on the object, before
// the element was connected: delete the property (after saving its value)
// and use the setter to (re-)set its value.
delete this[prop];
this[prop] = value;
}
}