Skip to content

Added "Copy Code" Button #2446 #3392

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

Closed
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
63 changes: 63 additions & 0 deletions client/components/CopyableTool.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

/**
* CopyableTool: A reusable tooltip component with the ability
* to copy text to the clipboard when triggered.
*/
const CopyableTool = ({ className, label, copyText, children }) => {
const [isCopied, setIsCopied] = useState(false);

const handleCopyClick = () => {
navigator.clipboard.writeText(copyText);
setIsCopied(true);
};

// Add click handler to element with the "copy-trigger" class
const processChildren = (childElements) =>
React.Children.map(childElements, (child) => {
if (React.isValidElement(child)) {
const childClassNames = child.props.className || '';

if (childClassNames.includes('copy-trigger')) {
return React.cloneElement(child, { onClick: handleCopyClick });
}

if (child.props.children) {
const newChildren = processChildren(child.props.children);
return React.cloneElement(child, { children: newChildren });
}
}

return child;
});

const childrenWithClickHandler = processChildren(children);

return (
<div
className={classNames(
className,
'tooltipped-no-delay',
isCopied &&
`tooltipped ${
className.includes('tooltipped') ? className : 'tooltipped-n'
}`
)}
aria-label={label}
onMouseLeave={() => setIsCopied(false)}
>
{childrenWithClickHandler}
</div>
);
};

CopyableTool.propTypes = {
className: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
copyText: PropTypes.string.isRequired,
children: PropTypes.node.isRequired
};

export default CopyableTool;
1 change: 1 addition & 0 deletions client/images/copy.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 15 additions & 33 deletions client/modules/IDE/components/CopyableInput.jsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,20 @@
import PropTypes from 'prop-types';
import React, { useEffect, useRef, useState } from 'react';
import Clipboard from 'clipboard';
import React, { useRef } from 'react';
import classNames from 'classnames';
import { useTranslation } from 'react-i18next';

import CopyableTool from '../../../components/CopyableTool';

import ShareIcon from '../../../images/share.svg';

