Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 33 additions & 9 deletions resources/js/components/fieldtypes/LinkFieldtype.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,31 @@
<Input v-if="option === 'url'" :read-only="isReadOnly" v-model="urlValue" />

<component
v-else-if="matchedType"
v-else-if="matchedType && matchedType.metaLoaded"
:is="matchedTypeComponent"
ref="typeField"
:config="matchedType.config"
:meta="matchedType.meta"
:value="selectedByType[option]"
:handle="option"
@update:value="typeSelected"
@update:meta="updateTypeMeta"
@update:meta="updateTypeMeta(option, $event)"
/>

<Icon v-else-if="matchedType" name="loading" class="size-4 self-center" />
</div>
</div>
</template>

<script>
import Fieldtype from './Fieldtype.vue';
import { Input, Select } from '@/components/ui';
import { Icon, Input, Select } from '@/components/ui';
import debounce from '@/util/debounce.js';
import { markRaw } from 'vue';
import { UPDATE_DEBOUNCE_MS } from './constants';

export default {
components: { Input, Select },
components: { Icon, Input, Select },
mixins: [Fieldtype],

provide: {
Expand All @@ -53,6 +55,8 @@ export default {
this.update(url);
this.updateMeta({ ...this.meta, initialUrl: url });
}, UPDATE_DEBOUNCE_MS));

if (this.matchedType) this.loadTypeMeta(this.option);
},

computed: {
Expand Down Expand Up @@ -96,9 +100,13 @@ export default {
} else if (option === 'first-child') {
this.update('@child');
} else if (this.matchedType) {
this.typeValue
? this.update(this.typeValue)
: this.$nextTick(() => this.openTypeSelector());
this.loadTypeMeta(option).then(() => {
if (this.option !== option) return;

this.typeValue
? this.update(this.typeValue)
: this.$nextTick(() => this.openTypeSelector());
});
}

this.updateMeta({ ...this.meta, initialOption: option });
Expand Down Expand Up @@ -140,6 +148,22 @@ export default {
);
},

loadTypeMeta(handle) {
const type = this.meta.types[handle];

if (!type || type.metaLoaded) return Promise.resolve();

const params = {
config: utf8btoa(JSON.stringify({ ...type.config, handle })),
value: this.selectedByType[handle]?.[0] ?? null,
};

return this.$axios
.post(cp_url('fields/field-meta'), params)
.then((response) => this.updateTypeMeta(handle, response.data.meta))
.catch((e) => this.$toast.error(e.response?.data?.message || __('Something went wrong')));
},

openTypeSelector() {
const field = this.$refs.typeField;

Expand All @@ -161,12 +185,12 @@ export default {
});
},

