Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better handling of ime input #83

Merged
merged 1 commit into from
Feb 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions dev/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@
<title>Vite App</title>
<style>
#editor {
height: min(540px, 70vh); width: min(960px, 90vw);
height: min(540px, 50vh); width: min(960px, 90vw);
position: absolute; resize: both; overflow: hidden
}
#editor>.cm-editor {width: 100%; height: 100%}
#editor.split>.cm-editor {height: 50%}
</style>
</head>
<body>
<input type="checkbox" id="wrap"> <label for="wrap">wrap</label>
<input type="checkbox" id="html"> <label for="html">html</label>
<input type="checkbox" id="status"> <label for="status">status bar</label>
<input type="checkbox" id="jj"> <label for="jj">map jj to Esc</label>
<div id="toolbar"></div>
<div id="editor"></div>
<script type="module" src="./index.ts"></script>
</body>
Expand Down
177 changes: 123 additions & 54 deletions dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { basicSetup, EditorView } from 'codemirror'
import { highlightActiveLine, keymap } from '@codemirror/view';
import { javascript } from '@codemirror/lang-javascript';
import { xml } from '@codemirror/lang-xml';
import { Vim, vim } from "../src/"
import { Vim, vim } from "../src/index"

import * as commands from "@codemirror/commands";
import { Compartment, EditorState } from '@codemirror/state';
import { Annotation, Compartment, EditorState, Extension, Transaction } from '@codemirror/state';

const doc = `//🌞
import { basicSetup, EditorView } from 'codemirror'
Expand All @@ -24,43 +24,51 @@ new EditorView({

`;


let wrapCheckbox = document.getElementById("wrap") as HTMLInputElement
wrapCheckbox.checked = localStorage.wrap == "true"
wrapCheckbox.onclick = function() {
updateView();
localStorage.wrap = wrapCheckbox.checked;
}
let htmlCheckbox = document.getElementById("html") as HTMLInputElement
htmlCheckbox.checked = localStorage.html == "true"
htmlCheckbox.onclick = function() {
updateView();
localStorage.html = htmlCheckbox.checked;
}
let statusBox = document.getElementById("status") as HTMLInputElement
statusBox.checked = localStorage.status == "true"
statusBox.onclick = function() {
updateView();
localStorage.status = statusBox.checked;
}
let jjBox = document.getElementById("jj") as HTMLInputElement
jjBox.checked = localStorage.jj == "true"
jjBox.onclick = function() {
if (jjBox.checked)
Vim.map("jj", "<Esc>", "insert");
else
Vim.unmap("jj", "insert")
localStorage.status = statusBox.checked;
function addOption(name, description?, onclick?) {
let checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = name;
let label = document.createElement("label");
label.setAttribute("for", name);
label.textContent = description || name;

let value = localStorage[name] == "true"
checkbox.checked = value;
checkbox.onclick = function() {
options[name] = checkbox.checked;
updateView();
if (onclick) onclick(options[name])
localStorage[name] = checkbox.checked;
}
document.getElementById("toolbar")?.append(checkbox, label, " ")
return value
}
jjBox.onclick()

var options = {
wrap: addOption("wrap"),
html: addOption("html"),
status: addOption("status", "status bar"),
jj: addOption("jj", "map jj to Esc", function(on) {
if (on)
Vim.map("jj", "<Esc>", "insert");
else
Vim.unmap("jj", "insert")
}),
split: addOption("split", "", function() {

}),
};




let global = window as any;
global._commands = commands;
global._Vim = Vim;

let view
let enableVim = true
let container = document.querySelector('#editor')!;
let view: EditorView|undefined, view2: EditorView|undefined;
let enableVim = true;
let vimCompartement = new Compartment();

var defaultExtensions = [
Expand All @@ -83,53 +91,114 @@ var defaultExtensions = [
])
]

function saveTab(name) {
return EditorView.updateListener.of((v) => {
if (v.docChanged) {
tabs[name] = v.state;
}
})
}

var tabs = {
js: EditorState.create({
doc: doc,
extensions: [...defaultExtensions, javascript()]
extensions: [...defaultExtensions, javascript(), saveTab("js")]
}),
html: EditorState.create({
doc: document.documentElement.outerHTML,
extensions: [...defaultExtensions, xml()]
extensions: [...defaultExtensions, xml(), saveTab("html")]
})
}
var selectedTab = ""


function updateView() {
if (!view) {
view = global._view = new EditorView({
doc: "",
extensions: defaultExtensions,
parent: document.querySelector('#editor'),
});
}
if (options.split && !view2) createSplit();
if (!options.split && view2) deleteSplit();

if (!view) view = createView();

selectTab(htmlCheckbox.checked ? "html": "js")
selectTab(options.html ? "html": "js")

var extensions = [
enableVim && vim({status: options.status}),
options.wrap && EditorView.lineWrapping,
].filter((x)=>!!x) as Extension[];

view.dispatch({
effects: vimCompartement.reconfigure([
enableVim && vim({status: statusBox.checked}),
wrapCheckbox.checked && EditorView.lineWrapping,
].filter(Boolean))
effects: vimCompartement.reconfigure(extensions)
})
}

function selectTab(tab: string) {
if (selectedTab != tab) {
tabs[selectedTab] = view.state;
selectedTab = tab
view.setState(tabs[selectedTab])
}
if (view) view.setState(tabs[tab])
if (view2) view2.setState(tabs[tab])
}