const CopyableInput = ({ label, value, hasPreviewLink }) => {
const { t } = useTranslation();

const [isCopied, setIsCopied] = useState(false);

const inputRef = useRef(null);

useEffect(() => {
const input = inputRef.current;

if (!input) return; // should never happen

const clipboard = new Clipboard(input, {
target: () => input
});

clipboard.on('success', () => {
setIsCopied(true);
});

// eslint-disable-next-line consistent-return
return () => {
clipboard.destroy();
};
}, [inputRef, setIsCopied]);
const handleInputFocus = () => {
if (!inputRef?.current) return;
inputRef.current.select();
};

return (
<div
Expand All @@ -39,14 +23,10 @@ const CopyableInput = ({ label, value, hasPreviewLink }) => {
hasPreviewLink && 'copyable-input--with-preview'
)}
>
<div
className={classNames(
'copyable-input__value-container',
'tooltipped-no-delay',
isCopied && 'tooltipped tooltipped-n'
)}
aria-label={t('CopyableInput.CopiedARIA')}
onMouseLeave={() => setIsCopied(false)}
<CopyableTool
className="copyable-input__value-container"
label={t('CopyableInput.CopiedARIA')}
copyText={value}
>
<label
className="copyable-input__label"
Expand All @@ -55,14 +35,16 @@ const CopyableInput = ({ label, value, hasPreviewLink }) => {
<div className="copyable-input__label-container">{label}</div>
<input
type="text"
className="copyable-input__value"
className={classNames('copy-trigger', 'copyable-input__value')}
id={`copyable-input__value-${label}`}
value={value}
ref={inputRef}
onFocus={handleInputFocus}
readOnly
/>
</label>
</div>
</CopyableTool>

{hasPreviewLink && (
<a
target="_blank"
Expand Down
82 changes: 38 additions & 44 deletions client/modules/IDE/components/Editor/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import 'codemirror/addon/fold/comment-fold';
import 'codemirror/addon/fold/foldcode';
import 'codemirror/addon/fold/foldgutter';
import 'codemirror/addon/fold/indent-fold';
import 'codemirror/addon/fold/xml-fold';
import 'codemirror/addon/comment/comment';
import 'codemirror/keymap/sublime';
import 'codemirror/addon/search/searchcursor';
Expand Down Expand Up @@ -54,6 +53,7 @@ import '../../../../utils/codemirror-search';
import beepUrl from '../../../../sounds/audioAlert.mp3';
import RightArrowIcon from '../../../../images/right-arrow.svg';
import LeftArrowIcon from '../../../../images/left-arrow.svg';
import CopyIcon from '../../../../images/copy.svg';
import { getHTMLFile } from '../../reducers/files';
import { selectActiveFile } from '../../selectors/files';

Expand All @@ -72,6 +72,7 @@ import UnsavedChangesIndicator from '../UnsavedChangesIndicator';
import { EditorContainer, EditorHolder } from './MobileEditor';
import { FolderIcon } from '../../../../common/icons';
import IconButton from '../../../../common/IconButton';
import CopyableTool from '../../../../components/CopyableTool';

emmet(CodeMirror);

Expand All @@ -84,10 +85,6 @@ const INDENTATION_AMOUNT = 2;
class Editor extends React.Component {
constructor(props) {
super(props);
this.state = {
currentLine: 1
};
this._cm = null;
this.tidyCode = this.tidyCode.bind(this);

this.updateLintingMessageAccessibility = debounce((annotations) => {
Expand Down Expand Up @@ -137,7 +134,7 @@ class Editor extends React.Component {
asi: true,
eqeqeq: false,
'-W041': false,
esversion: 11
esversion: 7
}
},
colorpicker: {
Expand Down Expand Up @@ -168,7 +165,6 @@ class Editor extends React.Component {
},
Enter: 'emmetInsertLineBreak',
Esc: 'emmetResetAbbreviation',
[`Shift-Tab`]: false,
[`${metaKey}-Enter`]: () => null,
[`Shift-${metaKey}-Enter`]: () => null,
[`${metaKey}-F`]: 'findPersistent',
Expand Down Expand Up @@ -200,9 +196,12 @@ class Editor extends React.Component {
}, 1000)
);

if (this._cm) {
this._cm.on('keyup', this.handleKeyUp);
}
this._cm.on('keyup', () => {
const temp = this.props.t('Editor.KeyUpLineNumber', {
lineNumber: parseInt(this._cm.getCursor().line + 1, 10)
});
document.getElementById('current-line').innerHTML = temp;
});

this._cm.on('keydown', (_cm, e) => {
// Show hint
Expand Down Expand Up @@ -237,16 +236,6 @@ class Editor extends React.Component {

componentDidUpdate(prevProps) {
if (this.props.file.id !== prevProps.file.id) {
const fileMode = this.getFileMode(this.props.file.name);
if (fileMode === 'javascript') {
// Define the new Emmet configuration based on the file mode
const emmetConfig = {
preview: ['html'],
markTagPairs: false,
autoRenameTags: true
};
this._cm.setOption('emmet', emmetConfig);
}
const oldDoc = this._cm.swapDoc(this._docs[this.props.file.id]);
this._docs[prevProps.file.id] = oldDoc;
this._cm.focus();
Expand Down Expand Up @@ -334,9 +323,7 @@ class Editor extends React.Component {
}

componentWillUnmount() {
if (this._cm) {
this._cm.off('keyup', this.handleKeyUp);
}
this._cm = null;
this.props.provideController(null);
}

Expand All @@ -352,7 +339,7 @@ class Editor extends React.Component {
mode = 'application/json';
} else if (fileName.match(/.+\.(frag|glsl)$/i)) {
mode = 'x-shader/x-fragment';
} else if (fileName.match(/.+\.(vert|stl|mtl)$/i)) {
} else if (fileName.match(/.+\.(vert|stl)$/i)) {
mode = 'x-shader/x-vertex';
} else {
mode = 'text/plain';
Expand All @@ -366,11 +353,6 @@ class Editor extends React.Component {
return updatedFile;
}

handleKeyUp = () => {
const lineNumber = parseInt(this._cm.getCursor().line + 1, 10);
this.setState({ currentLine: lineNumber });
};

showFind() {
this._cm.execCommand('findPersistent');
}
Expand Down Expand Up @@ -527,14 +509,14 @@ class Editor extends React.Component {
this.props.file.fileType === 'folder' || this.props.file.url
});

const { currentLine } = this.state;
const editorContent = this._cm && this.getContent().content;

return (
<MediaQuery minWidth={770}>
{(matches) =>
matches ? (
<section className={editorSectionClass}>
<div className="editor__header">
<header className="editor__header">
<button
aria-label={this.props.t('Editor.OpenSketchARIA')}
className="sidebar__contract"
Expand All @@ -557,9 +539,27 @@ class Editor extends React.Component {
{this.props.file.name}
<UnsavedChangesIndicator />
</span>

<button
className="editor__copy-btn"
onClick={this.props.copyFileContent}
>
<CopyIcon />
</button>
<Timer />
</div>
</div>
</header>

<CopyableTool
className={classNames('editor__copy', 'tooltipped-nw')}
label="Copied"
copyText={editorContent}
>
<button className="copy-trigger">
<CopyIcon />
</button>
</CopyableTool>

<article
ref={(element) => {
this.codemirrorContainer = element;
Expand All @@ -572,14 +572,11 @@ class Editor extends React.Component {
name={this.props.file.name}
/>
) : null}
<EditorAccessibility
lintMessages={this.props.lintMessages}
currentLine={currentLine}
/>
<EditorAccessibility lintMessages={this.props.lintMessages} />
</section>
) : (
<EditorContainer expanded={this.props.isExpanded}>
<div>
<header>
<IconButton
onClick={this.props.expandSidebar}
icon={FolderIcon}
Expand All @@ -588,7 +585,7 @@ class Editor extends React.Component {
{this.props.file.name}
<UnsavedChangesIndicator />
</span>
</div>
</header>
<section>
<EditorHolder
ref={(element) => {
Expand All @@ -601,10 +598,7 @@ class Editor extends React.Component {
name={this.props.file.name}
/>
) : null}
<EditorAccessibility
lintMessages={this.props.lintMessages}
currentLine={currentLine}
/>
<EditorAccessibility lintMessages={this.props.lintMessages} />
</section>
</EditorContainer>
)
Expand All @@ -622,8 +616,7 @@ Editor.propTypes = {
linewrap: PropTypes.bool.isRequired,
lintMessages: PropTypes.arrayOf(
PropTypes.shape({
severity: PropTypes.oneOf(['error', 'hint', 'info', 'warning'])
.isRequired,
severity: PropTypes.string.isRequired,
line: PropTypes.number.isRequired,
message: PropTypes.string.isRequired,
id: PropTypes.number.isRequired
Expand All @@ -638,6 +631,7 @@ Editor.propTypes = {
updateLintMessage: PropTypes.func.isRequired,
clearLintMessage: PropTypes.func.isRequired,
updateFileContent: PropTypes.func.isRequired,
copyFileContent: PropTypes.func.isRequired,
fontSize: PropTypes.number.isRequired,
file: PropTypes.shape({
name: PropTypes.string.isRequired,
Expand Down
Loading