updateTypeMeta(typeMeta) {
updateTypeMeta(handle, typeMeta) {
this.updateMeta({
...this.meta,
types: {
...this.meta.types,
[this.option]: { ...this.meta.types[this.option], meta: typeMeta },
[handle]: { ...this.meta.types[handle], meta: typeMeta, metaLoaded: true },
},
});
},
Expand Down
122 changes: 112 additions & 10 deletions resources/js/tests/components/fieldtypes/LinkFieldtype.test.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { mount } from '@vue/test-utils';
import { flushPromises, mount } from '@vue/test-utils';
import { expect, test, vi } from 'vitest';
import * as Globals from '@/bootstrap/globals';
import LinkFieldtype from '@/components/fieldtypes/LinkFieldtype.vue';

Object.keys(Globals).forEach((fn) => (window[fn] = Globals[fn]));
window.__ = (key) => key;
window.Statamic = { $config: { get: (key) => ({ cpUrl: '/cp' })[key] } };

function mountField({ value = null, config = {}, meta = {}, showFieldPreviews = false } = {}) {
function mountField({ value = null, config = {}, meta = {}, showFieldPreviews = false, axiosPost } = {}) {
return mount(LinkFieldtype, {
shallow: true,
props: {
Expand All @@ -22,6 +23,11 @@ function mountField({ value = null, config = {}, meta = {}, showFieldPreviews =
},
showFieldPreviews,
},
global: {
mocks: {
$axios: { post: axiosPost ?? vi.fn(() => Promise.resolve({ data: { meta: {} } })) },
},
},
});
}

Expand All @@ -30,8 +36,8 @@ test('builds dropdown options from the url, first child, and registered types',
meta: {
showFirstChildOption: true,
types: {
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, selected: [] },
asset: { title: 'Assets', component: 'assets', config: {}, meta: {}, selected: [] },
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, metaLoaded: true, selected: [] },
asset: { title: 'Assets', component: 'assets', config: {}, meta: {}, metaLoaded: true, selected: [] },
},
},
});
Expand Down Expand Up @@ -84,7 +90,7 @@ test('selecting a type with an existing selection emits the type reference immed
const wrapper = mountField({
meta: {
types: {
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, selected: ['4'] },
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, metaLoaded: true, selected: ['4'] },
},
},
});
Expand All @@ -101,7 +107,7 @@ test('selecting a type with no existing selection does not emit a value', async
const wrapper = mountField({
meta: {
types: {
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, selected: [] },
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, metaLoaded: true, selected: [] },
},
},
});
Expand All @@ -118,7 +124,7 @@ test('typeSelected stores the selection and emits the type reference', () => {
meta: {
initialOption: 'entry',
types: {
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, selected: ['1'] },
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, metaLoaded: true, selected: ['1'] },
},
},
});
Expand All @@ -133,8 +139,8 @@ test('initial selected values are indexed by type', () => {
const wrapper = mountField({
meta: {
types: {
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, selected: ['4'] },
asset: { title: 'Assets', component: 'assets', config: {}, meta: {}, selected: [] },
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, metaLoaded: true, selected: ['4'] },
asset: { title: 'Assets', component: 'assets', config: {}, meta: {}, metaLoaded: true, selected: [] },
},
},
});
Expand Down Expand Up @@ -171,6 +177,7 @@ test('replicatorPreview prefers the selected item title for a registered type',
component: 'relationship',
config: {},
meta: { data: [{ title: 'About Us' }] },
metaLoaded: true,
selected: ['4'],
},
},
Expand All @@ -191,6 +198,7 @@ test('replicatorPreview falls back to the basename when there is no title', () =
component: 'assets',
config: {},
meta: { data: [{ basename: 'photo.jpg' }] },
metaLoaded: true,
selected: ['4'],
},
},
Expand All @@ -206,10 +214,104 @@ test('replicatorPreview falls back to the type reference when there is no item d
meta: {
initialOption: 'entry',
types: {
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, selected: ['4'] },
entry: { title: 'Entries', component: 'relationship', config: {}, meta: {}, metaLoaded: true, selected: ['4'] },
},
},
});

expect(wrapper.vm.replicatorPreview).toBe('entry::4');
});

test('does not request meta for a type that was already preloaded', async () => {
const post = vi.fn(() => Promise.resolve({ data: { meta: {} } }));

const wrapper = mountField({
axiosPost: post,
meta: {
initialOption: 'entry',
types: {
entry: { title: 'Entries', component: 'relationship', config: {}, meta: { data: [] }, metaLoaded: true, selected: [] },
},
},
});

await wrapper.vm.$nextTick();

expect(post).not.toHaveBeenCalled();
});

test('requests meta the first time a type without preloaded meta is picked', async () => {
const post = vi.fn(() => Promise.resolve({ data: { meta: { data: [] } } }));

const wrapper = mountField({
axiosPost: post,
meta: {
types: {
entry: {
title: 'Entries',
component: 'relationship',
config: { type: 'entries', max_items: 1 },
meta: null,
metaLoaded: false,
selected: [],
},
},
},
});

wrapper.vm.option = 'entry';
await flushPromises();

expect(post).toHaveBeenCalledTimes(1);
expect(post.mock.calls[0][0]).toBe('/cp/fields/field-meta');
expect(JSON.parse(atob(post.mock.calls[0][1].config))).toEqual({
type: 'entries',
max_items: 1,
handle: 'entry',
});
expect(wrapper.emitted('update:meta').at(-1)[0].types.entry).toMatchObject({
meta: { data: [] },
metaLoaded: true,
});

wrapper.vm.option = 'url';
wrapper.vm.option = 'entry';
await flushPromises();

expect(post).toHaveBeenCalledTimes(1);
});

