All files / ext.wikilambda.app/composables useClipboard.js

100% Statements 89/89
100% Branches 17/17
100% Functions 6/6
100% Lines 89/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 9022x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 14x 14x 93x 93x 93x 93x 93x 4x 4x 93x 93x 93x 93x 93x 93x 93x 93x 93x 12x 12x 12x 7x 12x 5x 5x 10x 10x 10x 4x 3x 3x 1x 1x 10x 12x 93x 93x 93x 93x 93x 93x 93x 93x 236x 36x 36x 200x 236x 93x 93x 93x 93x 93x 93x 93x 93x 93x 22x  
/*!
 * Clipboard composable for Vue 3 Composition API.
 * Provides functions to handle clipboard actions
 *
 * @module ext.wikilambda.app.composables.useClipboard
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
'use strict';
 
const { ref, computed, inject } = require( 'vue' );
 
/**
 * Clipboard composable
 *
 * @param {Object} options - Options object
 * @return {Object} Clipboard composable API
 * @exports useClipboard
 */
module.exports = function useClipboard() {
	const i18n = inject( 'i18n' );
	const itemsCopied = ref( [] );
 
	const getCopiedText = computed( () => i18n( 'wikilambda-function-explorer-copied-text' ).text() );
 
	/**
	 * Add the copied value to the array
	 *
	 * @param {string} value The value to copy
	 */
	function copy( value ) {
		itemsCopied.value.push( value );
	}
 
	/**
	 * Remove the copied value from the array
	 */
	function clear() {
		itemsCopied.value.shift();
	}
 
	/**
	 * Copy a value to the clipboard and display a "copied" message for a short time
	 *
	 * @param {string} value The value to copy to the clipboard
	 * @param {Function} customCopyFn Optional custom copy function
	 * @param {Function} customClearFn Optional custom clear function
	 */
	function copyToClipboard( value, customCopyFn, customClearFn ) {
		navigator.clipboard.writeText( value );
 
		if ( customCopyFn ) {
			customCopyFn();
		} else {
			copy( value );
		}
 
		// Clear the "copied" message after 2 seconds
		setTimeout( () => {
			if ( customClearFn ) {
				customClearFn();
			} else {
				clear();
			}
		}, 2000 );
	}
 
	/**
	 * Show the value or a "copied" message
	 *
	 * @param {string} value The value to display
	 * @return {string} The value or a "copied" message
	 */
	function showValueOrCopiedMessage( value ) {
		if ( itemsCopied.value.includes( value ) ) {
			return getCopiedText.value;
		}
		return value;
	}
 
	return {
		itemsCopied,
		getCopiedText,
		copy,
		clear,
		copyToClipboard,
		showValueOrCopiedMessage
	};
};