PluginProbe
Smart Post – Post Grid, Post Carousel, Post Slider Gutenberg Blocks for Blog & News / 4.0.7
Smart Post – Post Grid, Post Carousel, Post Slider Gutenberg Blocks for Blog & News v4.0.7
4.0.8 4.0.7 4.0.6 4.0.5 4.0.4 4.0.3 4.0.2 4.0.1 2.3.5 2.3.6 2.4.0 2.4.1 2.4.10 2.4.11 2.4.12 2.4.13 2.4.14 2.4.15 2.4.16 2.4.17 2.4.18 2.4.19 2.4.2 2.4.20 2.4.21 All 88 releases
post-carousel / src / blocks / table-of-content / helper.js

helper.js in Smart Post – Post Grid, Post Carousel, Post Slider Gutenberg Blocks for Blog & News 4.0.7, at src/blocks/table-of-content/helper.js

87 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 const generateUniqueId = (text, existingIds = new Set()) => {
2 // Normalize Unicode characters and convert to lowercase
3 const id = text
4 .normalize("NFD") // Decompose characters
5 .toLowerCase()
6 // Replace spaces, underscores, and punctuation with hyphens
7 .replace(/[\s_.,!?;:()\[\]{}'"`~@#$%^&*+=<>\/\\|]+/g, "-")
8 // Remove any characters that are not letters, numbers, or hyphens
9 // This now includes Unicode letters (all languages)
10 .replace(/[^\p{L}\p{N}-]/gu, "")
11 // Replace multiple consecutive hyphens with single hyphen
12 .replace(/-+/g, "-")
13 // Trim hyphens from beginning and end
14 .replace(/^-+|-+$/g, "");
15
16 // If empty after processing, generate random ID
17 let finalId = id;
18 if (!finalId) {
19 finalId = "heading-" + Math.random().toString(36).substr(2, 9);
20 }
21
22 // Ensure uniqueness
23 let counter = 1;
24 let uniqueId = finalId;
25 while (existingIds.has(uniqueId)) {
26 uniqueId = `${finalId}-${counter}`;
27 counter++;
28 }
29 existingIds.add(uniqueId);
30 return uniqueId;
31 };
32
33 export const removePluginContent = (content) => {
34 return content
35 .replace(/<!-- wp:smart-post-show[^>]*-->.*?<!-- \/wp:smart-post-show -->/gs, "")
36 .replace(/<h[1-6][^>]*>Smart Post Show<\/h[1-6]>/gi, "");
37 };
38
39 export const buildNestedStructure = (headings) => {
40 const root = { children: [] };
41 const stack = [root];
42 const existingIds = new Set();
43
44 headings.forEach((heading) => {
45 const level = parseInt(heading.tagName.substring(1));
46 const text = heading.textContent.trim();
47 const id = generateUniqueId(text, existingIds);
48
49 const node = {
50 id,
51 text,
52 level,
53 children: [],
54 };
55
56 while (stack.length > 1 && stack[stack.length - 1].level >= level) {
57 stack.pop();
58 }
59
60 const parent = stack[stack.length - 1];
61 parent.children.push(node);
62 stack.push(node);
63 });
64
65 return root.children;
66 };
67
68 export function flattenTOC(items) {
69 const result = [];
70
71 function traverse(itemList) {
72 for (const item of itemList) {
73 // Push the item without the 'children' key
74 const { children, ...rest } = item;
75 result.push(rest);
76
77 // Recursively flatten children
78 if (children && children.length > 0) {
79 traverse(children);
80 }
81 }
82 }
83
84 traverse(items);
85 return result;
86 }
87