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

Add copy code to clipboard button for rustdoc #119929

Closed
wants to merge 9 commits into from
Closed

Add copy code to clipboard button for rustdoc #119929

wants to merge 9 commits into from

Conversation

grey4owl
Copy link

A very simple button that was missing in the upper right corner to copy the code blocks to the clipboard. It is hidden by default, but when you hover over the code block (<pre>) element then it appears.. It also works on mobile devices and it will appears after you tap on the code block.

It looks like this:
Screenshot from 2024-01-13 17-11-48
Screenshot from 2024-01-13 17-12-02

@rustbot
Copy link
Collaborator

rustbot commented Jan 13, 2024

Thanks for the pull request, and welcome! The Rust team is excited to review your changes, and you should hear from @fmease (or someone else) soon.

Please see the contribution instructions for more information. Namely, in order to ensure the minimum review times lag, PR authors and assigned reviewers should ensure that the review label (S-waiting-on-review and S-waiting-on-author) stays updated, invoking these commands when appropriate:

  • @rustbot author: the review is finished, PR author should check the comments and take action accordingly
  • @rustbot review: the author is ready for a review, this PR will be queued again in the reviewer's queue

@rustbot
Copy link
Collaborator

rustbot commented Jan 13, 2024

Some changes occurred in HTML/CSS/JS.

cc @GuillaumeGomez, @jsha

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-rustdoc Relevant to the rustdoc team, which will review and decide on the PR/issue. labels Jan 13, 2024
@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@fmease fmease added the needs-fcp This change is insta-stable, so needs a completed FCP to proceed. label Jan 14, 2024
Copy link
Member

@fmease fmease left a comment

Choose a reason for hiding this comment

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

Thanks for working on this, I've only skimmed your PR so far and have a couple of comments. Could you please squash the 8 commits into one (or at least fewer) and ./x fmt your changes (that's why CI has failed).

@@ -1734,6 +1734,37 @@ href="https://doc.rust-lang.org/${channel}/rustdoc/read-documentation/search.htm
resizer.addEventListener("pointerdown", initResize, false);
}());

