0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-06 20:52:40 +00:00

Use capture groups, add default "alt text" if none selected

Also allow whitespace at end and start of selection, so you don't have to be perfect.
This commit is contained in:
Trevor Buckner
2021-12-02 11:45:10 -05:00
parent 76553d1e65
commit 2586a871e1

View File

@@ -156,16 +156,17 @@ const CodeEditor = createClass({
}, },
makeLink : function() { makeLink : function() {
const isLink = /^\[(.*)(\]\()(.*)\)$/g; const isLink = /^\[(.*)\]\((.*)\)$/;
const selection = this.codeMirror.getSelection(); const selection = this.codeMirror.getSelection().trim();
if(isLink.test(selection) == true){ let match;
const altText = selection.slice(1, selection.lastIndexOf('](')); // could likely be done better with capture groups if(match = isLink.exec(selection)){
const url = selection.slice(selection.lastIndexOf('](') + 2, -1); // could likely be done better with capture groups const altText = match[1];
const url = match[2];
this.codeMirror.replaceSelection(`${altText} ${url}`); this.codeMirror.replaceSelection(`${altText} ${url}`);
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror.getCursor();
this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - url.length }, { line: cursor.line, ch: cursor.ch }); this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - url.length }, { line: cursor.line, ch: cursor.ch });
} else { } else {
this.codeMirror.replaceSelection(`[${selection}](url)`); this.codeMirror.replaceSelection(`[${selection || 'alt text'}](url)`);
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror.getCursor();
this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - 4 }, { line: cursor.line, ch: cursor.ch - 1 }); this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - 4 }, { line: cursor.line, ch: cursor.ch - 1 });
} }