Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feat: implement autocomplete replacement
  • Loading branch information
aviraldg committed Jul 3, 2016
1 parent 8961c87 commit cccc58b
Show file tree
Hide file tree
Showing 13 changed files with 270 additions and 120 deletions.
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -37,6 +37,7 @@
"glob": "^5.0.14",
"highlight.js": "^8.9.1",
"linkifyjs": "^2.0.0-beta.4",
"lodash": "^4.13.1",
"marked": "^0.3.5",
"matrix-js-sdk": "matrix-org/matrix-js-sdk#develop",
"optimist": "^0.6.1",
Expand Down
49 changes: 41 additions & 8 deletions src/RichText.js
@@ -1,12 +1,14 @@
import React from 'react';
import {
Editor,
Modifier,
ContentState,
ContentBlock,
convertFromHTML,
DefaultDraftBlockRenderMap,
DefaultDraftInlineStyle,
CompositeDecorator,
SelectionState
SelectionState,
} from 'draft-js';
import * as sdk from './index';
import * as emojione from 'emojione';
Expand All @@ -25,7 +27,7 @@ const STYLES = {
CODE: 'code',
ITALIC: 'em',
STRIKETHROUGH: 's',
UNDERLINE: 'u'
UNDERLINE: 'u',
};

const MARKDOWN_REGEX = {
Expand Down Expand Up @@ -168,7 +170,7 @@ export function modifyText(contentState: ContentState, rangeToReplace: Selection
text = "";


for(let currentKey = startKey;
for (let currentKey = startKey;
currentKey && currentKey !== endKey;
currentKey = contentState.getKeyAfter(currentKey)) {
let blockText = getText(currentKey);
Expand All @@ -189,14 +191,14 @@ export function modifyText(contentState: ContentState, rangeToReplace: Selection
* Note that this inherently means we make assumptions about what that means (no separator between ContentBlocks, etc)
* Used by autocomplete to show completions when the current selection lies within, or at the edges of a command.
*/
export function getTextSelectionOffsets(selectionState: SelectionState,
contentBlocks: Array<ContentBlock>): {start: number, end: number} {
export function selectionStateToTextOffsets(selectionState: SelectionState,
contentBlocks: Array<ContentBlock>): {start: number, end: number} {
let offset = 0, start = 0, end = 0;
for(let block of contentBlocks) {
if (selectionState.getStartKey() == block.getKey()) {
if (selectionState.getStartKey() === block.getKey()) {
start = offset + selectionState.getStartOffset();
}
if (selectionState.getEndKey() == block.getKey()) {
if (selectionState.getEndKey() === block.getKey()) {
end = offset + selectionState.getEndOffset();
break;
}
Expand All @@ -205,6 +207,37 @@ export function getTextSelectionOffsets(selectionState: SelectionState,

return {
start,
end
end,
};
}

export function textOffsetsToSelectionState({start, end}: {start: number, end: number},
contentBlocks: Array<ContentBlock>): SelectionState {
let selectionState = SelectionState.createEmpty();

for (let block of contentBlocks) {
let blockLength = block.getLength();

if (start !== -1 && start < blockLength) {
selectionState = selectionState.merge({
anchorKey: block.getKey(),
anchorOffset: start,
});
start = -1;
} else {
start -= blockLength;
}

if (end !== -1 && end <= blockLength) {
selectionState = selectionState.merge({
focusKey: block.getKey(),
focusOffset: end,
});
end = -1;
} else {
end -= blockLength;
}
}

return selectionState;
}
29 changes: 20 additions & 9 deletions src/autocomplete/AutocompleteProvider.js
Expand Up @@ -14,25 +14,36 @@ export default class AutocompleteProvider {
* Of the matched commands in the query, returns the first that contains or is contained by the selection, or null.
*/
getCurrentCommand(query: string, selection: {start: number, end: number}): ?Array<string> {
if(this.commandRegex == null)
if (this.commandRegex == null) {
return null;
}

let match = null;
while((match = this.commandRegex.exec(query)) != null) {
let match;
while ((match = this.commandRegex.exec(query)) != null) {
let matchStart = match.index,
matchEnd = matchStart + match[0].length;

console.log(match);

if(selection.start <= matchEnd && selection.end >= matchStart) {
return match;
if (selection.start <= matchEnd && selection.end >= matchStart) {
return {
command: match,
range: {
start: matchStart,
end: matchEnd,
},
};
}
}
this.commandRegex.lastIndex = 0;
return null;
return {
command: null,
range: {
start: -1,
end: -1,
},
};
}

getCompletions(query: String, selection: {start: number, end: number}) {
getCompletions(query: string, selection: {start: number, end: number}) {
return Q.when([]);
}

Expand Down
4 changes: 2 additions & 2 deletions src/autocomplete/Autocompleter.js
Expand Up @@ -9,14 +9,14 @@ const PROVIDERS = [
CommandProvider,
DuckDuckGoProvider,
RoomProvider,
EmojiProvider
EmojiProvider,
].map(completer => completer.getInstance());

export function getCompletions(query: string, selection: {start: number, end: number}) {
return PROVIDERS.map(provider => {
return {
completions: provider.getCompletions(query, selection),
provider
provider,
};
});
}
43 changes: 25 additions & 18 deletions src/autocomplete/CommandProvider.js
@@ -1,42 +1,45 @@
import React from 'react';
import AutocompleteProvider from './AutocompleteProvider';
import Q from 'q';
import Fuse from 'fuse.js';
import {TextualCompletion} from './Components';

const COMMANDS = [
{
command: '/me',
args: '<message>',
description: 'Displays action'
description: 'Displays action',
},
{
command: '/ban',
args: '<user-id> [reason]',
description: 'Bans user with given id'
description: 'Bans user with given id',
},
{
command: '/deop'
command: '/deop',
args: '<user-id>',
description: 'Deops user with given id',
},
{
command: '/encrypt'
},
{
command: '/invite'
command: '/invite',
args: '<user-id>',
description: 'Invites user with given id to current room'
},
{
command: '/join',
args: '<room-alias>',
description: 'Joins room with given alias'
description: 'Joins room with given alias',
},
{
command: '/kick',
args: '<user-id> [reason]',
description: 'Kicks user with given id'
description: 'Kicks user with given id',
},
{
command: '/nick',
args: '<display-name>',
description: 'Changes your display nickname'
}
description: 'Changes your display nickname',
},
];

let COMMAND_RE = /(^\/\w*)/g;
Expand All @@ -47,19 +50,23 @@ export default class CommandProvider extends AutocompleteProvider {
constructor() {
super(COMMAND_RE);
this.fuse = new Fuse(COMMANDS, {
keys: ['command', 'args', 'description']
keys: ['command', 'args', 'description'],
});
}

getCompletions(query: string, selection: {start: number, end: number}) {
let completions = [];
const command = this.getCurrentCommand(query, selection);
if(command) {
let {command, range} = this.getCurrentCommand(query, selection);
if (command) {
completions = this.fuse.search(command[0]).map(result => {
return {
title: result.command,
subtitle: result.args,
description: result.description
completion: result.command + ' ',
component: (<TextualCompletion
title={result.command}
subtitle={result.args}
description={result.description}
/>),
range,
};
});
}
Expand All @@ -71,7 +78,7 @@ export default class CommandProvider extends AutocompleteProvider {
}

static getInstance(): CommandProvider {
if(instance == null)
if (instance == null)
instance = new CommandProvider();

return instance;
Expand Down
14 changes: 10 additions & 4 deletions src/autocomplete/Components.js
@@ -1,13 +1,19 @@
export function TextualCompletion(props: {
import React from 'react';

export function TextualCompletion({
title,
subtitle,
description,
}: {
title: ?string,
subtitle: ?string,
description: ?string
}) {
return (
<div className="mx_Autocomplete_Completion">
<span>{completion.title}</span>
<em>{completion.subtitle}</em>
<span style={{color: 'gray', float: 'right'}}>{completion.description}</span>
<span>{title}</span>
<em>{subtitle}</em>
<span style={{color: 'gray', float: 'right'}}>{description}</span>
</div>
);
}
57 changes: 40 additions & 17 deletions src/autocomplete/DuckDuckGoProvider.js
@@ -1,9 +1,12 @@
import React from 'react';
import AutocompleteProvider from './AutocompleteProvider';
import Q from 'q';
import 'whatwg-fetch';

import {TextualCompletion} from './Components';

const DDG_REGEX = /\/ddg\s+(.+)$/g;
const REFERER = 'vector';
const REFERRER = 'vector';

let instance = null;

Expand All @@ -14,42 +17,62 @@ export default class DuckDuckGoProvider extends AutocompleteProvider {

static getQueryUri(query: String) {
return `http://api.duckduckgo.com/?q=${encodeURIComponent(query)}`
+ `&format=json&no_redirect=1&no_html=1&t=${encodeURIComponent(REFERER)}`;
+ `&format=json&no_redirect=1&no_html=1&t=${encodeURIComponent(REFERRER)}`;
}

getCompletions(query: string, selection: {start: number, end: number}) {
let command = this.getCurrentCommand(query, selection);
if(!query || !command)
let {command, range} = this.getCurrentCommand(query, selection);
if (!query || !command) {
return Q.when([]);
}

return fetch(DuckDuckGoProvider.getQueryUri(command[1]), {
method: 'GET'
method: 'GET',
})
.then(response => response.json())
.then(json => {
let results = json.Results.map(result => {
return {
title: result.Text,
description: result.Result
completion: result.Text,
component: (
<TextualCompletion
title={result.Text}
description={result.Result} />
),
range,
};
});
if(json.Answer) {
if (json.Answer) {
results.unshift({
title: json.Answer,
description: json.AnswerType
completion: json.Answer,
component: (
<TextualCompletion
title={json.Answer}
description={json.AnswerType} />
),
range,
});
}
if(json.RelatedTopics && json.RelatedTopics.length > 0) {
if (json.RelatedTopics && json.RelatedTopics.length > 0) {
results.unshift({
title: json.RelatedTopics[0].Text
completion: json.RelatedTopics[0].Text,
component: (
<TextualCompletion
title={json.RelatedTopics[0].Text} />
),
range,
});
}
if(json.AbstractText) {
if (json.AbstractText) {
results.unshift({
title: json.AbstractText
completion: json.AbstractText,
component: (
<TextualCompletion
title={json.AbstractText} />
),
range,
});
}
// console.log(results);
return results;
});
}
Expand All @@ -59,9 +82,9 @@ export default class DuckDuckGoProvider extends AutocompleteProvider {
}

static getInstance(): DuckDuckGoProvider {
if(instance == null)
if (instance == null) {
instance = new DuckDuckGoProvider();

}
return instance;
}
}

0 comments on commit cccc58b

Please sign in to comment.