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
6 changes: 5 additions & 1 deletion src/commands/field-add-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { GroupModel } from "@prismicio/types-internal";
import { capitalCase } from "change-case";

import { getNewFieldTarget, TARGET_OPTIONS } from "../fields";
import { createCommand, type CommandConfig } from "../lib/command";
import { CommandError, createCommand, type CommandConfig } from "../lib/command";
import { addField } from "../lib/prismic/models";

const config = {
Expand All @@ -25,6 +25,10 @@ export default createCommand(config, async ({ positionals, values }) => {
const [id] = positionals;
const { label } = values;

if (values["legacy-items-zone"]) {
throw new CommandError("Group fields cannot be added to the legacy items zone.");
}

const { fields, fieldId, save } = await getNewFieldTarget(id, values);

const field: GroupModel = {
Expand Down
5 changes: 5 additions & 0 deletions src/commands/slice-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,10 @@ export default createCommand(config, async ({ positionals, values }) => {
console.info("");
console.info(`${variation.id}:`);
console.info(formatFieldTable(variation.primary ?? {}));
if (variation.items && Object.keys(variation.items).length > 0) {
console.info("");
console.info(`${variation.id} (legacy items zone):`);
console.info(formatFieldTable(variation.items));
}
}
});
49 changes: 42 additions & 7 deletions src/fields.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { DynamicWidgetModel } from "@prismicio/types-internal";
import type { DynamicWidgetModel, SharedSliceModel } from "@prismicio/types-internal";

import { getAdapter } from "./adapters";
import { CommandError, exactlyOneOption, type CommandConfig } from "./lib/command";
import type { ContentRelationshipFieldSelection } from "./lib/prismic/models";
import {
FieldExistsError,
FieldNotFoundError,
SliceItemsNotFoundError,
resolveCustomTypeFieldContainer,
resolveContentRelationshipFieldSelection,
resolveSliceFieldContainer,
Expand All @@ -26,6 +27,12 @@ export const TARGET_OPTIONS = {
description: 'Slice variation ID (default: "default")',
dependsOn: "to-slice",
},
"legacy-items-zone": {
type: "boolean",
description:
"Edit the legacy repeatable zone of a slice upgraded from the Legacy Builder. New slices use a repeatable group instead.",
dependsOn: "to-slice",
},
tab: {
type: "string",
description: 'Content type tab name (default: "Main")',
Expand All @@ -47,6 +54,12 @@ export const SOURCE_OPTIONS = {
description: 'Slice variation ID (default: "default")',
dependsOn: "from-slice",
},
"legacy-items-zone": {
type: "boolean",
description:
"Edit the legacy repeatable zone of a slice upgraded from the Legacy Builder. New slices use a repeatable group instead.",
dependsOn: "from-slice",
},
} satisfies CommandConfig["options"];

type ResolvedFieldTarget = {
Expand All @@ -64,13 +77,14 @@ export async function getFieldReorderTargets(
"from-slice"?: string;
"from-type"?: string;
variation?: string;
"legacy-items-zone"?: boolean;
},
): Promise<{
source: ResolvedFieldContainer;
anchor: ResolvedFieldContainer;
save: () => Promise<void>;
}> {
const { variation = "default" } = values;
const { variation = "default", "legacy-items-zone": items } = values;
const { key, value } = exactlyOneOption(values, ["from-slice", "from-type"]);
const adapter = await getAdapter();

Expand All @@ -79,8 +93,8 @@ export async function getFieldReorderTargets(
let save: () => Promise<void>;
if (key === "from-slice") {
const { model } = await adapter.getSlice(value);
source = resolveSliceFieldContainer(sourcePath, model, variation);
anchor = resolveSliceFieldContainer(anchorPath, model, variation);
source = resolveSliceFields(sourcePath, model, variation, items);
anchor = resolveSliceFields(anchorPath, model, variation, items);
save = async () => {
await adapter.updateSlice(model);
await adapter.generateTypes();
Expand All @@ -107,14 +121,15 @@ export async function getNewFieldTarget(
"to-slice"?: string;
"to-type"?: string;
variation?: string;
"legacy-items-zone"?: boolean;
tab?: string;
},
): Promise<ResolvedFieldTarget> {
const { tab = "Main", variation = "default" } = values;
const { key, value } = exactlyOneOption(values, ["to-slice", "to-type"]);
const target =
key === "to-slice"
? await getSliceFieldTarget(path, value, variation)
? await getSliceFieldTarget(path, value, variation, values["legacy-items-zone"])
: await getCustomTypeFieldTarget(path, value, tab);
if (target.fieldId in target.fields) throw new FieldExistsError(path);
return target;
Expand All @@ -126,13 +141,14 @@ export async function getExistingField(
"from-slice"?: string;
"from-type"?: string;
variation?: string;
"legacy-items-zone"?: boolean;
},
): Promise<ResolvedFieldTarget & { field: DynamicWidgetModel }> {
const { variation = "default" } = values;
const { key, value } = exactlyOneOption(values, ["from-slice", "from-type"]);
const target =
key === "from-slice"
? await getSliceFieldTarget(path, value, variation)
? await getSliceFieldTarget(path, value, variation, values["legacy-items-zone"])
: await getCustomTypeFieldTarget(path, value);
const field = target.fields[target.fieldId];
if (!field) throw new FieldNotFoundError(path);
Expand All @@ -157,10 +173,11 @@ async function getSliceFieldTarget(
path: string,
sliceId: string,
variationId: string,
items?: boolean,
): Promise<ResolvedFieldTarget> {
const adapter = await getAdapter();
const { model } = await adapter.getSlice(sliceId);
const fieldContainer = resolveSliceFieldContainer(path, model, variationId);
const fieldContainer = resolveSliceFields(path, model, variationId, items);

return {
...fieldContainer,
Expand All @@ -171,6 +188,24 @@ async function getSliceFieldTarget(
};
}

function resolveSliceFields(
path: string,
slice: SharedSliceModel,
variationId: string,
items?: boolean,
): ResolvedFieldContainer {
try {
return resolveSliceFieldContainer(path, slice, variationId, items);
} catch (error) {
if (!(error instanceof SliceItemsNotFoundError)) throw error;
let target = `--to-slice ${slice.id}`;
if (variationId !== "default") target += ` --variation ${variationId}`;
throw new CommandError(
`${error.message}\nHint: prismic field add group items ${target}\nThen add fields to the group: prismic field add text items.<field_id> ${target}`,
);
}
}

async function getCustomTypeFieldTarget(
path: string,
customTypeId: string,
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
FieldExistsError,
FieldNotFoundError,
FieldSelectionError,
SliceItemsNotFoundError,
SliceVariationNotFoundError,
TabNotFoundError,
UnsupportedNestedFieldError,
Expand Down Expand Up @@ -71,6 +72,7 @@ const KNOWN_ERRORS = [
FieldSelectionError,
TabNotFoundError,
SliceVariationNotFoundError,
SliceItemsNotFoundError,
UnsupportedFileTypeError,
NoSupportedFrameworkError,
ModelExistsError,
Expand Down
17 changes: 17 additions & 0 deletions src/lib/prismic/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,16 @@ export function resolveSliceFieldContainer(
path: string,
slice: SharedSliceModel,
variationId: string,
items = false,
): { fields: Fields; fieldId: string } {
const variation = slice.variations.find((variation) => variation.id === variationId);
if (!variation) throw new SliceVariationNotFoundError(variationId, slice.id);
if (items) {
if (!variation.items || Object.keys(variation.items).length === 0) {
throw new SliceItemsNotFoundError(variationId, slice.id);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Removing the last items field locks the zone, and the error points users to primary

This throws as soon as items is empty. field edit can't change a field's type, so changing the type of the only items field means remove, then add:

$ prismic field remove image --from-slice hero --legacy-items-zone
Field removed: image
$ prismic field add link image --to-slice hero --legacy-items-zone
Variation "default" of slice "hero" has no legacy items zone. Add fields to the slice instead.

An agent that follows this message adds the field to primary. That turns a per-item field into a per-slice field, and existing item content no longer maps to it. The Type Builder keeps the empty list for the current mount for exactly this case. The CLI keeps no state between commands, so it can't do the same.

Hiding an empty zone is the right rule. upgrade-legacy writes items: {} on every variation, so checking whether the key exists would not work.

Suggestion: Make the dead end visible before users hit it.

  1. In field remove, when the removed field was the last one in the items zone, print a warning that the zone can no longer be edited, and that replacement fields must be added before the last one is removed.
  2. Reword the error so it doesn't send people to primary without context, e.g. "…has no legacy items zone. To add repeatable fields, add a repeatable group to the slice." That wording also keeps CLI flag names out of src/lib.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reply from Claude, working with Angelo on this PR.

Thanks! The empty-zone-is-no-zone behaviour is kept on purpose: once the last items field is removed, the legacy zone is retired, and new repeatable content belongs in a repeatable group.

The error is updated in 40b424c and 6c5d6c3. SliceItemsNotFoundError in src/lib now only says the variation has no legacy items zone and that repeatable fields go in a repeatable group, with no CLI syntax. The CLI hint is added one layer up in src/fields.ts, in one small wrapper around resolveSliceFieldContainer that all field commands use (add, edit, remove, reorder):

Variation "default" of slice "hero" has no legacy items zone. To add repeatable fields, add a repeatable group to the slice.
Hint: prismic field add group items --to-slice hero
Then add fields to the group: prismic field add text items.<field_id> --to-slice hero

Generated by Claude Code

}
return resolveNestedFieldContainer(path, variation.items);
}
variation.primary ??= {};
return resolveNestedFieldContainer(path, variation.primary);
}
Expand Down Expand Up @@ -378,3 +385,13 @@ export class SliceVariationNotFoundError extends Error {
super(`Variation "${id}" does not exist on slice "${sliceId}".`);
}
}

export class SliceItemsNotFoundError extends Error {
name = "SliceItemsNotFoundError";

constructor(variationId: string, sliceId: string) {
super(
`Variation "${variationId}" of slice "${sliceId}" has no legacy items zone. To add repeatable fields, add a repeatable group to the slice.`,
);
}
}
17 changes: 17 additions & 0 deletions test/field-add-group.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,20 @@ it("errors when dot syntax targets a field that does not support nesting", async
expect(exitCode).toBe(1);
expect(stderr).toContain('Field "my_text" does not support nested fields.');
});

it("errors for the legacy items zone", async ({ expect, prismic, project }) => {
const slice = buildSlice();
slice.variations[0].items = { label: { type: "Text", config: { label: "Label" } } };
await writeLocalSlice(project, slice);

const { stderr, exitCode } = await prismic("field", [
"add",
"group",
"my_group",
"--to-slice",
slice.id,
"--legacy-items-zone",
]);
expect(exitCode).toBe(1);
expect(stderr).toContain("Group fields cannot be added to the legacy items zone.");
});
40 changes: 40 additions & 0 deletions test/field-add-text.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,43 @@ it("errors for an unknown slice", async ({ expect, prismic }) => {
expect(exitCode).toBe(1);
expect(stderr).toContain('Slice "CallToAction" does not exist.');
});

it("adds a text field to a slice's legacy items zone", async ({ expect, prismic, project }) => {
const slice = buildSlice();
slice.variations[0].items = { label: { type: "Text", config: { label: "Label" } } };
await writeLocalSlice(project, slice);

const { stderr, exitCode } = await prismic("field", [
"add",
"text",
"subtitle",
"--to-slice",
slice.id,
"--legacy-items-zone",
]);
expect(exitCode, stderr).toBe(0);

const updated = await readLocalSlice(project, slice.id);
expect(updated!.variations[0].items!.subtitle).toMatchObject({ type: "Text" });
expect(updated!.variations[0].primary).toEqual({});
});

it("errors when the variation has no legacy items zone", async ({ expect, prismic, project }) => {
const slice = buildSlice();
await writeLocalSlice(project, slice);

const { stderr, exitCode } = await prismic("field", [
"add",
"text",
"subtitle",
"--to-slice",
slice.id,
"--legacy-items-zone",
]);
expect(exitCode).toBe(1);
expect(stderr).toContain(
`Variation "default" of slice "${slice.id}" has no legacy items zone. To add repeatable fields, add a repeatable group to the slice.`,
);
expect(stderr).toContain(`Hint: prismic field add group items --to-slice ${slice.id}`);
expect(stderr).toContain(`prismic field add text items.<field_id> --to-slice ${slice.id}`);
});
20 changes: 20 additions & 0 deletions test/field-edit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,3 +337,23 @@ it("edits link field options", async ({ expect, prismic, project }) => {
config: { allowTargetBlank: true },
});
});

it("edits a field in a slice's legacy items zone", async ({ expect, prismic, project }) => {
const slice = buildSlice();
slice.variations[0].items = { label: { type: "Text", config: { label: "Old Label" } } };
await writeLocalSlice(project, slice);

const { stderr, exitCode } = await prismic("field", [
"edit",
"label",
"--from-slice",
slice.id,
"--legacy-items-zone",
"--label",
"New Label",
]);
expect(exitCode, stderr).toBe(0);

const updated = await readLocalSlice(project, slice.id);
expect(updated!.variations[0].items!.label).toMatchObject({ config: { label: "New Label" } });
});
18 changes: 18 additions & 0 deletions test/field-remove.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,21 @@ it("removes a nested field using dot notation", async ({ expect, prismic, projec
expect(group.config?.fields).toMatchObject({});
expect(group.config?.fields?.subtitle).toBeUndefined();
});

it("removes a field from a slice's legacy items zone", async ({ expect, prismic, project }) => {
const slice = buildSlice();
slice.variations[0].items = { label: { type: "Text", config: { label: "Label" } } };
await writeLocalSlice(project, slice);

const { stderr, exitCode } = await prismic("field", [
"remove",
"label",
"--from-slice",
slice.id,
"--legacy-items-zone",
]);
expect(exitCode, stderr).toBe(0);

const updated = await readLocalSlice(project, slice.id);
expect(updated!.variations[0].items).toEqual({});
});
23 changes: 23 additions & 0 deletions test/field-reorder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,26 @@ it("errors when the field does not exist", async ({ expect, prismic, project })
expect(exitCode).toBe(1);
expect(stderr).toContain('"missing"');
});

it("reorders a field in a slice's legacy items zone", async ({ expect, prismic, project }) => {
const slice = buildSlice();
slice.variations[0].items = {
field_a: { type: "Boolean", config: { label: "A" } },
field_b: { type: "Boolean", config: { label: "B" } },
};
await writeLocalSlice(project, slice);

const { stderr, exitCode } = await prismic("field", [
"reorder",
"field_a",
"--after",
"field_b",
"--from-slice",
slice.id,
"--legacy-items-zone",
]);
expect(exitCode, stderr).toBe(0);

const updated = await readLocalSlice(project, slice.id);
expect(Object.keys(updated!.variations[0].items!)).toEqual(["field_b", "field_a"]);
});
10 changes: 10 additions & 0 deletions test/slice-view.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,13 @@ it("points at the upgrade for a legacy slice", async ({ expect, prismic, project
`"hero" is a legacy slice in "${customType.id}". Upgrade it first: \`prismic slice upgrade-legacy hero --from ${customType.id}\`.`,
);
});

it("shows a variation's legacy items zone fields", async ({ expect, prismic, project }) => {
const slice = buildSlice();
slice.variations[0].items = { label: { type: "Text", config: { label: "Label" } } };
await writeLocalSlice(project, slice);

const { stdout, stderr, exitCode } = await prismic("slice", ["view", slice.id]);
expect(exitCode, stderr).toBe(0);
expect(stdout).toMatch(/default \(legacy items zone\):\n\s+label\s+Text\s+Label/);
});
Loading