Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

started creating a vim config for custom keymaps (#508)

ggrandie0d60216d0b4
diff --git a/apps/web/src/app/challenge/_components/settings/settings-form.tsx b/apps/web/src/app/challenge/_components/settings/settings-form.tsx
index 88cfd359..a09dd24c 100644
--- a/apps/web/src/app/challenge/_components/settings/settings-form.tsx
+++ b/apps/web/src/app/challenge/_components/settings/settings-form.tsx
@@ -19,22 +19,19 @@ import {
SelectValue,
useToast,
DialogFooter,
+ Textarea,
} from '@repo/ui';
-import { useEditorSettingsStore } from '@repo/monaco/settings-store';
+import { DEFAULT_SETTINGS, useEditorSettingsStore } from '@repo/monaco/settings-store';
const formSchema = z.object({
fontSize: z.string(),
bindings: z.string(),
tabSize: z.string(),
+ vimConfig: z.string(),
});
export type FormSchema = z.infer<typeof formSchema>;
-export const DEFAULT_SETTINGS = {
- fontSize: '12',
- bindings: 'standard',
- tabSize: '2',
-};
export function SettingsForm() {
const { toast } = useToast();
@@ -90,19 +87,19 @@ export function SettingsForm() {
/>
<FormField
control={form.control}
- name="bindings"
+ name="tabSize"
render={({ field }) => (
<FormItem className="mb-3">
- <FormLabel>Key Bindings</FormLabel>
+ <FormLabel>Tab Size</FormLabel>
<Select defaultValue={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger>
- <SelectValue placeholder="Select a font size" />
+ <SelectValue placeholder="Select a tab size" />
</SelectTrigger>
</FormControl>
<SelectContent>
- <SelectItem value="standard">Standard</SelectItem>
- <SelectItem value="vim">Vim</SelectItem>
+ <SelectItem value="2">2 spaces</SelectItem>
+ <SelectItem value="4">4 spaces</SelectItem>
</SelectContent>
</Select>
<FormMessage />
@@ -111,25 +108,40 @@ export function SettingsForm() {
/>
<FormField
control={form.control}
- name="tabSize"
+ name="bindings"
render={({ field }) => (
<FormItem className="mb-3">
- <FormLabel>Tab Size</FormLabel>
+ <FormLabel>Key Bindings</FormLabel>
<Select defaultValue={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger>
- <SelectValue placeholder="Select a tab size" />
+ <SelectValue placeholder="Select a font size" />
</SelectTrigger>
</FormControl>
<SelectContent>
- <SelectItem value="2">2 spaces</SelectItem>
- <SelectItem value="4">4 spaces</SelectItem>
+ <SelectItem value="standard">Standard</SelectItem>
+ <SelectItem value="vim">Vim</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
+ <FormField
+ control={form.control}
+ name="vimConfig"
+ render={({ field: { value, ...field } }) => (
+ <FormItem className="mb-3">
+ <FormLabel>Vim Config</FormLabel>
+ <Textarea
+ value={value || DEFAULT_SETTINGS.vimConfig}
+ className="resize-none font-mono"
+ {...field}
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
<DialogFooter>
<DialogPrimitive.Close asChild>
diff --git a/apps/web/src/components/landing/hero.tsx b/apps/web/src/components/landing/hero.tsx
index daf5df5a..13ea7676 100644
--- a/apps/web/src/components/landing/hero.tsx
+++ b/apps/web/src/components/landing/hero.tsx
@@ -53,7 +53,7 @@ function Hero() {
skills through interactive coding challenges, discussions, and knowledge sharing
</Balancer>
</p>
- <div className="flex flex-col md:flex-row gap-3">
+ <div className="flex flex-col gap-3 md:flex-row">
<Button
asChild
className="hero-join-button group relative mx-auto w-fit overflow-hidden rounded-xl p-[2px] font-bold transition-all duration-300 hover:bg-transparent hover:shadow-[0_0_2rem_-0.5rem_#3178c6] dark:hidden md:mr-0 lg:mr-auto"
@@ -84,7 +84,7 @@ function Hero() {
<a
target="_blank"
rel="noreferrer"
- className="md:inline-flex gap-1"
+ className="gap-1 md:inline-flex"
href="https://github.com/bautistaaa/typehero"
>
<Github className="h-4 w-4" />
@@ -99,7 +99,7 @@ function Hero() {
<a
target="_blank"
rel="noreferrer"
- className="md:inline-flex gap-1"
+ className="gap-1 md:inline-flex"
href="https://twitter.com/typeheroapp"
>
<Twitter className="h-4 w-4" />
diff --git a/packages/monaco/monaco-vim.d.ts b/packages/monaco/monaco-vim.d.ts
index c2a4650f..9dded1e6 100644
--- a/packages/monaco/monaco-vim.d.ts
+++ b/packages/monaco/monaco-vim.d.ts
@@ -4,17 +4,27 @@ declare module 'monaco-vim' {
export function initVimMode(
editor: monaco.editor.IStandaloneCodeEditor,
statusbarNode?: Element | null,
- ): VimMode;
+ ): CMAdapter;
type VimModes = 'insert' | 'normal' | 'visual';
- export class VimMode {
+ class CMAdapter {
/** removes the attached vim bindings */
dispose(): void;
+ attached: boolean;
+
+ editor: monaco.editor.IStandaloneCodeEditor;
+
+ statusBar: {
+ clear(): void;
+ node: HTMLElement;
+ };
+
+ /** @see https://codemirror.net/5/doc/manual.html#vimapi */
static Vim: {
map(lhs: string, rhs: string, ctx: VimModes): void;
- unmap(lhs: string, ctx: VimModes): boolean;
+ unmap(lhs: string, ctx: VimModes | false): boolean;
noremap(lhs: string, rhs: string, ctx: VimModes): void;
mapCommand(
@@ -28,9 +38,9 @@ declare module 'monaco-vim' {
defineAction(
name: string,
fn: (
- cm: { editor: monaco.editor.IStandaloneCodeEditor },
- arg2: { registerName: null | string; repeat: number; repeatIsExplicit: boolean },
- arg3: unknown,
+ ctx: CMAdapter,
+ // TODO: Document other args
+ ...args: [unknown, unknown]
) => void,
): void;
@@ -38,15 +48,35 @@ declare module 'monaco-vim' {
name: string,
prefix: string | undefined,
fn: (
- ctx: { editor: monaco.editor.IStandaloneCodeEditor },
+ ctx: Ctx,
data: {
- argString: string[];
- args: string;
commandName: string;
input: string;
- } & ({ line: undefined } | { line: number; lineEnd: number }),
+ } & (
+ | {
+ argString: string;
+ args: [string, ...string[]];
+ }
+ | { argString?: never; args?: never }
+ ) &
+ ({ line: undefined } | { line: number; lineEnd: number }),
) => void,
): void;
+
+ /** clears user created mappings */
+ mapclear(ctx?: VimMode): void;
+
+ /** call this before `VimMode.Vim.handleKey` */
+ maybeInitVimState_(cma: CMAdapter): void;
+
+ /**
+ * calls an ex command, equivalent to `:` in vim
+ *
+ * *If it fails with `vim is null` call `VimMode.Vim.maybeInitVimState_` first*
+ */
+ handleEx(cma: CMAdapter, ex: string): void;
};
}
+
+ export { CMAdapter as VimMode, type CMAdapter };
}
diff --git a/packages/monaco/src/code-editor.tsx b/packages/monaco/src/code-editor.tsx
index 98467b57..594c7bb7 100644
--- a/packages/monaco/src/code-editor.tsx
+++ b/packages/monaco/src/code-editor.tsx
@@ -28,7 +28,7 @@ const DEFAULT_OPTIONS = {
} as const satisfies EditorProps['options'];
export const LIB_URI = 'file:///asserts.d.ts';
-// eslint-disable-next-line @typescript-eslint/consistent-type-imports
+
export function loadCheckingLib(monaco: typeof import('monaco-editor')) {
if (!monaco.editor.getModel(monaco.Uri.parse(LIB_URI))) {
monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, LIB_URI);
diff --git a/packages/monaco/src/index.tsx b/packages/monaco/src/index.tsx
index e8617018..d888d1af 100644
--- a/packages/monaco/src/index.tsx
+++ b/packages/monaco/src/index.tsx
@@ -1,6 +1,5 @@
'use client';
-import { useMonaco } from '@monaco-editor/react';
import clsx from 'clsx';
import { Loader2 } from '@repo/ui/icons';
import type * as monaco from 'monaco-editor';
@@ -68,6 +67,7 @@ export function CodePanel(props: CodePanelProps) {
const [testEditorState, setTestEditorState] = useState<monaco.editor.IStandaloneCodeEditor>();
const [userEditorState, setUserEditorState] = useState<monaco.editor.IStandaloneCodeEditor>();
+ const [monacoInstance, setMonacoInstance] = useState<typeof monaco>();
const handleSubmit = async () => {
const hasErrors = tsErrors?.some((e) => e.length) ?? false;
@@ -91,8 +91,6 @@ export function CodePanel(props: CodePanelProps) {
}
};
- const monacoInstance = useMonaco();
-
return (
<>
<div className="sticky top-0 flex h-[40px] items-center justify-end gap-4 border-b border-zinc-300 px-3 py-2 dark:border-zinc-700 dark:bg-[#1e1e1e]">
@@ -100,6 +98,7 @@ export function CodePanel(props: CodePanelProps) {
</div>
<div className="w-full flex-1">
<SplitEditor
+ monaco={monacoInstance}
tests={props.challenge.tests}
userCode={code}
onMount={{
@@ -107,6 +106,8 @@ export function CodePanel(props: CodePanelProps) {
setTestEditorState(editor);
},
user: async (editor, monaco) => {
+ setMonacoInstance(monaco);
+
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
...monaco.languages.typescript.typescriptDefaults.getCompilerOptions(),
strict: true,
diff --git a/packages/monaco/src/settings-store.ts b/packages/monaco/src/settings-store.ts
index 9a5188e0..1ac88a00 100644
--- a/packages/monaco/src/settings-store.ts
+++ b/packages/monaco/src/settings-store.ts
@@ -5,6 +5,16 @@ export const DEFAULT_SETTINGS = {
fontSize: '12',
bindings: 'standard',
tabSize: '2',
+ vimConfig: `" - this is a comment
+" - nmap == normal map
+" - \`:M\` is an ex command to run a monaco action
+nmap K :M<Space>editor.action.showHover
+nmap gd :M<Space>editor.action.goToDeclaration
+nmap gr :M<Space>editor.action.goToReferences
+nmap gi :M<Space>editor.action.goToImplementation
+nmap gx :M<Space>editor.action.openLink
+nmap ]d :M<Space>editor.action.marker.next
+nmap [d :M<Space>editor.action.marker.prev`,
};
type Settings = typeof DEFAULT_SETTINGS;
diff --git a/packages/monaco/src/split-editor.tsx b/packages/monaco/src/split-editor.tsx
index 46ef4a28..c3fa573c 100644
--- a/packages/monaco/src/split-editor.tsx
+++ b/packages/monaco/src/split-editor.tsx
@@ -26,6 +26,7 @@ export interface SplitEditorProps {
tests?: OnChange;
user?: OnChange;
};
+ monaco: typeof import('monaco-editor') | undefined;
}
export default function SplitEditor({
@@ -35,9 +36,8 @@ export default function SplitEditor({
onMount,
onValidate,
onChange,
+ monaco,
}: SplitEditorProps) {
- const monaco = useMonaco();
-
useEffect(() => {
if (monaco) {
const libUri = monaco.Uri.parse(LIB_URI);
diff --git a/packages/monaco/src/vim-keybindings.ts b/packages/monaco/src/vim-keybindings.ts
deleted file mode 100644
index c5778b56..00000000
--- a/packages/monaco/src/vim-keybindings.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { VimMode } from 'monaco-vim';
-
-interface Keybind {
- key: string;
- action: string;
- name: string;
-}
-
-function registerKeybind({ key, action, name }: Keybind) {
- VimMode.Vim.defineAction(name, function (ctx) {
- ctx.editor.trigger('action', action, null);
- });
- VimMode.Vim.mapCommand(key, 'action', name);
-}
-
-const KEYBINDS: Keybind[] = [
- {
- key: 'K',
- action: 'editor.action.showHover',
- name: 'hover',
- },
- {
- key: 'gd',
- action: 'editor.action.goToDeclaration',
- name: 'goToDeclaration',
- },
- {
- key: 'gr',
- action: 'editor.action.goToReferences',
- name: 'goToReferences',
- },
- {
- key: 'gi',
- action: 'editor.action.goToImplementation',
- name: 'goToImplementation',
- },
- {
- key: 'gx',
- action: 'editor.action.openLink',
- name: 'goToLink',
- },
- {
- key: ']d',
- action: 'editor.action.marker.next',
- name: 'nextDiagnostic',
- },
- {
- key: '[d',
- action: 'editor.action.marker.prev',
- name: 'prevDiagnostic',
- },
-];
-
-KEYBINDS.forEach(registerKeybind);
diff --git a/packages/monaco/src/vim-mode.tsx b/packages/monaco/src/vim-mode.tsx
index 6865e808..88de1454 100644
--- a/packages/monaco/src/vim-mode.tsx
+++ b/packages/monaco/src/vim-mode.tsx
@@ -2,17 +2,49 @@
import type * as monaco from 'monaco-editor';
import { useEffect, useRef } from 'react';
-import type { VimMode } from 'monaco-vim';
-import { initVimMode } from 'monaco-vim';
-import { useEditorSettingsStore } from './settings-store';
-import './vim-keybindings';
+import { VimMode, initVimMode } from 'monaco-vim';
+import { DEFAULT_SETTINGS, useEditorSettingsStore } from './settings-store';
+
+VimMode.Vim.defineEx('MonacoCommand', 'M', function monacoExCommand(ctx, { args }) {
+ if (!args) {
+ throw new TypeError('Expected an action to run');
+ }
+
+ // workaround for vim mode not substituting `<Space>` with ` `
+ if (args[0].startsWith('<Space>')) {
+ args[0] = args[0].slice(7);
+ }
+
+ console.log('running monaco command', args);
+
+ ctx.editor.trigger('exCommand', args[0], null);
+});
+
+export function sourceVimCommands(cma: VimMode, vimCommands: string) {
+ VimMode.Vim.mapclear();
+
+ VimMode.Vim.maybeInitVimState_(cma);
+
+ for (const line of vimCommands.split('\n')) {
+ // skip comments
+ if (line.startsWith('"')) continue;
+
+ const trimmed = line.trim();
+
+ // skip empty lines
+ if (!trimmed) continue;
+
+ VimMode.Vim.handleEx(cma, trimmed);
+ }
+}
interface VimStatusBarProps {
editor: monaco.editor.IStandaloneCodeEditor;
}
export function VimStatusBar({ editor }: VimStatusBarProps) {
- const statusBarRef = useRef<HTMLDivElement | null>(null);
+ const statusBarRef = useRef<HTMLDivElement>(null);
+ // NOTE: Maybe doesn't need to be a ref anymore?
const vimModeRef = useRef<VimMode>();
const { settings } = useEditorSettingsStore();
@@ -20,6 +52,8 @@ export function VimStatusBar({ editor }: VimStatusBarProps) {
if (settings.bindings === 'vim') {
vimModeRef.current = initVimMode(editor, statusBarRef.current);
+ sourceVimCommands(vimModeRef.current, settings.vimConfig || DEFAULT_SETTINGS.vimConfig);
+
return () => vimModeRef.current?.dispose();
}
@@ -29,7 +63,7 @@ export function VimStatusBar({ editor }: VimStatusBarProps) {
if (statusBarRef.current) {
statusBarRef.current.textContent = '';
}
- }, [editor, settings.bindings]);
+ }, [editor, settings.bindings, settings.vimConfig]);
return (
<div className="flex w-full">
diff --git a/tooling/config-eslint/utils/rules.js b/tooling/config-eslint/utils/rules.js
index 5f062494..95ebb4e6 100644
--- a/tooling/config-eslint/utils/rules.js
+++ b/tooling/config-eslint/utils/rules.js
@@ -5,6 +5,7 @@ module.exports = {
'no-floating-decimal': 'warn',
'react/no-unescaped-entities': 'off',
'unicorn/filename-case': 'off',
+ '@typescript-eslint/consistent-type-imports': ['warn', { disallowTypeAnnotations: false }],
// Rules below here can be re-enabled when the team wants to address them.
// When this repo was first monorepo'ed and given tighter checks,
// there were too many issues to address all at once.