-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathutil.js
More file actions
395 lines (323 loc) · 12.2 KB
/
util.js
File metadata and controls
395 lines (323 loc) · 12.2 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/* eslint-disable no-console */
import DEFAULT from './default.json'
import {
settings, isPro, cdnUrl,
} from 'stackable'
import { META_SEPARATORS } from '~stackable/util'
import { parse, serialize } from '@wordpress/blocks'
import { select } from '@wordpress/data'
export const DEFAULT_CONTENT = { ...DEFAULT }
const PARSER = new DOMParser()
export const cleanParse = content => {
const originalConsoleError = console.error
const originalConsoleWarn = console.warn
console.error = ( ...args ) => {
if ( args.length && typeof args[ 0 ] === 'string' &&
args[ 0 ].includes( 'Block validation failed' )
) {
return
}
originalConsoleError( ...args )
}
console.warn = ( ...args ) => {
if ( args.length && typeof args[ 0 ] === 'string' &&
args[ 0 ].includes( 'Block validation' )
) {
return
}
originalConsoleWarn( ...args )
}
let result
try {
result = parse( content )
} finally {
console.error = originalConsoleError
console.warn = originalConsoleWarn
}
return result
}
const replaceInnerContent = ( originalContent, newInnerHTML ) => {
const openTag = '<!-- wp:'
const closeTag = '<!-- /wp:'
const openIndex = originalContent.indexOf( openTag, openTag.length )
const lastClose = originalContent.lastIndexOf( closeTag )
const secondLastClose = originalContent.lastIndexOf( closeTag, lastClose - 1 )
const closeEnd = originalContent.indexOf( '-->', secondLastClose )
if ( openIndex === -1 || secondLastClose === -1 || closeEnd === -1 ) {
return originalContent
}
const before = originalContent.slice( 0, openIndex )
const after = originalContent.slice( closeEnd + 3 )
return `${ before }${ newInnerHTML }${ after }`
}
export const addContainerScheme = (
block,
containerScheme
) => {
const addScheme = blocks => {
return blocks.map( block => {
if ( block.innerBlocks?.length ) {
block.innerBlocks = addScheme( block.innerBlocks )
}
if ( block.attributes.hasContainer ) {
block.attributes.containerColorScheme = containerScheme
}
if ( block.name === 'core/missing' && block.attributes.originalName ) {
const { originalAttributes } = block.attributes
let innerHTML = ''
if ( block.innerBlocks.length ) {
innerHTML = serialize( block.innerBlocks )
} else if ( originalAttributes.text ) {
innerHTML = originalAttributes.text
}
const updatedContent = replaceInnerContent( block.attributes.originalContent, innerHTML )
block.attributes.originalContent = updatedContent
}
return block
} )
}
const newBlock = addScheme( block )
return newBlock
}
export const addBackgroundScheme = (
blocks,
enableBackground,
backgroundScheme,
addHasBackground = true
) => {
const addBackground = block => {
if ( addHasBackground ) {
block.attributes.hasBackground = true
}
if ( block.attributes.hasBackground && backgroundScheme !== '' ) {
block.attributes.backgroundColorScheme = backgroundScheme
}
return block
}
const getTargetBlock = blocks => {
blocks.forEach( _block => {
const customAttributes = _block.attributes.customAttributes
const isTarget = customAttributes?.find( attribute => attribute[ 0 ] === 'stk-design-library__bg-target' && attribute[ 1 ] === 'true' )
if ( isTarget ) {
_block = addBackground( _block )
} else if ( _block.innerBlocks.length ) {
getTargetBlock( _block.innerBlocks )
}
} )
}
if ( ! enableBackground ) {
return blocks
}
return blocks.map( block => {
const customAttributes = block.attributes.customAttributes
if ( ! customAttributes?.length ) {
block = addBackground( block )
return block
}
getTargetBlock( block.innerBlocks )
return block
} )
}
export const adjustPatternSpacing = ( attributes, category, spacingSize, isDesignLibraryDevMode ) => {
// Note: The styles for block margin/padding will only be generated by the BlockCssGenerator,
// which updates the generatedCss attribute. Therefore, updating the block margin/padding
// attributes here will have no effect on the preview. Instead, we add additional CSS directly
// to the generatedCss attribute for preview purposes. This generatedCss will be regenerated
// by the BlockCssGenerator once the pattern is actually added to the editor.
let additionalCss = ''
if ( ! isDesignLibraryDevMode && category !== 'header' ) {
if ( attributes.hasBackground ) {
additionalCss += 'margin-bottom: 0px !important;'
} else {
additionalCss += `margin-top: ${ spacingSize } !important;`
additionalCss += `margin-bottom: ${ spacingSize } !important;`
}
const blockLayouts = select( 'stackable/global-spacing-and-borders' ).getBlockLayouts()
if ( attributes.hasBackground && typeof blockLayouts === 'object' && ! blockLayouts[ 'block-background-padding' ] ) {
additionalCss += `padding-top: ${ spacingSize } !important;`
additionalCss += `padding-right: ${ spacingSize } !important;`
additionalCss += `padding-bottom: ${ spacingSize } !important;`
additionalCss += `padding-left: ${ spacingSize } !important;`
}
}
if ( additionalCss && attributes.uniqueId ) {
attributes.generatedCss += `.stk-${ attributes.uniqueId } {${ additionalCss }}`
}
}
export const replacePlaceholders = ( designContent, designCategory, isDesignLibraryDevMode, type ) => {
if ( type === 'saved' ) {
return designContent
}
const defaultValues = DEFAULT_CONTENT[ designCategory ]
if ( defaultValues && ! isDesignLibraryDevMode ) {
Object.keys( defaultValues ).forEach( key => {
designContent = designContent.replaceAll( key, defaultValues[ key ] )
} )
}
return designContent
}
const retrieveAttributes = ( blockName, hasNoInnerBlocks, content ) => {
const attrs = content.match( /{.*}/ )
let parsedAttrs = {}
if ( attrs ) {
try {
parsedAttrs = JSON.parse( attrs[ 0 ] )
if ( hasNoInnerBlocks ) {
content = content.replace( /<style[^>]*>[\s\S]*?<\/style>/gi, '' )
const doc = PARSER.parseFromString( content, 'text/html' )
parsedAttrs.text = doc.body.textContent.trim()
}
} catch ( err ) {}
}
return parsedAttrs
}
export const parseDisabledBlocks = parsedBlocks => {
const disabledBlocks = settings.stackable_block_states || []
const blocksForSubstitution = new Set()
if ( Array.isArray( disabledBlocks ) && ! disabledBlocks.length ) {
return [ parsedBlocks, blocksForSubstitution ]
}
const addOriginalAttributes = blocks => {
return blocks.map( block => {
if ( block.name === 'core/missing' ) {
blocksForSubstitution.add( block.attributes.originalName )
const newAttrs = retrieveAttributes( block.attributes.originalName, block.innerBlocks.length === 0, block.attributes.originalContent )
const attrs = block.attributes
block.attributes = {
...attrs, ...newAttrs, originalAttributes: newAttrs,
}
}
block.innerBlocks = addOriginalAttributes( block.innerBlocks )
return block
} )
}
const blocks = addOriginalAttributes( parsedBlocks )
return [ blocks, blocksForSubstitution ]
}
const IMAGE_STORAGE = cdnUrl.replace( /\/$/, '' ) + '/library-v4/images/'
export const addPlaceholderForPostsBlock = ( content, postsPlaceholder, defaultValues, img = null ) => {
const remainingPosts = [ ...postsPlaceholder ]
// Normalize special characters
const normalized = content
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /–/g, '-' )
.replace( /\u2013|\u2014/g, '-' )
// Regex to match all stackable/posts blocks
const postBlockRegex = /<!--\s*wp:stackable\/posts\s+(\{[\s\S]*?\})\s*-->([\s\S]*?)<!--\s*\/wp:stackable\/posts\s*-->/g
return normalized.replace( postBlockRegex, ( match, jsonStr, innerHtml ) => {
let attrs
try {
attrs = JSON.parse( jsonStr )
} catch {
return match // Skip if JSON is invalid
}
const numItems = attrs.numberOfItems ?? 6
const width = attrs.imageWidth ? attrs.imageWidth + ( attrs.imageWidthUnit ?? 'px' ) : 'auto'
const separator = META_SEPARATORS[ attrs.metaSeparator ?? 'dot' ]
// Get the post template inside the block
const templateMatch = innerHtml.match( /<!--\s*\/stk-start:posts\/template\s*-->([\s\S]*?)<!--\s*\/stk-end:post\/template\s*-->/ )
if ( ! templateMatch ) {
return match // Skip if template is missing
}
const template = templateMatch[ 1 ].trim()
let currentPosts
if ( numItems <= remainingPosts.length ) {
currentPosts = remainingPosts.slice( 0, numItems )
} else {
const needed = numItems
const postsToUse = [
...remainingPosts,
...Array.from(
{ length: needed - remainingPosts.length },
( _, i ) => postsPlaceholder[ i % postsPlaceholder.length ] // reuse placeholders if numberOfItems > 6
),
]
currentPosts = postsToUse.slice( 0, numItems )
}
const renderedPosts = currentPosts.map( ( post, index ) => {
const imgSrc = img ?? `${ IMAGE_STORAGE }stk-design-library-image-${ index + 1 }.jpeg`
return template
.replace( /!#title!#/g, post.title_placeholder )
.replace( /!#excerpt!#/g, post.text_placeholder )
.replace( /!#authorName!#/g, 'John Doe' )
.replaceAll( /!#metaSeparator!#/g, separator )
.replace( /!#commentsNum!#/g, '3 comments' )
.replace( /!#date!#/g, 'March 1, 2025' )
.replace( /!#readmoreText!#/g, defaultValues[ 'post-btn_placeholder' ] )
.replace( /!#category!#/g, defaultValues.tag_placeholder )
.replace( /img class="stk-img"/g, `img class="stk-img" src="${ imgSrc }" width="${ width }" style="width: ${ width } !important;"` )
} ).join( '\n' )
// Replace just the template portion, keep rest of the block
const updatedInnerHtml = innerHtml.replace(
/<!--\s*\/stk-start:posts\/template\s*-->([\s\S]*?)<!--\s*\/stk-end:post\/template\s*-->/,
renderedPosts
)
return `<!-- wp:stackable/posts ${ jsonStr } -->${ updatedInnerHtml }<!-- /wp:stackable/posts -->`
} )
}
export const replaceImages = content => {
const NEW_IMAGE_STORAGE = cdnUrl.replace( /\/$/, '' ) + '/library-v4/images/low-resolution/'
// Replace images in the content with low resolution images from the new image storage
return content.replace(
new RegExp( IMAGE_STORAGE.replace( /[.*+?^${}()|[\]\\]/g, '\\$&' ) + '([^\\/\\s]+\\.(jpeg|jpg|png))', 'g' ),
( match, filenameWithExt ) => {
return NEW_IMAGE_STORAGE + filenameWithExt
}
)
}
export const getCategorySlug = id => {
if ( typeof id !== 'string' ) {
return ''
}
if ( id.startsWith( 'section-' ) ) {
// Remove 'section-' prefix and trailing dash + number
return id.replace( /^section-/, '' ).replace( /-\d+$/, '' )
}
// Remove trailing dash + number for other ids
return id.replace( /-\d+$/, '' )
}
// Additional styles for blocks to render properly in the preview
export const getAdditionalStylesForPreview = () => {
let styles = ''
// Creates a Block Formatting Context (BFC), ensuring it contains the margin of its children
styles += 'body { display: flow-root; }'
styles += 'body { --stk-block-wide-width: 1000px; }'
// Use overflow-y: hidden to prevent mousewheel scrolling
styles += 'body.preview-pages { overflow-y: hidden; max-height: 1200px; }'
styles += '::-webkit-scrollbar { width: 0; }'
styles += 'body.preview-pages { scrollbar-width: none; -ms-overflow-style: none; }'
// Make sure count up block numbers are visible
styles += `.stk-block-count-up__text:not(.stk--count-up-active) { opacity: 1; }`
// Fill the vertical line in timeline blocks
styles += `.stk-block-timeline { --line-bg-color: var(--line-accent-bg-color, #000); }`
// Display correctly the progress in progress bar and progress circle blocks
styles += `.stk-progress-bar .stk-progress-bar__bar { width: var(--progress-percent, 0px); }`
styles += `.stk-progress-circle .stk-progress-circle__bar { stroke-dashoffset: var(--progress-dash-offset); }`
// Set styles for maps graphic
styles += `.stk-block-map { height: 100%; } .stk-block-map > img { height: 100%; width: 100%; object-fit: cover; }`
// Display correctly the styles for posts block.
// Do this only if in Free version, since we will be able to load the correct CSS for Premium.
if ( ! isPro ) {
styles += `.stk-block-posts.is-style-horizontal-2 {
.stk-block-posts__item > .stk-container {
padding: 0;
display: flex;
flex-direction: row;
> .stk-block-posts__image-link:empty ~ .stk-container-padding,
.stk-container-padding:only-child {
width: 100%;
}
}
.stk-img-wrapper {
height: 100%;
margin-top: 0;
margin-bottom: 0;
}
.stk-block-posts__image-link {
margin-bottom: 0;
}
}`
}
return styles
}