Vim.defineEx("tabnext", "tabn", () => {
tabs["scratch"] = EditorState.create({
doc: "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
extensions: defaultExtensions,
extensions: [defaultExtensions, saveTab("scratch")],
})
selectTab("scratch")
});



Vim.defineEx("split", "sp", () => {
options.split = !options.split;
updateView();
});



// splitting
let syncAnnotation = Annotation.define<boolean>()

function syncDispatch(tr: Transaction, view: EditorView, other: EditorView) {
view.update([tr])
if (!tr.changes.empty && !tr.annotation(syncAnnotation)) {
let annotations: Annotation<any>[] = [syncAnnotation.of(true)]
let userEvent = tr.annotation(Transaction.userEvent)
if (userEvent) annotations.push(Transaction.userEvent.of(userEvent))
other.dispatch({changes: tr.changes, annotations})
}
}


function createSplit() {
deleteSplit();

view = global._view = new EditorView({
doc: "",
extensions: defaultExtensions,
parent: container,
dispatch: tr => syncDispatch(tr, view!, view2!)
});
view2 = global._view2 = new EditorView({
doc: "",
extensions: defaultExtensions,
parent: container,
dispatch: tr => syncDispatch(tr, view2!, view!)
});

container.classList.add("split")
}

function deleteSplit() {
if (view) view.destroy();
if (view2) view2.destroy();
view = view2 = undefined;
container.classList.remove("split");
}

function createView() {
if (view) view.destroy();
view = global._view = new EditorView({
doc: "",
extensions: defaultExtensions,
parent: container,
});
return view;
}


updateView()
2 changes: 1 addition & 1 deletion src/cm_adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ var specialKey: any = {
Enter: 'CR', ' ': 'Space'
};
var ignoredKeys: any = { Shift: 1, Alt: 1, Command: 1, Control: 1,
CapsLock: 1, AltGraph: 1, Dead: 1 };
CapsLock: 1, AltGraph: 1, Dead: 1, Unidentified: 1 };


let wordChar: RegExp
Expand Down
74 changes: 72 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type EditorViewExtended = EditorView & { cm: CodeMirror };
const vimPlugin = ViewPlugin.fromClass(
class implements PluginValue {
private dom: HTMLElement;
private statusButton: HTMLElement;
public view: EditorViewExtended;
public cm: CodeMirror;
public status = "";
Expand Down Expand Up @@ -88,6 +89,12 @@ const vimPlugin = ViewPlugin.fromClass(

this.dom = document.createElement("span");
this.dom.style.cssText = "position: absolute; right: 10px; top: 1px";
this.statusButton = document.createElement("span");
this.statusButton.onclick = (e) => {
Vim.handleKey(this.cm, "<Esc>", "user");
this.cm.focus();
};
this.statusButton.style.cssText = "cursor: pointer";
}

update(update: ViewUpdate) {
Expand Down Expand Up @@ -140,7 +147,9 @@ const vimPlugin = ViewPlugin.fromClass(
dom.appendChild(dialog);
}
} else {
dom.textContent = `--${(vim.mode || "normal").toUpperCase()}--`;
dom.textContent = ""
this.statusButton.textContent = `--${(vim.mode || "normal").toUpperCase()}--`;
dom.appendChild(this.statusButton);
}

this.dom.textContent = vim.status;
Expand Down Expand Up @@ -228,6 +237,7 @@ const vimPlugin = ViewPlugin.fromClass(
return !!result;
}
lastKeydown = ''
useNextTextInput = false
},
{
eventHandlers: {
Expand All @@ -237,14 +247,74 @@ const vimPlugin = ViewPlugin.fromClass(
},
keydown: function(e: KeyboardEvent, view: EditorView) {
this.lastKeydown = e.key;
this.handleKey(e, view);
if (
this.lastKeydown == "Unidentified"
|| this.lastKeydown == "Process"
|| this.lastKeydown == "Dead"
) {
this.useNextTextInput = true;
} else {
this.useNextTextInput = false;
this.handleKey(e, view);
}
},
},
provide: () => {
return [
EditorView.inputHandler.of((view, from, to, text) => {
var cm = getCM(view);
if (!cm) return false;
var vim = cm.state?.vim;
var vimPlugin = cm.state.vimPlugin;

if (vim && !vim.insertMode && !cm.curOp?.isVimOp) {
if (text.length == 1 && vimPlugin.useNextTextInput) {
vimPlugin.handleKey({
key: text,
preventDefault: ()=>{},
stopPropagation: ()=>{}
});
}
forceEndComposition(view);
return true;
}
return false;
})
]
},

decorations: (v) => v.decorations,
}
);

function forceEndComposition(view: EditorView) {
var parent = view.scrollDOM.parentElement;
if (!parent) return;
var sibling = view.scrollDOM.nextSibling;
var selection = window.getSelection();
var savedSelection = selection && {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};

view.scrollDOM.remove();
parent.insertBefore(view.scrollDOM, sibling);
try {
if (savedSelection && selection) {
selection.setPosition(savedSelection.anchorNode, savedSelection.anchorOffset);
if (savedSelection.focusNode) {
selection.extend(savedSelection.focusNode, savedSelection.focusOffset);
}
}
} catch(e) {
console.error(e);
}
view.focus();
view.contentDOM.dispatchEvent(new CustomEvent("compositionend"));
}

const matchMark = Decoration.mark({ class: "cm-searchMatch" });

const showVimPanel = StateEffect.define<boolean>();
Expand Down