Skip to content
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

✨ Bento amp-copy #35221

Closed
wants to merge 19 commits into from
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
10 changes: 10 additions & 0 deletions build-system/compile/bundles.config.extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,16 @@
"hasCss": true
}
},
{
"name": "amp-copy",
"version": "1.0",
"latestVersion": "1.0",
"options": {
"npm": true,
"hasCss": true,
"wrapper": "bento"
}
},
{
"name": "amp-crypto-polyfill",
"version": "0.1",
Expand Down
15 changes: 15 additions & 0 deletions extensions/amp-copy/1.0/amp-copy.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove the copyright header from all new files now :)

* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
52 changes: 52 additions & 0 deletions extensions/amp-copy/1.0/amp-copy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {ActionTrust} from '#core/constants/action-constants';
import {BaseElement} from './base-element';
import {CSS} from '../../../build/amp-copy-1.0.css';
import {isExperimentOn} from '#experiments';
import {userAssert} from '../../../src/log';

/** @const {string} */
const TAG = 'amp-copy';

class AmpCopy extends BaseElement {
/** @override */
init() {
this.registerApiAction(
'copyToClipboard',
(api, invocation) => {
const {args} = invocation;
api.copyToClipboard(args['selector'], args['staticText']);
},
ActionTrust.LOW
);
}

/** @override */
isLayoutSupported(layout) {
userAssert(
isExperimentOn(this.win, 'bento') ||
isExperimentOn(this.win, 'bento-copy'),
'expected global "bento" or specific "bento-copy" experiment to be enabled'
);
return super.isLayoutSupported(layout);
}
}

AMP.extension(TAG, '1.0', (AMP) => {
AMP.registerElement(TAG, AmpCopy, CSS);
});
40 changes: 40 additions & 0 deletions extensions/amp-copy/1.0/base-element.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {CSS as COMPONENT_CSS} from './component.jss';
import {Copy} from './component';
import {PreactBaseElement} from '#preact/base-element';

export class BaseElement extends PreactBaseElement {}

/** @override */
BaseElement['Component'] = Copy;

/** @override */
BaseElement['props'] = {
'children': {passthroughNonEmpty: true},
'sourceId': {attr: 'source-id', type: 'string'},
'text': {attr: 'text', type: 'string'},
caroqliu marked this conversation as resolved.
Show resolved Hide resolved
};

/** @override */
BaseElement['layoutSizeDefined'] = true;

/** @override */
BaseElement['usesShadowDom'] = true;

/** @override */
BaseElement['shadowCss'] = COMPONENT_CSS;
121 changes: 121 additions & 0 deletions extensions/amp-copy/1.0/component.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Preact from '#preact';
import {
copyTextToClipboard,
isCopyingToClipboardSupported,
} from '#core/window/clipboard';
import {
useCallback,
useImperativeHandle,
useLayoutEffect,
useState,
} from '#preact';
import {forwardRef} from '#preact/compat';
import {useStyles} from './component.jss';
import objstr from 'obj-str';

/**
* @param {!CopyDef.Props} props
* @param {{current: ?CopyDef.CopyApi}} ref
* @return {PreactDef.Renderable}
*/
export function CopyWithRef({children, sourceId, text, ...rest}, ref) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: it may be worth aliasing this to textProp so that you can then use the variable name text in smaller scope locations instead of staticText etc.

const [status, setStatus] = useState(null);
const [isCopySupported, setIsCopySupported] = useState(false);
const classes = useStyles();
useLayoutEffect(() => {
if (!ref.current) {
return;
}
if (isCopyingToClipboardSupported(ref.current.ownerDocument)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would setting isCopySupported be better suited with a callback ref? https://reactjs.org/docs/refs-and-the-dom.html#callback-refs

setIsCopySupported(true);
} else {
setIsCopySupported(false);
}
}, [ref, setIsCopySupported]);

const copy = useCallback(
(sourceId) => {
let textToCopy = '';

if (sourceId == undefined) {
// Copy static text value
textToCopy = text;
} else {
// Copy content of sourceId element
const content = ref.current.ownerDocument.getElementById(sourceId);
textToCopy = (content.value ?? content.textContent).trim();
}

setStatus(copyTextToClipboard(window, textToCopy));

setTimeout(() => {
setStatus(null);
}, 3000);
},
[ref, text]
);

const copyText = useCallback((textToCopy) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wasn't copy written to handle both the copyText and copySelector case?

setStatus(copyTextToClipboard(window, textToCopy));

setTimeout(() => {
setStatus(null);
}, 3000);
}, []);

/** Copy Component - API Function */
useImperativeHandle(
ref,
() =>
/** @type {!CopyDef.CopyApi} */ ({
copyToClipboard: (selector = null, staticText = null) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What should be the behavior if both are provided? Should we emit an error message?

if (selector !== null) {
copy(selector);
} else if (staticText !== null) {
copyText(staticText);
} else {
// TODO: Assert Error
}
},
}),
[copy, copyText]
);

return (
<button
ref={ref}
className={objstr({
[classes.success]: status,
[classes.failed]: status === false,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
[classes.failed]: status === false,
[classes.failed]: !status,

[classes.enabled]: isCopySupported,
[classes.disabled]: !isCopySupported,
})}
layout
size
paint
{...rest}
onClick={() => copy(sourceId)}
>
{children}
</button>
);
}

const Copy = forwardRef(CopyWithRef);
Copy.displayName = 'Copy'; // Make findable for tests.
export {Copy};
40 changes: 40 additions & 0 deletions extensions/amp-copy/1.0/component.jss.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {createUseStyles} from 'react-jss';

const disabled = {
};

const enabled = {
};

const success = {
};

const failed = {
};

const JSS = {
enabled,
disabled,
success,
failed,
};

// useStyles gets replaced for AMP builds via `babel-plugin-transform-jss`.
// eslint-disable-next-line local/no-export-side-effect
export const useStyles = createUseStyles(JSS);
38 changes: 38 additions & 0 deletions extensions/amp-copy/1.0/component.type.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/** @externs */

/** @const */
var CopyDef = {};

/**
* @typedef {{
* sourceId: (string|undefined),
* text: (string|undefined),
* }}
*/
CopyDef.Props;

/** @interface */
CopyDef.CopyApi = class {
/**
* Copies content or static text
* @param {string} selector
* @param {string} staticText
*/
copyToClipboard(selector = null, staticText = null) {}
};
53 changes: 53 additions & 0 deletions extensions/amp-copy/1.0/storybook/Basic.amp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as Preact from '#preact';
import {withAmp} from '@ampproject/storybook-addon';
import {withKnobs} from '@storybook/addon-knobs';

export default {
title: 'amp-copy-1_0',
decorators: [withKnobs, withAmp],

parameters: {
extensions: [{name: 'amp-copy', version: '1.0'}],
experiments: ['bento'],
},
};

export const CopyInputValue = () => {
return (
<>
<input type="text" id="myInputField1" value="Text to copy!" />
<amp-copy width="100" height="20" source-id="myInputField1">
Copy Text
</amp-copy>
</>
);
};

export const CopyDIVContentText = () => {
return (
<>
<div id="myDiv1">
<p> hello world </p>
</div>
<amp-copy width="100" height="20" source-id="myDiv1">
Copy Content
</amp-copy>
</>
);
};
Loading