|
1 | | -import { genericCompletion } from "../genericCompletion"; |
2 | | - |
3 | | -export const completions = genericCompletion({ |
4 | | - options: [ |
5 | | - { label: "http://", type: "constant" }, |
6 | | - { label: "https://", type: "constant" }, |
7 | | - ], |
8 | | - minMatch: 1, |
9 | | -}); |
| 1 | +import { insertCompletionText, pickedCompletion, type Completion } from "@codemirror/autocomplete"; |
| 2 | +import type { EditorView } from "@codemirror/view"; |
| 3 | +import type { GenericCompletionOption } from "@yaakapp-internal/plugins"; |
| 4 | +import { |
| 5 | + genericCompletion, |
| 6 | + type GenericCompletion, |
| 7 | + type GenericCompletionConfig, |
| 8 | +} from "../genericCompletion"; |
| 9 | + |
| 10 | +const protocolOptions: GenericCompletionOption[] = [ |
| 11 | + { label: "http://", type: "constant" }, |
| 12 | + { label: "https://", type: "constant" }, |
| 13 | +]; |
| 14 | + |
| 15 | +export function getUrlCompletionConfig( |
| 16 | + options: GenericCompletionOption[], |
| 17 | + minMatch = 3, |
| 18 | +): GenericCompletionConfig { |
| 19 | + const urlOptions = [ |
| 20 | + ...protocolOptions, |
| 21 | + ...options.filter( |
| 22 | + (option) => !protocolOptions.some((protocol) => protocol.label === option.label), |
| 23 | + ), |
| 24 | + ]; |
| 25 | + return { |
| 26 | + minMatch, |
| 27 | + options: urlOptions.map<GenericCompletion>((option) => ({ |
| 28 | + ...option, |
| 29 | + apply: applyUrlCompletion, |
| 30 | + })), |
| 31 | + }; |
| 32 | +} |
| 33 | + |
| 34 | +export function applyUrlCompletion( |
| 35 | + view: EditorView, |
| 36 | + completion: Completion, |
| 37 | + from: number, |
| 38 | + to: number, |
| 39 | +) { |
| 40 | + const isProtocol = /^https?:\/\/$/.test(completion.label); |
| 41 | + const replaceTo = isProtocol |
| 42 | + ? to + (view.state.sliceDoc(to, to + 3) === "://" ? 3 : 0) |
| 43 | + : view.state.doc.length; |
| 44 | + |
| 45 | + view.dispatch({ |
| 46 | + ...insertCompletionText(view.state, completion.label, from, replaceTo), |
| 47 | + annotations: pickedCompletion.of(completion), |
| 48 | + }); |
| 49 | +} |
| 50 | + |
| 51 | +export const completions = genericCompletion(getUrlCompletionConfig([], 1)); |
0 commit comments