Line data Source code
1 : import {
2 : canonicalCombo,
3 : canvasCommandForWrittenKeys,
4 : modifierLabel
5 : } from '@/platform/keybindings/canvasActionShortcuts'
6 :
7 : /** Reports every key sequence a command is bound to now. */
8 : export type KeySequenceResolver = (commandId: string) => string[][]
9 :
10 1 : const NON_PROSE_ELEMENTS = new Set([
11 : 'CODE',
12 : 'PRE',
13 : 'KBD',
14 : 'A',
15 : 'SCRIPT',
16 : 'STYLE'
17 : ])
18 :
19 1 : const INLINE_ELEMENTS = new Set([
20 : 'SPAN',
21 : 'STRONG',
22 : 'EM',
23 : 'B',
24 : 'I',
25 : 'U',
26 : 'S',
27 : 'SMALL',
28 : 'MARK',
29 : 'SUB',
30 : 'SUP',
31 : 'Q',
32 : 'CITE',
33 : 'ABBR',
34 : 'TIME',
35 : 'VAR',
36 : 'SAMP',
37 : 'DFN',
38 : 'BDI',
39 : 'BDO',
40 : 'FONT',
41 : 'INS',
42 : 'DEL',
43 : 'RUBY',
44 : 'RT',
45 : 'RP'
46 : ])
47 :
48 1 : const MODIFIER = String.raw`ctrl|control|cmd|command|meta|⌘|alt|option|opt|⌥|shift|⇧`
49 :
50 1 : const MODIFIER_SLOT = String.raw`(?:${MODIFIER})(?:\s*/\s*(?:${MODIFIER})){0,3}`
51 :
52 1 : const NAMED_KEY = String.raw`f\d{1,2}|enter|return|escape|esc|spacebar|space|tab|delete|del|backspace|home|end|pageup|pagedown|up|down|left|right`
53 :
54 1 : const SINGLE_KEY =
55 : String.raw`[a-z0-9` + '`' + String.raw`~!@#$%^&*()\-_=+\[\]{}\\|;:'",.<>/?]`
56 :
57 1 : const MODIFIER_BEARING_COMBO =
58 : String.raw`(?<![a-z0-9/])${MODIFIER_SLOT}(?:\s*\+\s*${MODIFIER_SLOT}){0,3}` +
59 : String.raw`\s*\+\s*(?:${NAMED_KEY}|${SINGLE_KEY})(?![a-z0-9])`
60 :
61 0 : function keyLabel(sequence: string): string {
62 0 : return sequence.length === 1 ? sequence.toUpperCase() : sequence
63 : }
64 :
65 0 : function keycaps(sequences: string[]): DocumentFragment {
66 0 : const fragment = document.createDocumentFragment()
67 0 : sequences.forEach((sequence, index) => {
68 0 : if (index > 0) fragment.append('+')
69 0 : const kbd = document.createElement('kbd')
70 0 : kbd.textContent = keyLabel(sequence)
71 0 : fragment.append(kbd)
72 : })
73 0 : return fragment
74 : }
75 :
76 0 : function slotKey(slot: string): string | undefined {
77 0 : const spellings = slot.split('/')
78 0 : if (spellings.length === 1) return modifierLabel(slot) ?? slot
79 0 : if (spellings.some((spelling) => !spelling.trim())) return slot
80 :
81 0 : const labels = spellings.map((spelling) => modifierLabel(spelling.trim()))
82 0 : const [first] = labels
83 0 : return first && labels.every((label) => label === first) ? first : undefined
84 : }
85 :
86 0 : function comboKeys(combo: string): string[] | undefined {
87 0 : const slots = combo.split(/\s*\+\s*/)
88 0 : const keys: string[] = []
89 0 : for (const [index, slot] of slots.entries()) {
90 0 : if (!slot) {
91 0 : if (index > 0 && index === slots.length - 1) keys.push('+')
92 0 : continue
93 : }
94 0 : const key = slotKey(slot)
95 0 : if (key === undefined) return undefined
96 0 : keys.push(key)
97 : }
98 0 : return keys
99 : }
100 :
101 0 : function liveKeys(
102 : written: string[],
103 : resolve: KeySequenceResolver
104 : ): string[] | undefined {
105 0 : const commandId = canvasCommandForWrittenKeys(written)
106 0 : if (!commandId) return written
107 :
108 0 : const bound = resolve(commandId)
109 0 : const asWritten = canonicalCombo(written)
110 0 : return bound.find((keys) => canonicalCombo(keys) === asWritten) ?? bound.at(0)
111 : }
112 :
113 : interface Match {
114 : start: number
115 : end: number
116 : keys: string[]
117 : }
118 :
119 0 : function matchesIn(text: string, resolve: KeySequenceResolver): Match[] {
120 0 : const matches: Match[] = []
121 0 : for (const match of text.matchAll(new RegExp(MODIFIER_BEARING_COMBO, 'gi'))) {
122 0 : const written = comboKeys(match[0])
123 0 : const keys = written && liveKeys(written, resolve)
124 0 : if (keys) {
125 0 : matches.push({
126 : start: match.index,
127 : end: match.index + match[0].length,
128 : keys
129 : })
130 : }
131 : }
132 0 : return matches
133 : }
134 :
135 0 : function spliceMatches(node: Text, nodeStart: number, matches: Match[]): void {
136 0 : const text = node.data
137 0 : const nodeEnd = nodeStart + text.length
138 0 : const fragment = document.createDocumentFragment()
139 0 : let cursor = 0
140 :
141 0 : for (const match of matches) {
142 0 : const localStart = Math.max(match.start, nodeStart) - nodeStart
143 0 : if (localStart > cursor) fragment.append(text.slice(cursor, localStart))
144 0 : if (match.start >= nodeStart) fragment.append(keycaps(match.keys))
145 0 : cursor = Math.min(match.end, nodeEnd) - nodeStart
146 : }
147 :
148 0 : if (cursor < text.length) fragment.append(text.slice(cursor))
149 0 : node.replaceWith(fragment)
150 : }
151 :
152 0 : function rewriteRun(run: Text[], resolve: KeySequenceResolver): boolean {
153 0 : const matches = matchesIn(run.map((node) => node.data).join(''), resolve)
154 0 : if (matches.length === 0) return false
155 :
156 0 : let nodeStart = 0
157 0 : let pending = 0
158 0 : for (const node of run) {
159 0 : const nodeEnd = nodeStart + node.data.length
160 0 : let past = pending
161 0 : while (past < matches.length && matches[past].start < nodeEnd) past++
162 0 : spliceMatches(node, nodeStart, matches.slice(pending, past))
163 0 : while (pending < matches.length && matches[pending].end <= nodeEnd)
164 0 : pending++
165 0 : nodeStart = nodeEnd
166 : }
167 0 : return true
168 : }
169 :
170 0 : function isProse(node: Text): boolean {
171 0 : for (let parent = node.parentElement; parent; parent = parent.parentElement) {
172 0 : if (NON_PROSE_ELEMENTS.has(parent.tagName)) return false
173 : }
174 0 : return true
175 : }
176 :
177 0 : function blockOf(node: Text): Element | null {
178 0 : let parent = node.parentElement
179 0 : while (parent && INLINE_ELEMENTS.has(parent.tagName)) {
180 0 : parent = parent.parentElement
181 : }
182 0 : return parent
183 : }
184 :
185 0 : function proseRuns(root: DocumentFragment): Text[][] {
186 0 : const walker = document.createTreeWalker(
187 : root,
188 : NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT
189 : )
190 0 : const runs: Text[][] = []
191 0 : let current: Text[] = []
192 0 : let currentBlock: Element | null = null
193 :
194 0 : const endRun = () => {
195 0 : if (current.length > 0) runs.push(current)
196 0 : current = []
197 0 : currentBlock = null
198 : }
199 :
200 0 : while (walker.nextNode()) {
201 0 : const node = walker.currentNode
202 0 : if (node instanceof Element) {
203 0 : if (!INLINE_ELEMENTS.has(node.tagName)) endRun()
204 0 : continue
205 : }
206 0 : if (!(node instanceof Text)) continue
207 0 : const text = node
208 0 : const block = isProse(text) ? blockOf(text) : null
209 0 : if (!block || block !== currentBlock) {
210 0 : endRun()
211 0 : currentBlock = block
212 : }
213 0 : if (block) current.push(text)
214 : }
215 0 : endRun()
216 0 : return runs
217 : }
218 :
219 : /** Renders the key combos in reply HTML as keycaps showing the user's binding. */
220 0 : export function renderShortcutKeycaps(
221 : html: string,
222 : resolve: KeySequenceResolver
223 : ): string {
224 0 : if (!html.includes('+')) return html
225 :
226 0 : const template = document.createElement('template')
227 0 : template.innerHTML = html
228 :
229 0 : let rewritten = false
230 0 : for (const run of proseRuns(template.content)) {
231 0 : if (rewriteRun(run, resolve)) rewritten = true
232 : }
233 0 : return rewritten ? template.innerHTML : html
234 : }
|