@stacksjs/components 0.2.863 → 0.2.864

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,11 +6,11 @@
6
6
  * something lives here or below, in plain TypeScript, so it can be driven from
7
7
  * a test - or from a host that is not an stx page at all.
8
8
  */
9
- import type { CompletionItem, Keymap, Transaction } from './core'
10
- import type { EditorDiagnostic, EditorWidget } from './view'
11
- import { CompletionList, createKeymap, defaultKeymap, EditorCore, languageConfig, rangeEmpty, rangeFrom, rangeTo, registerDefaultCommands, wordStart } from './core'
9
+ import type { CompletionItem, Keymap, LineTokenizer, Position, SignatureHelp, Transaction } from './core'
10
+ import type { EditorDiagnostic, EditorWidget, HintBlock } from './view'
11
+ import { callContext, CompletionList, createKeymap, defaultKeymap, EditorCore, hoverPlainText, languageConfig, mapOffset, parseHoverContent, rangeEmpty, rangeFrom, rangeTo, registerDefaultCommands, signatureParts, wordAt, wordStart } from './core'
12
12
  import { createLanguageTokenizer } from './tokenizer'
13
- import { EditorView } from './view'
13
+ import { EditorView, renderCodeHtml } from './view'
14
14
 
15
15
  export interface CodeEditorConfig {
16
16
  value?: string
@@ -28,6 +28,12 @@ export interface CodeEditorConfig {
28
28
  /** Bindings laid over the defaults. An empty command name unbinds a key. */
29
29
  keymap?: Keymap
30
30
  inlineDiagnostics?: boolean
31
+ /** Ask for a hover when the pointer rests on a word. Default true. */
32
+ hover?: boolean
33
+ /** Milliseconds the pointer rests before a hover is asked for. Default 300. */
34
+ hoverDelay?: number
35
+ /** Ask for signature help after `(` and `,` inside a call. Default true. */
36
+ signatureHelp?: boolean
31
37
  }
32
38
 
33
39
  export interface SelectionDetail {
@@ -75,6 +81,33 @@ export interface CompletionRequest {
75
81
  trigger: string
76
82
  }
77
83
 
84
+ export interface HoverRequest {
85
+ /** Zero-based line and column asked about: under the pointer, or the caret. */
86
+ line: number
87
+ column: number
88
+ /** Offsets of the word there. */
89
+ from: number
90
+ to: number
91
+ word: string
92
+ /** True for the keyboard command, false for a resting pointer. */
93
+ explicit: boolean
94
+ }
95
+
96
+ export interface SignatureRequest {
97
+ /** Zero-based line and column of the caret. */
98
+ line: number
99
+ column: number
100
+ /** Offset of the caret. */
101
+ offset: number
102
+ /** Offset just inside the call's opening parenthesis. */
103
+ start: number
104
+ /** Which argument the caret is in, counted from the text alone. */
105
+ active: number
106
+ /** The character that asked: `(` or `,`. Empty for the command. */
107
+ trigger: string
108
+ explicit: boolean
109
+ }
110
+
78
111
  export interface PopupItem {
79
112
  id: string
80
113
  index: number
@@ -93,6 +126,10 @@ export interface PopupState {
93
126
  top: number
94
127
  /** `above` when there is no room under the caret. */
95
128
  placement: 'below' | 'above'
129
+ /** The selected item's note, whole: the row cuts it short. */
130
+ detail: string
131
+ /** The selected item's longer note. */
132
+ documentation: string
96
133
  }
97
134
 
98
135
  export interface CodeEditorHooks {
@@ -103,12 +140,33 @@ export interface CodeEditorHooks {
103
140
  onCompleteRequest?: (request: CompletionRequest) => void
104
141
  onCompletionAccept?: (item: CompletionItem) => void
105
142
  onPopup?: (state: PopupState) => void
143
+ /** A hover is wanted. Answer with `showHover`. */
144
+ onHoverRequest?: (request: HoverRequest) => void
145
+ /** Signature help is wanted. Answer with `showSignature`. */
146
+ onSignatureRequest?: (request: SignatureRequest) => void
106
147
  onGhost?: (outcome: 'accept' | 'dismiss', text: string) => void
107
148
  onFocus?: () => void
108
149
  onBlur?: () => void
109
150
  }
110
151
 
111
- const CLOSED_POPUP: PopupState = { open: false, items: [], activeId: '', left: 0, top: 0, placement: 'below' }
152
+ const CLOSED_POPUP: PopupState = { open: false, items: [], activeId: '', left: 0, top: 0, placement: 'below', detail: '', documentation: '' }
153
+ /** How much text before the caret is read to find the call it is in. */
154
+ const CALL_WINDOW = 4000
155
+
156
+ interface HoverTarget {
157
+ from: number
158
+ to: number
159
+ explicit: boolean
160
+ serial: number
161
+ }
162
+
163
+ interface SignatureTarget {
164
+ /** Offset of the call's opening parenthesis. */
165
+ open: number
166
+ help: SignatureHelp | null
167
+ /** The argument the caret was in when the help arrived. */
168
+ base: number
169
+ }
112
170
  const WORD = /^[\p{L}\p{N}_$]*$/u
113
171
  const TRIGGER = /[\p{L}\p{N}_$.]/u
114
172
  /** Rows the popup draws. Narrowing by typing is how a reader gets to the rest. */
@@ -131,6 +189,14 @@ export class CodeEditorController {
131
189
  private languageRequest = 0
132
190
  private userKeymap: Keymap
133
191
  private popupWasOpen = false
192
+ /** Which side of the caret line the completion list is on, while it is open. */
193
+ private popupSide: 'above' | 'below' | '' = ''
194
+ private hoverEnabled: boolean
195
+ private signatureEnabled: boolean
196
+ private hoverTarget: HoverTarget | null = null
197
+ private hoverSerial = 0
198
+ private signatureTarget: SignatureTarget | null = null
199
+ private readonly hintTokenizers = new Map<string, Promise<LineTokenizer<any> | null>>()
134
200
  private destroyed = false
135
201
 
136
202
  constructor(root: HTMLElement, config: CodeEditorConfig = {}, hooks: CodeEditorHooks = {}) {
@@ -140,6 +206,8 @@ export class CodeEditorController {
140
206
  this.autoComplete = config.autoComplete ?? true
141
207
  this.highlight = config.highlight ?? true
142
208
  this.userKeymap = config.keymap ?? {}
209
+ this.hoverEnabled = config.hover ?? true
210
+ this.signatureEnabled = config.signatureHelp ?? true
143
211
 
144
212
  this.core = new EditorCore({
145
213
  value: config.value ?? '',
@@ -161,8 +229,18 @@ export class CodeEditorController {
161
229
  onFocus: () => this.hooks.onFocus?.(),
162
230
  onBlur: () => {
163
231
  this.closeCompletions()
232
+ this.closeHover()
233
+ this.closeSignature()
164
234
  this.hooks.onBlur?.()
165
235
  },
236
+ hoverDelay: config.hoverDelay,
237
+ onPointerRest: offset => this.onPointerRest(offset),
238
+ onPointerLeave: () => {
239
+ // A hover asked for from the keyboard is not the pointer's to close.
240
+ if (!this.hoverTarget?.explicit)
241
+ this.closeHover()
242
+ },
243
+ onScroll: () => this.closeHover(),
166
244
  })
167
245
  this.view.setReadOnly(config.readOnly ?? false)
168
246
  this.view.setLineNumbers(config.lineNumbers ?? true)
@@ -306,6 +384,21 @@ export class CodeEditorController {
306
384
  return true
307
385
  }
308
386
 
387
+ if (name === 'showHover') {
388
+ const head = this.core.main.head
389
+ const range = this.wordRangeAt(head, true)
390
+ if (range)
391
+ this.requestHover(head, range, true)
392
+ else
393
+ this.view.announce('Nothing to describe here.')
394
+ return true
395
+ }
396
+
397
+ if (name === 'triggerSignature') {
398
+ this.requestSignature(true, '')
399
+ return true
400
+ }
401
+
309
402
  return false
310
403
  }
311
404
 
@@ -330,6 +423,10 @@ export class CodeEditorController {
330
423
  if (transaction.selectionChanged || transaction.docChanged)
331
424
  this.hooks.onSelection?.(this.selection)
332
425
 
426
+ // A hint describes the text as it was. Typing, or moving, makes it stale.
427
+ this.closeHover()
428
+ this.followSignature(transaction)
429
+
333
430
  if (this.list.isOpen) {
334
431
  this.narrowCompletions()
335
432
  }
@@ -439,8 +536,25 @@ export class CodeEditorController {
439
536
  }
440
537
 
441
538
  private onKeydown(event: KeyboardEvent): boolean {
442
- if (!this.list.isOpen || event.ctrlKey || event.metaKey || event.altKey)
539
+ if (event.ctrlKey || event.metaKey || event.altKey)
540
+ return false
541
+
542
+ if (!this.list.isOpen) {
543
+ // Escape closes one thing at a time, nearest the reader first. Only
544
+ // with nothing open does it reach the editor, where it frees Tab.
545
+ if (event.key !== 'Escape' || event.shiftKey)
546
+ return false
547
+ if (this.view.hoverOpen || this.hoverTarget) {
548
+ this.closeHover()
549
+ return true
550
+ }
551
+ if (this.signatureTarget) {
552
+ this.closeSignature()
553
+ return true
554
+ }
555
+
443
556
  return false
557
+ }
444
558
 
445
559
  switch (event.key) {
446
560
  case 'ArrowDown':
@@ -479,6 +593,7 @@ export class CodeEditorController {
479
593
  if (!this.list.isOpen) {
480
594
  if (this.popupWasOpen) {
481
595
  this.popupWasOpen = false
596
+ this.setPopupSide('')
482
597
  this.hooks.onPopup(CLOSED_POPUP)
483
598
  }
484
599
  return
@@ -487,6 +602,7 @@ export class CodeEditorController {
487
602
  this.popupWasOpen = true
488
603
  const anchor = this.view.caretAnchor(this.list.from)
489
604
  const above = anchor.spaceBelow < POPUP_ROOM && anchor.spaceAbove > anchor.spaceBelow
605
+ this.setPopupSide(above ? 'above' : 'below')
490
606
  const selected = this.list.selectedIndex
491
607
  const items = this.list.visible.slice(0, POPUP_LIMIT).map((entry, index) => ({
492
608
  id: `${this.popupId}-${index}`,
@@ -504,14 +620,270 @@ export class CodeEditorController {
504
620
  left: anchor.left,
505
621
  top: above ? anchor.top : anchor.bottom,
506
622
  placement: above ? 'above' : 'below',
623
+ detail: this.list.selected?.detail ?? '',
624
+ documentation: this.list.selected?.documentation ?? '',
507
625
  })
508
626
  }
509
627
 
628
+ /** The list and the signature both want the caret line. The list has it first. */
629
+ private setPopupSide(side: 'above' | 'below' | ''): void {
630
+ if (side === this.popupSide)
631
+ return
632
+
633
+ this.popupSide = side
634
+ if (this.signatureTarget?.help)
635
+ this.drawSignature(this.currentCall()?.active ?? 0)
636
+ }
637
+
638
+ // ------------------------------------------------------------------- hover
639
+
640
+ setHover(enabled: boolean): void {
641
+ this.hoverEnabled = enabled
642
+ if (!enabled)
643
+ this.closeHover()
644
+ }
645
+
646
+ /** The word at an offset, as offsets. */
647
+ private wordRangeAt(offset: number, inclusiveEnd: boolean): { from: number, to: number, word: string } | null {
648
+ const line = this.core.doc.lineAt(Math.max(0, Math.min(this.core.doc.length, offset)))
649
+ const range = wordAt(line.text, offset - line.from, inclusiveEnd)
650
+
651
+ return range ? { from: line.from + range.from, to: line.from + range.to, word: range.word } : null
652
+ }
653
+
654
+ private onPointerRest(offset: number | null): void {
655
+ if (!this.hoverEnabled)
656
+ return
657
+
658
+ const range = offset === null ? null : this.wordRangeAt(offset, false)
659
+ if (!range) {
660
+ if (!this.hoverTarget?.explicit)
661
+ this.closeHover()
662
+ return
663
+ }
664
+
665
+ // Still on the word already asked about: nothing new to ask.
666
+ const current = this.hoverTarget
667
+ if (current && current.from === range.from && current.to === range.to)
668
+ return
669
+
670
+ this.requestHover(offset!, range, false)
671
+ }
672
+
673
+ private requestHover(offset: number, range: { from: number, to: number, word: string }, explicit: boolean): void {
674
+ this.view.hideHover()
675
+ // A new serial makes any answer still on its way a stale one.
676
+ this.hoverTarget = { from: range.from, to: range.to, explicit, serial: ++this.hoverSerial }
677
+ const position = this.core.doc.positionAt(offset)
678
+ this.hooks.onHoverRequest?.({ line: position.line, column: position.column, from: range.from, to: range.to, word: range.word, explicit })
679
+ }
680
+
681
+ /**
682
+ * Show a hover: Markdown or plain text, as a language server gives it. A
683
+ * fenced block is drawn as code in the fence's language (the editor's when
684
+ * it names none), the rest as text.
685
+ *
686
+ * Pass the position the answer is for. An answer for a word the pointer has
687
+ * since left is dropped, which is how a slow answer never lands on the wrong
688
+ * word. Without a position it goes to the word last asked about, or the one
689
+ * at the caret. Empty content closes the hover.
690
+ */
691
+ showHover(content: string | null | undefined, position?: Position): void {
692
+ if (this.destroyed)
693
+ return
694
+
695
+ let target = this.hoverTarget
696
+ if (position) {
697
+ const offset = this.core.doc.offsetAt(position)
698
+ if (target && (offset < target.from || offset > target.to))
699
+ return
700
+ if (!target) {
701
+ const range = this.wordRangeAt(offset, true) ?? { from: offset, to: offset }
702
+ target = { from: range.from, to: range.to, explicit: false, serial: ++this.hoverSerial }
703
+ }
704
+ }
705
+ else if (!target) {
706
+ const head = this.core.main.head
707
+ const range = this.wordRangeAt(head, true) ?? { from: head, to: head }
708
+ target = { from: range.from, to: range.to, explicit: true, serial: ++this.hoverSerial }
709
+ }
710
+
711
+ const segments = typeof content === 'string' ? parseHoverContent(content) : []
712
+ if (segments.length === 0) {
713
+ this.closeHover()
714
+ return
715
+ }
716
+
717
+ this.hoverTarget = target
718
+ const blocks: HintBlock[] = segments.map(segment => ({ kind: segment.kind, text: segment.text }))
719
+ this.view.showHover(blocks, target.from)
720
+ if (target.explicit)
721
+ this.view.announce(hoverPlainText(content!))
722
+
723
+ // Colour arrives a moment later. A grammar the editor already has is a
724
+ // resolved promise away; one it has to load must not hold the hint back.
725
+ const { serial } = target
726
+ const pending: Array<Promise<void>> = []
727
+ segments.forEach((segment, index) => {
728
+ if (segment.kind !== 'code')
729
+ return
730
+
731
+ pending.push(this.hintTokenizer(segment.language || this.language).then((tokenizer) => {
732
+ if (tokenizer)
733
+ blocks[index] = { kind: 'code', text: segment.text, html: renderCodeHtml(tokenizer, segment.text) }
734
+ }))
735
+ })
736
+ if (pending.length > 0) {
737
+ void Promise.all(pending).then(() => {
738
+ if (!this.destroyed && this.hoverTarget?.serial === serial && this.view.hoverOpen && blocks.some(block => block.html !== undefined))
739
+ this.view.showHover(blocks, target.from)
740
+ })
741
+ }
742
+ }
743
+
744
+ closeHover(): void {
745
+ if (!this.hoverTarget && !this.view.hoverOpen)
746
+ return
747
+
748
+ this.hoverTarget = null
749
+ this.hoverSerial++
750
+ this.view.hideHover()
751
+ }
752
+
753
+ private hintTokenizer(language: string): Promise<LineTokenizer<any> | null> {
754
+ let tokenizer = this.hintTokenizers.get(language)
755
+ if (!tokenizer) {
756
+ tokenizer = this.highlight ? createLanguageTokenizer(language).catch(() => null) : Promise.resolve(null)
757
+ this.hintTokenizers.set(language, tokenizer)
758
+ }
759
+
760
+ return tokenizer
761
+ }
762
+
763
+ // --------------------------------------------------------------- signature
764
+
765
+ setSignatureHelp(enabled: boolean): void {
766
+ this.signatureEnabled = enabled
767
+ if (!enabled)
768
+ this.closeSignature()
769
+ }
770
+
771
+ /** The call the caret is in, with its parenthesis as a document offset. */
772
+ private currentCall(): { open: number, active: number } | null {
773
+ if (!rangeEmpty(this.core.main))
774
+ return null
775
+
776
+ const head = this.core.main.head
777
+ const start = Math.max(0, head - CALL_WINDOW)
778
+ const context = callContext(this.core.doc.slice(start, head))
779
+
780
+ return context ? { open: start + context.open, active: context.active } : null
781
+ }
782
+
783
+ private requestSignature(explicit: boolean, trigger: string): void {
784
+ if (this.core.readOnly)
785
+ return
786
+
787
+ const call = this.currentCall()
788
+ if (!call) {
789
+ this.closeSignature()
790
+ return
791
+ }
792
+
793
+ // The same call keeps what it is showing until the new answer replaces it.
794
+ if (this.signatureTarget?.open !== call.open) {
795
+ this.view.hideSignature()
796
+ this.signatureTarget = { open: call.open, help: null, base: call.active }
797
+ }
798
+
799
+ const head = this.core.main.head
800
+ const cursor = this.core.cursor
801
+ this.hooks.onSignatureRequest?.({ line: cursor.line, column: cursor.column, offset: head, start: call.open + 1, active: call.active, trigger, explicit })
802
+ }
803
+
804
+ /**
805
+ * Show a signature above the caret with one parameter marked. `active` is
806
+ * the parameter being written; left out, it is counted from the commas
807
+ * typed so far. A null, or a caret that is in no call, closes it.
808
+ */
809
+ showSignature(help: SignatureHelp | null | undefined): void {
810
+ if (this.destroyed)
811
+ return
812
+
813
+ const call = this.currentCall()
814
+ if (!help || !help.label || !call) {
815
+ this.closeSignature()
816
+ return
817
+ }
818
+
819
+ this.signatureTarget = { open: call.open, help, base: call.active }
820
+ this.drawSignature(call.active)
821
+ }
822
+
823
+ closeSignature(): void {
824
+ if (!this.signatureTarget)
825
+ return
826
+
827
+ this.signatureTarget = null
828
+ this.view.hideSignature()
829
+ }
830
+
831
+ private drawSignature(active: number): void {
832
+ const target = this.signatureTarget
833
+ if (!target?.help)
834
+ return
835
+
836
+ const { help } = target
837
+ // The host's count is the truth for the moment it was given. Commas typed
838
+ // since move it on, so the mark does not wait for the next answer.
839
+ const index = help.active === undefined ? active : help.active + (active - target.base)
840
+ const parts = signatureParts({ ...help, active: index })
841
+ const head = this.core.main.head
842
+ const sameLine = this.core.doc.lineIndexAt(target.open) === this.core.doc.lineIndexAt(head)
843
+
844
+ this.view.showSignature({
845
+ before: parts.before,
846
+ active: parts.active,
847
+ after: parts.after,
848
+ documentation: parts.parameterDocumentation || help.documentation || '',
849
+ }, sameLine ? target.open + 1 : head, this.popupSide === 'above' ? 'below' : this.popupSide === 'below' ? 'above' : undefined)
850
+ }
851
+
852
+ /** Keep the signature with the call it is for, and ask when one begins. */
853
+ private followSignature(transaction: Transaction): void {
854
+ const target = this.signatureTarget
855
+ if (target && transaction.docChanged)
856
+ target.open = mapOffset(target.open, transaction.changes, 1)
857
+
858
+ const typed = transaction.docChanged && (transaction.kind === 'type' || transaction.kind === 'pair')
859
+ ? this.core.doc.slice(Math.max(0, this.core.main.head - 1), this.core.main.head)
860
+ : ''
861
+ if (this.signatureEnabled && (typed === '(' || typed === ',')) {
862
+ this.requestSignature(false, typed)
863
+ if (this.signatureTarget?.help)
864
+ this.drawSignature(this.currentCall()?.active ?? 0)
865
+ return
866
+ }
867
+
868
+ if (!target)
869
+ return
870
+
871
+ const call = this.currentCall()
872
+ if (!call)
873
+ this.closeSignature()
874
+ else if (call.open !== target.open)
875
+ this.requestSignature(false, '')
876
+ else
877
+ this.drawSignature(call.active)
878
+ }
879
+
510
880
  // ----------------------------------------------------------------- teardown
511
881
 
512
882
  destroy(): void {
513
883
  this.destroyed = true
514
884
  this.list.close()
885
+ this.hoverTarget = null
886
+ this.signatureTarget = null
515
887
  this.view.destroy()
516
888
  }
517
889
  }
@@ -19,6 +19,8 @@ export interface CompletionItem {
19
19
  insert?: string
20
20
  /** A short note beside the label, such as a type. */
21
21
  detail?: string
22
+ /** A longer note, shown under the list while the item is selected. */
23
+ documentation?: string
22
24
  /** What sort of thing it is (`function`, `property`), for an icon or a tint. */
23
25
  kind?: string
24
26
  /** Matched instead of the label when set. */