// This section handles the copy buttons that appears in top right corner of the code blocks
(function() {
let preElements = document.querySelectorAll("pre:has(code)");
Copy link
Member

@fmease fmease Jan 14, 2024

Choose a reason for hiding this comment

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

:has is not supported in Firefox Mobile: https://caniuse.com/css-has

let preElements = document.querySelectorAll("pre:has(code)");
preElements.forEach(function(pre, index) {
let resetTimeout = null;
let copyBtn = pre.querySelector("button[class='copy-code']");
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
let copyBtn = pre.querySelector("button[class='copy-code']");
let copyBtn = pre.querySelector("button.copy-code");

let copyBtn = pre.querySelector("button[class='copy-code']");
let icon = copyBtn.innerHTML;
pre.addEventListener("mouseenter", function() {
copyBtn.style.opacity = "1";
Copy link
Member

@fmease fmease Jan 14, 2024

Choose a reason for hiding this comment

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

You should be able to express this in pure CSS with:

pre:hover > button.copy-code { opacity: 1; }

@fmease fmease added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jan 14, 2024
@rustbot rustbot added the has-merge-commits PR has merge commits, merge with caution. label Jan 14, 2024
@rustbot
Copy link
Collaborator

rustbot commented Jan 14, 2024

There are merge commits (commits with multiple parents) in your changes. We have a no merge policy so these commits will need to be removed for this pull request to be merged.

You can start a rebase with the following commands:

$ # rebase
$ git rebase -i master
$ # delete any merge commits in the editor that appears
$ git push --force-with-lease

The following commits are merge commits:

@rust-log-analyzer
Copy link
Collaborator

The job mingw-check-tidy failed! Check out the build log: (web) (plain)

Click to see the possible cause of the failure (guessed by this bot)
Prepare all required actions
Getting action download info
Download action repository 'actions/checkout@v4' (SHA:b4ffde65f46336ab88eb53be808477a3936bae11)
Download action repository 'actions/upload-artifact@v3' (SHA:a8a3f3ad30e3422c9c7b888a15615d19a852ae32)
Complete job name: PR - mingw-check-tidy
git config --global core.autocrlf false
shell: /usr/bin/bash --noprofile --norc -e -o pipefail {0}
---
GITHUB_ACTION=__run_7
GITHUB_ACTIONS=true
GITHUB_ACTION_REF=
GITHUB_ACTION_REPOSITORY=
GITHUB_ACTOR=grey4owl
GITHUB_API_URL=https://api.github.com
GITHUB_BASE_REF=master
GITHUB_ENV=/home/runner/work/_temp/_runner_file_commands/set_env_fc72e92d-bcc1-4b63-b3b2-9b781973032e
GITHUB_EVENT_NAME=pull_request
---
GITHUB_SERVER_URL=https://github.com
GITHUB_SHA=4b3381370e9eaf4512ee758936e8134d4dff6bc3
GITHUB_STATE=/home/runner/work/_temp/_runner_file_commands/save_state_fc72e92d-bcc1-4b63-b3b2-9b781973032e
GITHUB_STEP_SUMMARY=/home/runner/work/_temp/_runner_file_commands/step_summary_fc72e92d-bcc1-4b63-b3b2-9b781973032e
GITHUB_TRIGGERING_ACTOR=grey4owl
GITHUB_WORKFLOW_REF=rust-lang/rust/.github/workflows/ci.yml@refs/pull/119929/merge
GITHUB_WORKFLOW_SHA=4b3381370e9eaf4512ee758936e8134d4dff6bc3
GITHUB_WORKSPACE=/home/runner/work/rust/rust
GOROOT_1_19_X64=/opt/hostedtoolcache/go/1.19.13/x64
---
Removing intermediate container 848f268c18bb
 ---> b4e2576a30e8
Step 6/10 : COPY host-x86_64/mingw-check/reuse-requirements.txt /tmp/
 ---> 3854dec379c6
Step 7/10 : RUN pip3 install --no-deps --no-cache-dir --require-hashes -r /tmp/reuse-requirements.txt     && pip3 install virtualenv
Collecting binaryornot==0.4.4
  Downloading binaryornot-0.4.4-py2.py3-none-any.whl (9.0 kB)
Collecting boolean-py==4.0
  Downloading boolean.py-4.0-py3-none-any.whl (25 kB)
---
Building wheels for collected packages: reuse
  Building wheel for reuse (pyproject.toml): started
  Building wheel for reuse (pyproject.toml): finished with status 'done'
  Created wheel for reuse: filename=reuse-1.1.0-cp310-cp310-manylinux_2_35_x86_64.whl size=180123 sha256=f323ccf11d14c5b11f6d5e70edb46e391f4b49a5df5c7d922224477ad8ee15c5
  Stored in directory: /tmp/pip-ephem-wheel-cache-kx9iahkn/wheels/c2/3c/b9/1120c2ab4bd82694f7e6f0537dc5b9a085c13e2c69a8d0c76d
Installing collected packages: boolean-py, binaryornot, setuptools, reuse, python-debian, markupsafe, license-expression, jinja2, chardet
  Attempting uninstall: setuptools
    Found existing installation: setuptools 59.6.0
    Not uninstalling setuptools at /usr/lib/python3/dist-packages, outside environment /usr
    Not uninstalling setuptools at /usr/lib/python3/dist-packages, outside environment /usr
    Can't uninstall 'setuptools'. No files were found to uninstall.
Successfully installed binaryornot-0.4.4 boolean-py-4.0 chardet-5.1.0 jinja2-3.1.2 license-expression-30.0.0 markupsafe-2.1.1 python-debian-0.1.49 reuse-1.1.0 setuptools-66.0.0
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Collecting virtualenv
  Downloading virtualenv-20.25.0-py3-none-any.whl (3.8 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.8/3.8 MB 64.7 MB/s eta 0:00:00
Collecting distlib<1,>=0.3.7
  Downloading distlib-0.3.8-py2.py3-none-any.whl (468 kB)
Collecting filelock<4,>=3.12.2
  Downloading filelock-3.13.1-py3-none-any.whl (11 kB)
  Downloading filelock-3.13.1-py3-none-any.whl (11 kB)
Collecting platformdirs<5,>=3.9.1
  Downloading platformdirs-4.1.0-py3-none-any.whl (17 kB)
Installing collected packages: distlib, platformdirs, filelock, virtualenv
Successfully installed distlib-0.3.8 filelock-3.13.1 platformdirs-4.1.0 virtualenv-20.25.0
Removing intermediate container c469032f0ba0
 ---> a5fd7b7e17e7
Step 8/10 : COPY host-x86_64/mingw-check/validate-toolstate.sh /scripts/
 ---> 0a45da5a37c2
 ---> 0a45da5a37c2
Step 9/10 : COPY host-x86_64/mingw-check/validate-error-codes.sh /scripts/
 ---> cb6bd8574658
Step 10/10 : ENV SCRIPT TIDY_PRINT_DIFF=1 python2.7 ../x.py test            --stage 0 src/tools/tidy tidyselftest --extra-checks=py:lint
Removing intermediate container 83ee3dd2922a
 ---> 94e81b3762c3
Successfully built 94e81b3762c3
Successfully tagged rust-ci:latest
Successfully tagged rust-ci:latest
##[endgroup]
Built container sha256:94e81b3762c3941a1408cf2ad00dddc09e0abb74c1a3f490208d07e61cf8d62c
Uploading finished image sha256:94e81b3762c3941a1408cf2ad00dddc09e0abb74c1a3f490208d07e61cf8d62c to https://ci-caches.rust-lang.org/docker/139141a603ff222e98d20ef66f0e4eaedfc4b373e41d302ecff577f90ee0c6cf0cab092d18a8f6a073c88b362b9a680d3b2b6e5c828faaf25d1b853eabb78b1a
IMAGE          CREATED          CREATED BY                                      SIZE      COMMENT
94e81b3762c3   1 second ago     /bin/sh -c #(nop)  ENV SCRIPT=TIDY_PRINT_DIF…   0B        
0a45da5a37c2   2 seconds ago    /bin/sh -c #(nop) COPY file:078ea1d11e7b7cda…   367B      
a5fd7b7e17e7   3 seconds ago    |1 DEBIAN_FRONTEND=noninteractive /bin/sh -c…   23.9MB    
3854dec379c6   9 seconds ago    /bin/sh -c #(nop) COPY file:ac591dd6bc5afa66…   5.33kB    
b4e2576a30e8   10 seconds ago   |1 DEBIAN_FRONTEND=noninteractive /bin/sh -c…   23.1MB    
---
<missing>      4 weeks ago      /bin/sh -c #(nop)  LABEL org.opencontainers.…   0B        
<missing>      4 weeks ago      /bin/sh -c #(nop)  ARG LAUNCHPAD_BUILD_ARCH     0B        
<missing>      4 weeks ago      /bin/sh -c #(nop)  ARG RELEASE                  0B        

<botocore.awsrequest.AWSRequest object at 0x7fc176947450>
gzip: stdout: Broken pipe
xargs: docker: terminated by signal 13
https://ci-caches.rust-lang.org/docker/139141a603ff222e98d20ef66f0e4eaedfc4b373e41d302ecff577f90ee0c6cf0cab092d18a8f6a073c88b362b9a680d3b2b6e5c828faaf25d1b853eabb78b1a
sha256:94e81b3762c3941a1408cf2ad00dddc09e0abb74c1a3f490208d07e61cf8d62c
---
DirectMap4k:      188352 kB
DirectMap2M:     7151616 kB
DirectMap1G:    11534336 kB
##[endgroup]
Executing TIDY_PRINT_DIFF=1 python2.7 ../x.py test            --stage 0 src/tools/tidy tidyselftest --extra-checks=py:lint
+ TIDY_PRINT_DIFF=1 python2.7 ../x.py test --stage 0 src/tools/tidy tidyselftest --extra-checks=py:lint
    Finished dev [unoptimized] target(s) in 0.03s
##[endgroup]
downloading https://ci-artifacts.rust-lang.org/rustc-builds-alt/665d2c6f2c49f1b9710f201b341354769cef3f94/rust-dev-nightly-x86_64-unknown-linux-gnu.tar.xz
extracting /checkout/obj/build/cache/llvm-665d2c6f2c49f1b9710f201b341354769cef3f94-true/rust-dev-nightly-x86_64-unknown-linux-gnu.tar.xz to /checkout/obj/build/x86_64-unknown-linux-gnu/ci-llvm
---
   Compiling tidy v0.1.0 (/checkout/src/tools/tidy)
    Finished release [optimized] target(s) in 25.09s
##[endgroup]
fmt check
##[error]Diff in /checkout/src/librustdoc/html/sources.rs at line 5:
 use crate::html::format;
 use crate::html::highlight;
 use crate::html::layout;
-use crate::html::Page;
 use crate::html::render::Context;
+use crate::html::Page;
 use crate::visit::DocVisitor;
 use askama::Template;
 use askama::Template;
##[error]Diff in /checkout/src/librustdoc/html/sources.rs at line 338:
     });
     let static_root_path = get_static_root_path();
     let static_root_path = get_static_root_path();
-    Source { embedded, needs_expansion, lines, code_html: code, static_root_path }.render_into(&mut writer).unwrap();
+    Source { embedded, needs_expansion, lines, code_html: code, static_root_path }
+        .render_into(&mut writer)
+        .unwrap();
 
 
##[error]Diff in /checkout/src/librustdoc/html/markdown.rs at line 48:
 use crate::html::escape::Escape;
 use crate::html::format::Buffer;
 use crate::html::highlight;
+use crate::html::layout::Page;
 use crate::html::length_limit::HtmlWithLimit;
 use crate::html::render::small_url_encode;
-use crate::html::toc::TocBuilder;
 use crate::html::static_files;
-use crate::html::layout::Page;
+use crate::html::toc::TocBuilder;
 use pulldown_cmark::{
 use pulldown_cmark::{
     html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, OffsetIter, Options, Parser, Tag,
Running `"/checkout/obj/build/x86_64-unknown-linux-gnu/rustfmt/bin/rustfmt" "--config-path" "/checkout" "--edition" "2021" "--unstable-features" "--skip-children" "--check" "/checkout/src/etc/test-float-parse/src/bin/short-decimals.rs" "/checkout/src/etc/test-float-parse/src/lib.rs" "/checkout/src/librustdoc/html/tests.rs" "/checkout/src/librustdoc/html/url_parts_builder.rs" "/checkout/src/librustdoc/html/markdown/tests.rs" "/checkout/src/librustdoc/html/highlight/fixtures/union.rs" "/checkout/src/librustdoc/html/highlight/fixtures/sample.rs" "/checkout/src/librustdoc/html/markdown.rs"` failed.
If you're running `tidy`, try again with `--bless`. Or, if you just want to format code, run `./x.py fmt` instead.
  local time: Sun Jan 14 21:43:14 UTC 2024
  network time: Sun, 14 Jan 2024 21:43:14 GMT
##[error]Process completed with exit code 1.
Post job cleanup.

@grey4owl
Copy link
Author

@fmease I messed up some things, Im closing this PR and I'll make a new one. Sorry .. 🥲

@grey4owl grey4owl closed this Jan 14, 2024
@fmease
Copy link
Member

fmease commented Jan 14, 2024

All good, now worries! You can write r? @fmease in the description of your new PR and it will automatically assign me.

@egtwp
Copy link

egtwp commented May 15, 2024

@grey4owl had you opened a new MR about this? Thank u!

@fmease
Copy link
Member

fmease commented May 15, 2024

They did, yes. Namely #119979 which was closed, too, due inactivity/time constraints of the author. Feel free to take over the work of #119979!

@GuillaumeGomez
Copy link
Member

A few things to take into account for this feature:

  • Considering it's only working when JS is enabled, it should not be rendered into HTML files but instead generated with JS.
  • To prevent this generation to impact load time too much, it should be done in two steps:
    1. Add a onhover event on all rust codeblocks.
    2. When this event is triggered, generate the button and remove the event handler on the item.

@fmease fmease added the S-inactive Status: Inactive and waiting on the author. This is often applied to closed PRs. label May 29, 2024
@GuillaumeGomez
Copy link
Member

I implemented the feature. Just needs some UI tests and then I'll send a PR.

@GuillaumeGomez
Copy link
Member

Forgot to mention but PR is open: #125779

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
has-merge-commits PR has merge commits, merge with caution. needs-fcp This change is insta-stable, so needs a completed FCP to proceed. S-inactive Status: Inactive and waiting on the author. This is often applied to closed PRs. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-rustdoc Relevant to the rustdoc team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants