| 1 |
import slugify from 'slugify'; |
| 2 |
import striptags from 'striptags'; |
| 3 |
|
| 4 |
import { select } from '@wordpress/data'; |
| 5 |
const { getBlocks } = select('core/block-editor'); |
| 6 |
|
| 7 |
/** |
| 8 |
* Get all block IDs. |
| 9 |
* |
| 10 |
* @param {Array} excludeId exclude block client id. |
| 11 |
* @param {Array} blocks blocks list to check. |
| 12 |
* |
| 13 |
* @return {Array} block anchors and slugs array. |
| 14 |
*/ |
| 15 |
function getAllSlugs(excludeId, blocks = 'none') { |
| 16 |
let slugs = []; |
| 17 |
|
| 18 |
if (blocks === 'none') { |
| 19 |
blocks = getBlocks(); |
| 20 |
} |
| 21 |
|
| 22 |
blocks.forEach((block) => { |
| 23 |
if (block.clientId !== excludeId && block.attributes) { |
| 24 |
if (block.attributes.anchor) { |
| 25 |
slugs.push(block.attributes.anchor); |
| 26 |
} |
| 27 |
if ( |
| 28 |
(block.name === 'ghostkit/tabs-tab-v2' || |
| 29 |
block.name === 'ghostkit/accordion-item') && |
| 30 |
block.attributes.slug |
| 31 |
) { |
| 32 |
slugs.push(block.attributes.slug); |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
if (block.innerBlocks && block.innerBlocks.length) { |
| 37 |
slugs = [...slugs, ...getAllSlugs(excludeId, block.innerBlocks)]; |
| 38 |
} |
| 39 |
}); |
| 40 |
|
| 41 |
return slugs; |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Check if slug is unique. |
| 46 |
* |
| 47 |
* @param {string} slug new slug. |
| 48 |
* @param {Array} slugs slugs list to check. |
| 49 |
* |
| 50 |
* @return {boolean} is unique. |
| 51 |
*/ |
| 52 |
function isUniqueSlug(slug, slugs) { |
| 53 |
let isUnique = true; |
| 54 |
|
| 55 |
slugs.forEach((thisSlug) => { |
| 56 |
if (thisSlug === slug) { |
| 57 |
isUnique = false; |
| 58 |
} |
| 59 |
}); |
| 60 |
|
| 61 |
return isUnique; |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Get slug from title. |
| 66 |
* |
| 67 |
* @param {string} title title string. |
| 68 |
* |
| 69 |
* @return {string} slug. |
| 70 |
*/ |
| 71 |
export function getSlug(title) { |
| 72 |
return slugify(striptags(title), { |
| 73 |
replacement: '-', |
| 74 |
remove: /[*_+~()'"!?/\-—–−:@^|&#.,;%<>{}]/g, |
| 75 |
lower: true, |
| 76 |
}); |
| 77 |
} |
| 78 |
|
| 79 |
/** |
| 80 |
* Get unique slug from title. |
| 81 |
* |
| 82 |
* @param {string} title title string. |
| 83 |
* @param {string} excludeBlockId exclude block id to not check. |
| 84 |
* |
| 85 |
* @return {string} slug. |
| 86 |
*/ |
| 87 |
export default function getUniqueSlug(title, excludeBlockId) { |
| 88 |
let newSlug = ''; |
| 89 |
let i = 0; |
| 90 |
const allSlugs = getAllSlugs(excludeBlockId); |
| 91 |
|
| 92 |
while (!newSlug || !isUniqueSlug(newSlug, allSlugs)) { |
| 93 |
if (newSlug) { |
| 94 |
i += 1; |
| 95 |
} |
| 96 |
newSlug = `${getSlug(title)}${i ? `-${i}` : ''}`; |
| 97 |
} |
| 98 |
|
| 99 |
return newSlug; |
| 100 |
} |
| 101 |
|