Skip to content

Commit e8356b8

Browse files
committed
Preserve portable file references in editor cards [all]
Normalize scalar file values for card rendering without changing saved attributes. Keep fallback cards removable and sortable alongside media IDs, and cover single and repeater fields, save/reload, and media selection. Refs #117
1 parent 3ec626a commit e8356b8

13 files changed

Lines changed: 348 additions & 75 deletions

File tree

‎docs/docs/blocks/attributes/field-types.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ All fields share these common properties:
4242
| `switch` | boolean | Display a toggle that can disable the field. Defaults to `false`. |
4343
| `conditions` | array | Conditional logic rules |
4444

45+
Files fields with `"returnFormat": "id"` preserve imported string references,
46+
including single values inside repeaters. Unresolved names show fallback cards
47+
without thumbnails; Blockstudio does not resolve them to attachment IDs. See
48+
[portable media references](/guides/field-patterns#return-format-variations) for details.
49+
4550
<!-- GENERATED_FIELD_TYPES_START -->
4651

4752
## attributes

‎docs/guides/field-patterns.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,16 @@ Control what the files field returns:
582582

583583
Use `"id"` when you need to call `wp_get_attachment_image()` yourself. Use `"url"` for simple background images. Use `"object"` (the default) for everything else.
584584

585+
With `"returnFormat": "id"`, an imported string reference such as `"buckshair-home"`
586+
is passed through unchanged. The editor shows a fallback card without a thumbnail,
587+
including in repeater rows. Opening or saving the page does not convert a scalar
588+
reference into an array. Mixed lists of attachment IDs and string references also
589+
work; only positive attachment IDs are looked up in the media library.
590+
591+
Blockstudio does not resolve custom string references to attachments. Resolve them
592+
in your own render filter or template when using portable names across sites.
593+
Choosing a replacement in the media library stores its attachment ID as usual.
594+
585595
## Dynamic Options
586596

587597
### Populate from posts
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
<?php return array('dependencies' => array('lodash', 'react', 'react-dom', 'react-jsx-runtime', 'wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-compose', 'wp-data', 'wp-dom-ready', 'wp-element', 'wp-hooks', 'wp-i18n', 'wp-plugins', 'wp-polyfill', 'wp-primitives'), 'version' => '9def4e00fa6f4bd266a3');
1+
<?php return array('dependencies' => array('lodash', 'react', 'react-dom', 'react-jsx-runtime', 'wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-compose', 'wp-data', 'wp-dom-ready', 'wp-element', 'wp-hooks', 'wp-i18n', 'wp-plugins', 'wp-polyfill', 'wp-primitives'), 'version' => '6f549865a1fb1a708e6f');

‎includes/admin/assets/blocks/index.tsx.js‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎readme.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ Download the latest release zip from [GitHub Releases](https://github.com/inline
6565
* Fix: the Update URI header prevents unrelated WordPress.org plugins from being offered as Blockstudio updates (#113)
6666
* Fix: repeater row preferences preserve other rows and tolerate unavailable or malformed browser storage
6767
* Fix: links inside Blockstudio blocks no longer navigate away from the editor when clicked (#116)
68+
* Fix: files fields accept scalar string references without crashing the editor and preserve fallback cards when removing or reordering values (#117)
6869

6970
= 7.7.1 =
7071
* Fix: page sync skips post writes, update hooks, timestamps, and revisions when merged content and managed fields are unchanged (#104)

‎src/blocks/components/fields/components/files.tsx‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,12 @@ import { Base } from '@/blocks/components/base';
77
import { Cards } from '@/blocks/components/list/cards';
88
import { useMedia } from '@/blocks/hooks/use-media';
99
import { selectors } from '@/blocks/store/selectors';
10+
import { isMediaId, normalizeCardValues } from '@/blocks/utils/card-values';
1011
import { BlockstudioAttribute } from '@/types/block';
11-
import { BlockstudioBlockAttributes } from '@/types/types';
12+
import {
13+
BlockstudioBlockAttributes,
14+
BlockstudioFieldsChange,
15+
} from '@/types/types';
1216
import { __ } from '@/utils/__';
1317
import { css } from '@/utils/css';
1418

@@ -26,17 +30,15 @@ export const Files = ({
2630
...rest
2731
}: {
2832
attributes: BlockstudioBlockAttributes;
29-
change: (val: string[] | string, media?: boolean, size?: string) => void;
33+
change: BlockstudioFieldsChange;
3034
config: boolean;
3135
disable: (id: string) => void;
3236
inRepeater: boolean;
3337
item: BlockstudioAttribute;
34-
v: string[];
38+
v: string | number | (string | number)[] | false | null | undefined;
3539
repeaterId: string;
3640
}) => {
37-
const mediaIds = (Array.isArray(v) ? v : [v]).filter((id) =>
38-
/^[1-9]\d*$/.test(`${id ?? ''}`),
39-
);
41+
const mediaIds = normalizeCardValues(v).filter(isMediaId).map(Number);
4042
const shouldResolveMedia = mediaIds.length > 0;
4143

4244
useMedia(mediaIds);
@@ -111,7 +113,7 @@ export const Files = ({
111113
<MediaUploadCheck>
112114
<MediaUpload
113115
{...rest}
114-
value={v as unknown as number}
116+
value={(Array.isArray(v) ? mediaIds : mediaIds[0]) as number}
115117
modalClass={` blockstudio-function__media-min-${
116118
item?.min || 0
117119
} blockstudio-function__media-max-${item?.max || 'unlimited'}`}

‎src/blocks/components/list/cards.tsx‎

Lines changed: 59 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ import {
66
} from '@wordpress/components';
77
import { forwardRef, useState } from '@wordpress/element';
88
import { closeSmall, file } from '@wordpress/icons';
9-
import { isArray } from 'lodash-es';
109
import { Control } from '@/blocks/components/control';
1110
import { List } from '@/blocks/components/list/index';
1211
import { Label } from '@/blocks/components/list/label';
12+
import { isMediaId, normalizeCardValues } from '@/blocks/utils/card-values';
1313
import {
1414
Any,
1515
BlockstudioBlockAttributes,
16+
BlockstudioFieldsChange,
1617
BlockstudioFieldsListMove,
1718
BlockstudioFieldsRepeaterAddRemove,
1819
} from '@/types/types';
@@ -33,6 +34,7 @@ type CardDataObject = {
3334
};
3435

3536
type CardData = CardDataObject | string | number | null | undefined;
37+
type CardValues = CardData | CardData[] | false;
3638

3739
const getCardDataObject = (data: CardData): CardDataObject =>
3840
data && typeof data === 'object' ? data : {};
@@ -67,7 +69,7 @@ export const Card = forwardRef<
6769
HTMLDivElement,
6870
{
6971
attributes: BlockstudioBlockAttributes;
70-
change: (val: string[], media: boolean) => void;
72+
change: BlockstudioFieldsChange;
7173
data: CardData;
7274
id: string;
7375
inRepeater: boolean;
@@ -78,9 +80,7 @@ export const Card = forwardRef<
7880
onClick: (name: string) => void;
7981
onClickDelete?: () => void;
8082
style?: Record<string, string>;
81-
v: {
82-
[key: string]: Any;
83-
};
83+
v: CardValues;
8484
}
8585
>(
8686
(
@@ -118,16 +118,10 @@ export const Card = forwardRef<
118118
}
119119

120120
if (showDelete) {
121-
const filteredIds = isArray(v)
122-
? v.filter(
123-
(e) =>
124-
e !== dataObject.id &&
125-
(media ? true : e?.value !== dataObject.value),
126-
)
127-
: [];
128-
const transformedIds = (
129-
filteredIds.length === 0 ? false : filteredIds
130-
) as string[];
121+
const filteredIds = normalizeCardValues(v).filter(
122+
(_, valueIndex) => valueIndex !== index,
123+
);
124+
const transformedIds = filteredIds.length === 0 ? false : filteredIds;
131125
change(transformedIds, !media);
132126
}
133127
};
@@ -290,9 +284,9 @@ export const Cards = ({
290284
v,
291285
}: {
292286
attributes: BlockstudioBlockAttributes;
293-
change: (val: string[], media: boolean) => void;
287+
change: BlockstudioFieldsChange;
294288
disable: BlockstudioFieldsRepeaterAddRemove;
295-
ids: string[];
289+
ids: CardValues;
296290
inRepeater: boolean;
297291
item: {
298292
id?: string;
@@ -307,53 +301,57 @@ export const Cards = ({
307301
>
308302
| boolean;
309303
style?: Record<string, string>;
310-
v: {
311-
[key: string]: Any;
312-
};
304+
v: CardValues;
313305
}) => {
314-
return v?.length || v ? (
315-
<List {...{ style, ids }} onChange={(val) => change(val, !media)}>
306+
const values = normalizeCardValues(v);
307+
308+
return values.length ? (
309+
<List
310+
style={style}
311+
ids={normalizeCardValues(ids)}
312+
onChange={(val) => change(val, !media)}
313+
>
316314
{({ moveUp, moveDown }) =>
317-
(v.length ? v : [v]).map(
318-
(itemInner: string | number, index: number) => {
319-
const el = (media as Record<string, Any>)?.[itemInner] ?? itemInner;
320-
const id = `${v[index]?.value || v[index]}`;
315+
values.map((itemInner, index) => {
316+
const el = isMediaId(itemInner)
317+
? ((media as Record<string, Any>)?.[itemInner] ?? itemInner)
318+
: itemInner;
319+
const id = `${getCardDataObject(itemInner).value ?? itemInner}`;
321320

322-
return (
323-
<Draggable
324-
{...{ index }}
325-
key={id}
326-
draggableId={id}
327-
isDragDisabled={!v?.length}
328-
>
329-
{(provided, snapshot) => (
330-
<Card
331-
ref={provided.innerRef}
332-
{...provided.draggableProps}
333-
{...provided.dragHandleProps}
334-
{...{
335-
attributes,
336-
change,
337-
inRepeater,
338-
index,
339-
moveDown,
340-
moveUp,
341-
v,
342-
}}
343-
data={el}
344-
id={item.id || item.value || ''}
345-
loaded={media ? el?.mime_type : true}
346-
onClick={(id) => disable(id)}
347-
style={getItemStyle(
348-
snapshot.isDragging,
349-
provided.draggableProps.style || {},
350-
)}
351-
/>
352-
)}
353-
</Draggable>
354-
);
355-
},
356-
)
321+
return (
322+
<Draggable
323+
{...{ index }}
324+
key={id}
325+
draggableId={id}
326+
isDragDisabled={!Array.isArray(v)}
327+
>
328+
{(provided, snapshot) => (
329+
<Card
330+
ref={provided.innerRef}
331+
{...provided.draggableProps}
332+
{...provided.dragHandleProps}
333+
{...{
334+
attributes,
335+
change,
336+
inRepeater,
337+
index,
338+
moveDown,
339+
moveUp,
340+
v,
341+
}}
342+
data={el}
343+
id={item.id || item.value || ''}
344+
loaded={!media || !isMediaId(itemInner) || !!el?.mime_type}
345+
onClick={(id) => disable(id)}
346+
style={getItemStyle(
347+
snapshot.isDragging,
348+
provided.draggableProps.style || {},
349+
)}
350+
/>
351+
)}
352+
</Draggable>
353+
);
354+
})
357355
}
358356
</List>
359357
) : null;

‎src/blocks/components/list/index.tsx‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { ConditionalWrapper } from '@/components/conditional-wrapper';
44
import { BlockstudioFieldsListMove } from '@/types/types';
55
import { css } from '@/utils/css';
66

7-
export const List = ({
7+
export const List = <T,>({
88
children,
99
context = true,
1010
id = 'droppable',
@@ -24,8 +24,8 @@ export const List = ({
2424
}) => ReactNode);
2525
context?: boolean;
2626
id?: string;
27-
ids?: string[];
28-
onChange?: (ids: string[], droppableId: string) => void;
27+
ids?: T[];
28+
onChange?: (ids: T[], droppableId: string) => void;
2929
repeaters?: { [key: string]: string[] };
3030
style?: Record<string, string>;
3131
}) => {
@@ -66,7 +66,7 @@ export const List = ({
6666
data,
6767
result.source.index,
6868
result.destination.index,
69-
) as string[];
69+
) as T[];
7070

7171
onChange?.(newItems, droppableId || '');
7272
};
@@ -87,7 +87,7 @@ export const List = ({
8787

8888
const data = droppableId ? repeaterData(droppableId) : ids || [];
8989
const newItems = reorder(data, index, index + offset);
90-
onChange?.(newItems as string[], droppableId);
90+
onChange?.(newItems as T[], droppableId);
9191

9292
const focusIndex = index + offset;
9393
(

‎src/blocks/utils/card-values.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export const normalizeCardValues = <T>(
2+
value: T | T[] | false | null | undefined,
3+
): T[] => (Array.isArray(value) ? value : value ? [value] : []);
4+
5+
export const isMediaId = (value: unknown): value is string | number =>
6+
(typeof value === 'string' || typeof value === 'number') &&
7+
/^[1-9]\d*$/.test(`${value}`);

‎tests/client/card-values.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'node:test';
3+
import {
4+
isMediaId,
5+
normalizeCardValues,
6+
} from '../../src/blocks/utils/card-values';
7+
8+
test('single file values become one card without splitting strings', () => {
9+
for (const value of ['buckshair-home', '1604', 1604]) {
10+
assert.deepEqual(normalizeCardValues(value), [value]);
11+
}
12+
});
13+
14+
test('empty file values produce no cards', () => {
15+
for (const value of [false, null, undefined, '', 0, []]) {
16+
assert.deepEqual(normalizeCardValues(value), []);
17+
}
18+
});
19+
20+
test('file arrays and select option objects preserve their values and identity', () => {
21+
const files = ['buckshair-home', 1604, 'another-image'];
22+
const options = [
23+
{ value: 'first', label: 'First' },
24+
{ value: 'second', label: 'Second' },
25+
];
26+
assert.equal(normalizeCardValues(files), files);
27+
assert.equal(normalizeCardValues(options), options);
28+
assert.equal(normalizeCardValues(options[0])[0], options[0]);
29+
assert.deepEqual(files, ['buckshair-home', 1604, 'another-image']);
30+
});
31+
32+
test('only attachment IDs are eligible for media resolution', () => {
33+
for (const value of [1604, '1604', 1, '1']) {
34+
assert.equal(isMediaId(value), true);
35+
}
36+
for (const value of [
37+
'buckshair-home',
38+
'',
39+
'0',
40+
0,
41+
-1,
42+
1.5,
43+
'1604abc',
44+
'https://example.com/a.jpg',
45+
false,
46+
null,
47+
undefined,
48+
{},
49+
[],
50+
]) {
51+
assert.equal(isMediaId(value), false);
52+
}
53+
assert.deepEqual(
54+
normalizeCardValues(['buckshair-home', 1604, '1605']).filter(isMediaId),
55+
[1604, '1605'],
56+
);
57+
});

0 commit comments

Comments
 (0)