Copy All Text
This plugin will be responsible of copying all the text from the terminal, this will be done with the key combination alt + c
.
The following code creates a function that does not work as one of the Editor's props per se but instead relies on the key_bindings_plugin (which uses one of such props) to assign a keycode to a command. This function is made visible to the other plugins through the return statement.
const getKeys = () => ({
keyCode: 67,
keyWord: 'copy',
hasCommandModifier: false,
altKey: true,
});
Next we use one of the props handleKeyCommand to start overwriting the default Editor's behaviour.
const handleKeyCommand = (command, obj) => {
if (command === 'copy') {
// Execute the code to COPY
return 'handled';
}
return 'not-handled';
};
Firstly we get a hold of the current SelectionState
as well as the editorState
, and all the current Blocks, which will be put in an array named Keys, using the getBlocksAsArray
function.
const newSelectionState = SelectionState.createEmpty('copySelection');
const editorState = obj.getEditorState();
const Keys = editorState.getCurrentContent().getBlocksAsArray();
Now we must create a new selectionState, using the previously created one, we do this merging the new propierties we desire:
- anchorOffset: set to 0, being the start of the first content block
- focus offset: set to the length of the last content block
- anchorKey: being the key of the first content block
- focusKey: being the key of the last content block+
This will create a new selectionState with all the text selected (from the first char of the first contentBlock to the last char of the last contentBlock).
const updatedSelection = newSelectionState.merge({
anchorOffset: 0,
focusOffset: Keys[Keys.length - 1].getText().length,
anchorKey: Keys[0].getKey(),
focusKey: Keys[Keys.length - 1].getKey(),
});
Then we create a promise, setting the new state, we must create a Promise because we don't want the text being copied before the setting of the new state has ended.
We copy the text using the document.execCommand('copy')
.
new Promise((resolve) => {
resolve(obj.setEditorState(EditorState.forceSelection(editorState, updatedSelection)));
}).then(() => {
document.execCommand('copy');
return 'handled';
});