From 736f2e9a298220f66c1f8ce2e17440f456035814 Mon Sep 17 00:00:00 2001 From: AkiraFukushima Date: Sat, 4 Aug 2018 12:09:01 +0900 Subject: [PATCH] refs #352 Add function to take account name from text --- src/renderer/utils/suggestText.js | 27 +++++++++++++++++++ test/mocha/suggestText.spec.js | 45 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 src/renderer/utils/suggestText.js create mode 100644 test/mocha/suggestText.spec.js diff --git a/src/renderer/utils/suggestText.js b/src/renderer/utils/suggestText.js new file mode 100644 index 00000000..2f7dd800 --- /dev/null +++ b/src/renderer/utils/suggestText.js @@ -0,0 +1,27 @@ +// https://github.com/tootsuite/mastodon/blob/master/app/javascript/mastodon/components/autosuggest_textarea.js +const textAtCursorMatch = (str, cursorPosition, separator = '@') => { + let word + + let left = str.slice(0, cursorPosition).search(/\S+$/) + let right = str.slice(cursorPosition).search(/\s/) + + if (right < 0) { + word = str.slice(left) + } else { + word = str.slice(left, right + cursorPosition) + } + + if (!word || word.trim().length < 3 || [separator].indexOf(word[0]) === -1) { + return [null, null] + } + + word = word.trim().toLowerCase() + + if (word.length > 0) { + return [left + 1, word] + } else { + return [null, null] + } +} + +export default textAtCursorMatch diff --git a/test/mocha/suggestText.spec.js b/test/mocha/suggestText.spec.js new file mode 100644 index 00000000..722ef5fe --- /dev/null +++ b/test/mocha/suggestText.spec.js @@ -0,0 +1,45 @@ +import assert from 'assert' +import suggestText from '../../src/renderer/utils/suggestText' + +describe('account', () => { + context('Only account name', () => { + const str = '@h3pote' + it('should match', () => { + const [start, word] = suggestText(str, 7) + assert.strictEqual(str, word) + assert.strictEqual(start, 1) + }) + }) + context('Beginning of the sentence', () => { + const str = '@h3pote toot body' + it('should match', () => { + const [start, word] = suggestText(str, 7) + assert.strictEqual(word, '@h3pote') + assert.strictEqual(start, 1) + }) + }) + context('Halfway of the sentence', () => { + const str = 'toot body @h3pote toot' + it('should match', () => { + const [start, word] = suggestText(str, 17) + assert.strictEqual(word, '@h3pote') + assert.strictEqual(start, 11) + }) + }) + context('End of the sentence', () => { + const str = 'toot body @h3pote' + it('should match', () => { + const [start, word] = suggestText(str, 17) + assert.strictEqual(word, '@h3pote') + assert.strictEqual(start, 11) + }) + }) + context('No space', () => { + const str = 'tootbody@h3pote' + it('should not match', () => { + const [start, word] = suggestText(str, 15) + assert.strictEqual(word, null) + assert.strictEqual(start, null) + }) + }) +})