Skip to content
Open
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
12 changes: 12 additions & 0 deletions resources/js/components/blueprints/Builder.vue
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import SuggestsConditionalFields from './SuggestsConditionalFields';
import Tabs from './Tabs.vue';
import CanDefineLocalizable from '../fields/CanDefineLocalizable';
import { computed } from 'vue';

export default {
mixins: [SuggestsConditionalFields, CanDefineLocalizable],
Expand All @@ -59,6 +60,17 @@ export default {
isFormBlueprint: { type: Boolean, default: false },
},

provide() {
return {
fieldtypeContext: computed(() => ({
view: 'blueprint',
blueprint: this.initialBlueprint.fullyQualifiedHandle,
field_path: [],
nested: false,
})),
};
},

data() {
return {
blueprint: this.initializeBlueprint(),
Expand Down
13 changes: 13 additions & 0 deletions resources/js/components/blueprints/Section.vue
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,25 @@
import Fields from './Fields.vue';
import CanDefineLocalizable from '../fields/CanDefineLocalizable';
import { Switch, Heading } from '@/components/ui';
import { computed } from 'vue';

export default {
mixins: [CanDefineLocalizable],

inject: {
suggestableConditionFieldsProvider: { default: null },
parentFieldtypeContext: { from: 'fieldtypeContext', default: () => ({}) },
isInsideSet: { default: false },
},

provide() {
return {
fieldtypeContext: computed(() => this.isInsideSet ? {
...this.parentFieldtypeContext,
field_path: [...(this.parentFieldtypeContext.field_path ?? []), this.section.handle],
nested: true,
} : this.parentFieldtypeContext),
};
},

components: {
Expand Down
59 changes: 37 additions & 22 deletions resources/js/components/fields/FieldtypeSelector.vue
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ import fuzzysort from 'fuzzysort';
import { ref } from 'vue';
import { mapValues } from 'lodash-es';
import { Icon } from '@/components/ui';
import qs from 'qs';

const loadedFieldtypes = ref(null);
const loadedFieldtypes = ref({});

export default {
components: {
Expand All @@ -72,6 +73,10 @@ export default {
},
},

inject: {
fieldtypeContext: { default: () => ({}) },
},

data: function () {
return {
categories: {
Expand Down Expand Up @@ -112,18 +117,19 @@ export default {
fieldtypes() {
if (!this.fieldtypesLoaded) return;

return loadedFieldtypes.value.data;
return loadedFieldtypes.value[this.cacheKey];
},

isFormBlueprint() {
return !!this.$config.get('isFormBlueprint');
},

cacheKey() {
return JSON.stringify({ forms: this.isFormBlueprint, context: this.fieldtypeContext });
},

fieldtypesLoaded() {
// The cache is shared across every picker instance, but form and regular blueprints
// request different lists. Only treat it as loaded when the cached list matches the
// current blueprint mode, otherwise we'll refetch the correct one.
return Array.isArray(loadedFieldtypes.value?.data) && loadedFieldtypes.value.forms === this.isFormBlueprint;
return Array.isArray(loadedFieldtypes.value[this.cacheKey]);
},

allFieldtypes() {
Expand Down Expand Up @@ -217,6 +223,13 @@ export default {
},

watch: {
cacheKey: {
immediate: true,
handler() {
this.loadFieldtypes();
},
},

fieldtypesLoaded: {
immediate: true,
handler() {
Expand All @@ -229,24 +242,26 @@ export default {
},
},

created() {
if (this.fieldtypesLoaded) return;

const forms = this.isFormBlueprint;

let url = cp_url('fields/fieldtypes?selectable=true');

if (forms) url += '&forms=true';

this.$axios.get(url)
.then((response) => (loadedFieldtypes.value = { forms, data: response.data }))
.catch((e) => {
this.$toast.error(e.response?.data?.message || __('Something went wrong'));
this.close();
methods: {
loadFieldtypes() {
if (this.fieldtypesLoaded) return;

const key = this.cacheKey;
const query = qs.stringify({
selectable: true,
forms: this.isFormBlueprint || undefined,
context: this.fieldtypeContext,
});
},

methods: {
this.$axios.get(cp_url(`fields/fieldtypes?${query}`))
.then((response) => (loadedFieldtypes.value[key] = response.data))
.catch((e) => {
if (this.cacheKey !== key) return;
this.$toast.error(e.response?.data?.message || __('Something went wrong'));
this.close();
});
},

select(selection) {
if (selection.isMeta) {
return this.selectMeta(selection);
Expand Down
12 changes: 12 additions & 0 deletions resources/js/components/fields/Settings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import { FieldConditionsBuilder, FIELD_CONDITIONS_KEYS } from '../field-conditio
import FieldValidationBuilder from '../field-validation/Builder.vue';
import { Heading, Button, Tabs, TabList, TabTrigger, TabContent, CardPanel, Icon, StackHeader, StackContent } from '@/components/ui';
import shortcutLabel from '@/util/shortcutLabel.js';
import { computed } from 'vue';

export default {
emits: ['committed', 'closed'],
Expand Down Expand Up @@ -104,10 +105,12 @@ export default {
updateFieldSettingsValue: this.updateField,
getFieldSettingsValue: this.getFieldValue,
commitParentField: this.commit,
fieldtypeContext: computed(() => this.fieldtypeContext),
};
},

inject: {
parentFieldtypeContext: { from: 'fieldtypeContext', default: () => ({}) },
isInsideConfigFields: {
default: false
},
Expand Down Expand Up @@ -139,6 +142,13 @@ export default {
},

computed: {
fieldtypeContext() {
return {
...this.parentFieldtypeContext,
field_path: [...(this.parentFieldtypeContext.field_path ?? []), this.values?.handle ?? this.config.handle ?? null],
};
},

adjustedBlueprint() {
let blueprint = this.blueprint;

Expand Down Expand Up @@ -283,6 +293,7 @@ export default {
values: this.values,
fields: this.fields,
isInsideSet: this.isInsideSet,
context: this.fieldtypeContext,
})
.then((response) => {
this.$refs.container?.clearDirtyState();
Expand Down Expand Up @@ -389,6 +400,7 @@ export default {
type: this.type,
reference: field?.type === 'reference' ? field.field_reference : false,
values: this.config,
context: this.fieldtypeContext,
})
.then((response) => {
this.loading = false;
Expand Down
8 changes: 8 additions & 0 deletions resources/js/components/fieldtypes/grid/FieldsFieldtype.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,20 @@ import Fieldtype from '../Fieldtype.vue';
import Fields from '../../blueprints/Fields.vue';
import { Sortable, Plugins } from '@shopify/draggable';
import SuggestsConditionalFields from '../../blueprints/SuggestsConditionalFields';
import { computed } from 'vue';

export default {
mixins: [Fieldtype, SuggestsConditionalFields],

inject: {
suggestableConditionFieldsProvider: { default: null },
parentFieldtypeContext: { from: 'fieldtypeContext', default: () => ({}) },
},

provide() {
return {
fieldtypeContext: computed(() => ({ ...this.parentFieldtypeContext, nested: true })),
};
},

components: {
Expand Down
12 changes: 10 additions & 2 deletions resources/js/pages/fieldsets/Edit.vue
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,16 @@ export default {

props: ['action', 'initialFieldset'],

provide: {
isInsideFieldset: true,
provide() {
return {
isInsideFieldset: true,
fieldtypeContext: {
view: 'fieldset',
fieldset: this.initialFieldset.handle,
field_path: [],
nested: false,
},
};
},

data() {
Expand Down
104 changes: 104 additions & 0 deletions resources/js/tests/components/FieldtypeContext.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { flushPromises, mount } from '@vue/test-utils';
import { expect, test, vi } from 'vitest';
import { h, inject } from 'vue';
import * as Globals from '@/bootstrap/globals';
import Settings from '@/components/fields/Settings.vue';
import Section from '@/components/blueprints/Section.vue';
import GridFields from '@/components/fieldtypes/grid/FieldsFieldtype.vue';
import { publishContextKey } from '@/components/ui';

Object.assign(window, Globals);
window.__ = key => key;
window.cp_url = url => url;
window.Statamic = { $config: { get: key => key === 'sites' ? [] : undefined }, $fieldActions: { get: () => [] } };

const Probe = {
methods: {
clearDirtyState() {},
},
setup() {
const context = inject('fieldtypeContext');
return () => h('div', [h('output', { class: 'blueprint-section-draggable-zone' }, JSON.stringify(context.value ?? context))]);
},
};
const PassThrough = { template: '<div><slot /><slot name="actions" /></div>' };

test.each([
[{ view: 'blueprint', blueprint: 'runway::post', field_path: [], nested: false }, 'author'],
[{ view: 'fieldset', fieldset: 'common', field_path: [], nested: false }, null],
])('settings send and inject owner context independently of configuration values', async (context, handle) => {
const post = vi.fn((url, payload) => Promise.resolve({ data: url === 'fields/edit' ? {
fieldtype: { icon: 'text' },
blueprint: { tabs: [{ sections: [] }] },
values: payload.values,
meta: {},
} : payload.values }));
const wrapper = mount(Settings, {
props: { config: { handle, type: 'text' }, fields: [], type: 'text' },
global: {
provide: { fieldtypeContext: context },
mocks: {
$axios: { post },
$keys: { bindGlobal: () => ({ destroy() {} }) },
$config: { get: () => undefined },
},
stubs: {
StackHeader: PassThrough, StackContent: PassThrough,
Tabs: PassThrough, TabContent: PassThrough, TabList: true, Button: true,
CardPanel: true, FieldConditionsBuilder: true, FieldValidationBuilder: true,
},
components: { 'ui-publish-container': Probe },
},
});
await flushPromises();

expect(JSON.parse(wrapper.find('output').text())).toEqual({ ...context, field_path: [handle] });
expect(post.mock.calls[0][1].context).toEqual({ ...context, field_path: [handle] });
wrapper.vm.values.handle = 'renamed';
await flushPromises();
expect(JSON.parse(wrapper.find('output').text()).field_path).toEqual(['renamed']);

await wrapper.findAllComponents({ name: 'Button' })[0].trigger('click');
await flushPromises();
const payload = post.mock.calls.at(-1)[1];
expect(payload.context.field_path).toEqual(['renamed']);
expect(payload.values).not.toHaveProperty('context');
wrapper.unmount();
});

test.each([false, true])('sections add set handles only inside sets (inside set: %s)', insideSet => {
const wrapper = mount(Section, {
props: { section: { handle: 'quote', fields: [] } },
global: {
provide: {
fieldtypeContext: { blueprint: 'runway::post', field_path: ['blocks'], nested: false },
isInsideSet: insideSet,
},
mocks: { $config: { get: () => undefined } },
stubs: { Fields: Probe, 'ui-panel': PassThrough, 'ui-panel-header': true, 'ui-stack': true },
},
});
expect(JSON.parse(wrapper.find('output').text())).toEqual({
blueprint: 'runway::post',
field_path: insideSet ? ['blocks', 'quote'] : ['blocks'],
nested: insideSet,
});
wrapper.unmount();
});

test('grid field configuration marks its children nested without adding a config-field handle', () => {
const wrapper = mount(GridFields, {
props: { handle: 'fields', value: [], config: {} },
global: {
provide: {
[publishContextKey]: {},
fieldtypeContext: { blueprint: 'runway::post', field_path: ['rows'], nested: false },
},
stubs: { Fields: Probe },
},
});
expect(JSON.parse(wrapper.find('output').text())).toEqual({
blueprint: 'runway::post', field_path: ['rows'], nested: true,
});
wrapper.unmount();
});
Loading
Loading