Skip to content

feat(plugin-copy-code): add inlineSelector option #416

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

Merged
merged 22 commits into from
Mar 28, 2025
Merged
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
3 changes: 3 additions & 0 deletions docs/.vuepress/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ export default defaultTheme({
},

themePlugins: {
copyCode: {
inline: true,
},
git: {
contributors: {
avatar: true,
Expand Down
12 changes: 11 additions & 1 deletion docs/plugins/features/copy-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,23 @@ export default {

### ignoreSelector

- Type: `string[]`
- Type: `string[] | string`
- Details:

Elements selector in code blocks, used to ignore related elements when copying.

For example, `['.token.comment']` will ignore nodes with the class name `.token.comment` in code blocks (which in `prismjs` refers to ignoring comments).

### inlineSelector

- Type: `string[] | string | boolean`
- Default: `false`

Whether to copy inline code content when double click.

- `boolean`: Whether to copy inline code content when double click.
- `string | string[]`: The selector of inline code.

### transform <Badge type="tip" text="Composables API Only" />

- Type: `(preElement: HTMLPreElement) => void`
Expand Down
13 changes: 12 additions & 1 deletion docs/zh/plugins/features/copy-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,24 @@ export default {

### ignoreSelector

- 类型:`string[]`
- 类型:`string[] | string`
- 详情:

代码块中的元素选择器,用于在复制时忽略相关元素。

例如: `['.token.comment']` 将忽略代码块中类名为 `.token.comment` 的节点 (这会在 `prismjs` 中忽略注释)。

### inlineSelector

- 类型:`string[] | string | boolean`
- 默认值:`false`
- 详情:

是否在双击时复制行内代码内容。

- `boolean`: 是否在双击时复制行内代码内容。
- `string[] | string`: 选择器,表示需要复制的行内代码内容。

### transform <Badge type="tip" text="仅限组合式 API" />

- 类型:`(preElement: HTMLPreElement) => void`
Expand Down
2 changes: 1 addition & 1 deletion plugins/features/plugin-copy-code/rollup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default [
files: ['config', 'index'],
},
{
dtsExternal: ['@vuepress/helper/shared'],
dtsExternal: ['@vuepress/helper/client', '@vuepress/helper/shared'],
},
),
]
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useLocaleConfig } from '@vuepress/helper/client'
import { Message, useLocaleConfig } from '@vuepress/helper/client'
import {
useClipboard,
useEventListener,
Expand All @@ -9,19 +9,19 @@ import { computed } from 'vue'
import { onContentUpdated } from 'vuepress/client'
import type { CopyCodePluginLocaleConfig } from '../types.js'

import '@vuepress/helper/message.css'
import '../styles/copy-code.css'
import '../styles/vars.css'

export interface UseCopyCodeOptions {
locales: CopyCodePluginLocaleConfig
selector: string[]
selector: string
ignoreSelector?: string
inlineSelector?: string
/** @default 2000 */
duration: number
/** @default false */
showInMobile?: boolean
/** @default [] */
ignoreSelector?: string[]

/**
* Transform pre element before copy
*
Expand All @@ -44,14 +44,17 @@ export interface UseCopyCodeOptions {
transform?: (preElement: HTMLElement) => void
}

const CHECK_ICON =
'<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#06a35a"><path d="M822.812 824.618c-83.076 81.992-188.546 124.614-316.05 127.865-122.085-3.251-223.943-45.873-305.935-127.865S76.213 640.406 72.962 518.682c3.251-127.503 45.873-232.973 127.865-316.05 81.992-83.075 184.211-126.058 305.936-129.309 127.503 3.251 232.973 46.234 316.049 129.31 83.076 83.076 126.059 188.546 129.31 316.05-2.89 121.723-46.234 223.943-129.31 305.935zM432.717 684.111c3.973 3.974 8.307 5.78 13.364 6.14 5.057.362 9.753-1.444 13.365-5.417l292.57-287.515c3.974-3.973 5.78-8.307 5.78-13.364s-1.806-9.753-5.78-13.365l1.807 1.806c-3.973-3.973-8.669-5.779-14.087-6.14-5.418-.361-10.475 1.445-14.809 5.418L460.529 592.006c-3.973 3.25-8.669 4.695-14.448 4.695-5.78 0-10.836-1.445-15.531-3.973l-94.273-72.962c-4.335-3.251-9.392-4.335-14.448-3.973s-9.392 3.25-12.642 7.585l-2.89 3.973c-3.25 4.334-4.334 9.391-3.973 14.81.722 5.417 2.528 10.113 5.779 14.086L432.717 684.11z"/></svg>'
const SHELL_RE = /language-(shellscript|shell|bash|sh|zsh)/

export const useCopyCode = ({
selector,
ignoreSelector,
inlineSelector,
duration = 2000,
locales,
selector,
showInMobile,
ignoreSelector = [],
transform,
}: UseCopyCodeOptions): void => {
if (__VUEPRESS_SSR__) return
Expand Down Expand Up @@ -83,9 +86,7 @@ export const useCopyCode = ({
document.body.classList.toggle('no-copy-code', !enabled.value)
if (!enabled.value) return

document
.querySelectorAll<HTMLElement>(selector.join(','))
.forEach(insertCopyButton)
document.querySelectorAll<HTMLElement>(selector).forEach(insertCopyButton)
}

watchImmediate(enabled, appendCopyButton, {
Expand All @@ -98,6 +99,7 @@ export const useCopyCode = ({

const { copy } = useClipboard({ legacy: true })
const timeoutIdMap = new WeakMap<HTMLElement, ReturnType<typeof setTimeout>>()
let message: Message | null = null

const copyContent = async (
codeContainer: HTMLDivElement,
Expand All @@ -106,8 +108,8 @@ export const useCopyCode = ({
): Promise<void> => {
const clone = codeContent.cloneNode(true) as HTMLPreElement

if (ignoreSelector.length) {
clone.querySelectorAll(ignoreSelector.join(',')).forEach((node) => {
if (ignoreSelector) {
clone.querySelectorAll(ignoreSelector).forEach((node) => {
node.remove()
})
}
Expand Down Expand Up @@ -148,4 +150,28 @@ export const useCopyCode = ({
void copyContent(codeContainer, preBlock, el as HTMLButtonElement)
}
})

if (inlineSelector) {
useEventListener('dblclick', (event) => {
const el = event.target as HTMLElement

if (enabled.value && el.matches(inlineSelector)) {
const selection = window.getSelection()

if (
selection &&
(el.contains(selection.anchorNode) ||
el.contains(selection.focusNode))
) {
selection.removeAllRanges()
}

void copy(el.textContent || '')
;(message ??= new Message()).pop(
`${CHECK_ICON}<span>${locale.value.copied} </span>`,
duration,
)
}
})
}
}
6 changes: 4 additions & 2 deletions plugins/features/plugin-copy-code/src/client/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@ import type { CopyCodePluginLocaleConfig } from './types.js'

declare const __CC_DURATION__: number
declare const __CC_LOCALES__: CopyCodePluginLocaleConfig
declare const __CC_SELECTOR__: string[]
declare const __CC_IGNORE_SELECTOR__: string[]
declare const __CC_SELECTOR__: string
declare const __CC_IGNORE_SELECTOR__: string
declare const __CC_INLINE_SELECTOR__: string
declare const __CC_SHOW_IN_MOBILE__: boolean

export default defineClientConfig({
setup: () => {
useCopyCode({
selector: __CC_SELECTOR__,
ignoreSelector: __CC_IGNORE_SELECTOR__,
inlineSelector: __CC_INLINE_SELECTOR__,
locales: __CC_LOCALES__,
duration: __CC_DURATION__,
showInMobile: __CC_SHOW_IN_MOBILE__,
Expand Down
21 changes: 14 additions & 7 deletions plugins/features/plugin-copy-code/src/node/copyCodePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,26 @@ export const copyCodePlugin =
name: PLUGIN_NAME,

define: () => ({
__CC_DURATION__: options.duration ?? 2000,
__CC_IGNORE_SELECTOR__: options.ignoreSelector ?? [],
__CC_SELECTOR__: isArray(options.selector)
? options.selector.join(',')
: (options.selector ?? '[vp-content] div[class*="language-"] pre'),
__CC_IGNORE_SELECTOR__: Array.isArray(options.ignoreSelector)
? options.ignoreSelector.join(',')
: (options.ignoreSelector ?? ''),
__CC_INLINE_SELECTOR__: Array.isArray(options.inline)
? options.inline.join(',')
: isString(options.inline)
? options.inline
: options.inline
? '[vp-content] :not(pre) > code'
: '',
__CC_LOCALES__: getFullLocaleConfig({
app,
name: PLUGIN_NAME,
default: copyCodeLocaleInfo,
config: options.locales,
}),
__CC_SELECTOR__: isArray(options.selector)
? options.selector
: isString(options.selector)
? [options.selector]
: ['[vp-content] div[class*="language-"] pre'],
__CC_DURATION__: options.duration ?? 2000,
__CC_SHOW_IN_MOBILE__: options.showInMobile ?? false,
}),

Expand Down
17 changes: 16 additions & 1 deletion plugins/features/plugin-copy-code/src/node/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,27 @@ export interface CopyCodePluginOptions {
*
* @default []
*/
ignoreSelector?: string[]
ignoreSelector?: string[] | string

/**
* Locale config
*
* 国际化配置
*/
locales?: LocaleConfig<CopyCodePluginLocaleData>

/**
* Whether to copy inline code content when double click.
*
* - boolean: Whether to copy inline code content when double click.
* - string | string[]: The selector of inline code.
*
* 是否在双击时复制内联代码内容
*
* - boolean: 是否在双击时复制内联代码内容
* - string | string[]: 内联代码的选择器
*
* @default '[vp-content] :not(pre) > code'
*/
inline?: string[] | boolean | string
}
Loading