test('does not request meta again for a type whose fieldtype has no meta to preload', async () => {
const post = vi.fn(() => Promise.resolve({ data: { meta: null } }));

const wrapper = mountField({
axiosPost: post,
meta: {
types: {
email: {
title: 'Email',
component: 'text',
config: { type: 'text' },
meta: null,
metaLoaded: false,
selected: [],
},
},
},
});

wrapper.vm.option = 'email';
await flushPromises();

expect(post).toHaveBeenCalledTimes(1);
expect(wrapper.emitted('update:meta').at(-1)[0].types.email.metaLoaded).toBe(true);

await wrapper.setProps({ meta: wrapper.emitted('update:meta').at(-1)[0] });

wrapper.vm.option = 'url';
await flushPromises();
wrapper.vm.option = 'email';
await flushPromises();

expect(post).toHaveBeenCalledTimes(1);
});
7 changes: 5 additions & 2 deletions src/Fieldtypes/Link.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ public function preload()

$url = ($value !== '@child' && ! $linkType) ? $value : null;

$initialOption = $this->initialOption($value, $linkType);

$types = [];

foreach (static::types() as $handle => $type) {
Expand All @@ -149,14 +151,15 @@ public function preload()
'title' => $type->title(),
'component' => $nestedFieldtype->component(),
'config' => $nestedFieldtype->config(),
'meta' => $nestedFieldtype->preload(),
'meta' => $handle === $initialOption ? $nestedFieldtype->preload() : null,
'metaLoaded' => $handle === $initialOption,
'selected' => $selected ? [$selected] : [],
];
}

return [
'initialUrl' => $url,
'initialOption' => $this->initialOption($value, $linkType),
'initialOption' => $initialOption,
'showFirstChildOption' => $this->showFirstChildOption(),
'types' => $types,
];
Expand Down
65 changes: 65 additions & 0 deletions tests/Fieldtypes/LinkTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,71 @@ public function it_excludes_a_custom_type_with_a_null_fieldtype_from_preload()
$this->assertArrayNotHasKey('link-extend-test-no-picker', $fieldtype->preload()['types']);
}

#[Test]
public function it_only_preloads_meta_for_the_initial_option()
{
$this->setUpRoutableCollection();

Facades\AssetContainer::make('assets')->disk('local')->save();

$field = new Field('test', ['type' => 'link', 'container' => 'assets']);
$field->setValue('entry::123');

$types = (new Link)->setField($field)->preload()['types'];

$this->assertNotNull($types['entry']['meta']);
$this->assertTrue($types['entry']['metaLoaded']);
$this->assertNull($types['asset']['meta']);
$this->assertFalse($types['asset']['metaLoaded']);
}

#[Test]
public function it_preloads_meta_for_the_default_option_when_there_is_no_value()
{
$this->setUpRoutableCollection();

Facades\AssetContainer::make('assets')->disk('local')->save();

$field = new Field('test', ['type' => 'link', 'container' => 'assets', 'default_option' => 'asset']);

$types = (new Link)->setField($field)->preload()['types'];

$this->assertNull($types['entry']['meta']);
$this->assertFalse($types['entry']['metaLoaded']);
$this->assertNotNull($types['asset']['meta']);
$this->assertTrue($types['asset']['metaLoaded']);
}

#[Test]
public function it_preloads_no_type_meta_when_there_is_no_initial_option()
{
$this->setUpRoutableCollection();

Facades\AssetContainer::make('assets')->disk('local')->save();

$field = new Field('test', ['type' => 'link', 'container' => 'assets']);

$types = (new Link)->setField($field)->preload()['types'];

$this->assertNull($types['entry']['meta']);
$this->assertFalse($types['entry']['metaLoaded']);
$this->assertNull($types['asset']['meta']);
$this->assertFalse($types['asset']['metaLoaded']);
}

#[Test]
public function it_marks_meta_as_loaded_for_a_type_whose_fieldtype_preloads_nothing()
{
Link::extend('link-extend-test-basic-preload', TestBasicLinkType::class);

$field = new Field('test', ['type' => 'link', 'default_option' => 'link-extend-test-basic-preload']);

$types = (new Link)->setField($field)->preload()['types'];

$this->assertNull($types['link-extend-test-basic-preload']['meta']);
$this->assertTrue($types['link-extend-test-basic-preload']['metaLoaded']);
}

#[Test]
public function it_includes_custom_type_and_icon_in_pre_process_index()
{
Expand Down
Loading