Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

42.4 KB
Raw Blame
import equal from "fast-deep-equal";
import {
  blockTemplateComponent,
  blockBodyComponent,
  blockComponent,
  getContentBlockSource,
  findContentBlockBodyContainers,
  assignUniqueBlockTemplateNamesMutable,
  elementComponent,
  instanceComponent,
  ROOT_INSTANCE_ID,
  type Breakpoints,
  type DataSource,
  type DataSources,
  type Instance,
  type Instances,
  type Page,
  type PageTemplate,
  type Pages,
  type Props,
  type Resources,
  type Styles,
  type StyleSources,
  type StyleSourceSelections,
  type WebstudioData,
  type WebstudioFragment,
} from "@webstudio-is/sdk";
import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
import {
  compactBuilderPatchPayload,
  type BuilderPatch,
  type BuilderPatchChange,
} from "../contracts/patch";
import type { BuilderState } from "../state/builder-state";
import { getComponentTemplates } from "./component-templates";
import {
  createComponentTemplateFragment,
  type ComponentTemplateRegistry,
} from "./component-template";
import { isComponentAvailableForDocumentType } from "./component-catalog";
import type {
  ComponentInsertResult,
  FragmentInsertResult,
} from "./component-insert-contract";
import {
  createCollectionFragment,
  conflictResolutionInput,
  insertCollectionInput,
  type InsertCollectionResult,
} from "./collection";
import type { BuilderRuntimeContext } from "./context";
import { isFragmentContentModeCopyableProp } from "./content-mode-copy-policy";
import { isContentModeTemplateDefaultPropType } from "./content-mode-permissions";
import { findAvailableVariables } from "./data";
import { addZodValidationIssue, throwBuilderRuntimeError } from "./errors";
import {
  detectFragmentTokenConflicts,
  extractWebstudioFragment,
  insertWebstudioFragmentCopy,
  webstudioFragmentMutationInput,
} from "./fragment";
import {
  blockTemplateNameConfirmationInput,
  createInstanceAppendPayload,
  createInstanceChild,
  insertIndexInput,
  instanceInsertModeInput,
  requireBlockTemplateNameConfirmation,
} from "./instances";
import { createRuntimeMutation, type BuilderRuntimeMutation } from "./mutation";
import { getSlotFragmentDropTargetMutable } from "./slot";
import type { ConflictResolution } from "./style-copy";
import { findPageAndSelectorByInstanceId } from "./lookup";
import { validateFragmentHtmlEmbedCode } from "./html-embed";
import {
  getFragmentPlacementContentModelWarnings,
  getNewFragmentContentModelWarnings,
} from "./matcher";
import { z } from "zod";
import { getBlockTemplateNameConfirmation } from "./block";
import { hasMdxComponentAdapter } from "./mdx-component-adapters";
import { wrapEditableChildrenAroundInsertIndexMutable } from "./tree";

export const insertComponentInput = z.object({
  parentInstanceId: z.string(),
  component: instanceComponent.describe(
    'Exact component id returned by components.search, components.get, or templates.get. Do not derive HTML shorthands such as "ws:div" or "ws:form". For a native HTML element, use "ws:element" and set "tag".'
  ),
  tag: z
    .string()
    .min(1)
    .optional()
    .describe('Required when component is "ws:element"; omit otherwise.'),
  mode: instanceInsertModeInput.optional(),
  insertIndex: insertIndexInput.optional(),
  templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),
});

export const insertFragmentInput = z
  .object({
    parentInstanceId: z.string().optional(),
    fragment: webstudioFragmentMutationInput.describe(
      "Structured Webstudio fragment produced by Webstudio JSX/template helpers. Runtime remaps fragment ids to generated project ids."
    ),
    conflictResolution: conflictResolutionInput.optional(),
    contentMode: z
      .boolean()
      .optional()
      .describe(
        "Apply content-mode copy restrictions to props and styles while reusing existing tokens and breakpoints."
      ),
    mode: instanceInsertModeInput.optional(),
    insertIndex: insertIndexInput.optional(),
    templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),
  })
  .superRefine((input, context) => {
    if (
      input.fragment.children.length > 0 &&
      input.parentInstanceId === undefined
    ) {
      addZodValidationIssue(context, {
        code: "missing_fragment_parent",
        path: ["parentInstanceId"],
        message: "Required when inserting a fragment with children",
        constraint: "required_when:fragment.children.length>0",
        example: "parent-instance-id",
      });
    }
  });

export const componentInsertNamespaces = [
  "instances",
  "props",
  "dataSources",
  "resources",
  "styleSources",
  "styleSourceSelections",
  "styles",
  "breakpoints",
  "assets",
] as const;

export const componentInsertReadNamespaces = [
  "pages",
  ...componentInsertNamespaces,
] as const;

const canContainDescendant = (
  ancestorComponent: Instance["component"],
  descendantComponent: Instance["component"],
  visited = new Set<Instance["component"]>()
): boolean => {
  if (visited.has(ancestorComponent)) {
    return false;
  }
  visited.add(ancestorComponent);
  const contentModel = componentMetas.get(ancestorComponent)?.contentModel;
  const directOrNested = [
    ...(contentModel?.children ?? []),
    ...(contentModel?.descendants ?? []),
  ];
  if (directOrNested.includes(descendantComponent)) {
    return true;
  }
  return directOrNested.some(
    (descendant) =>
      typeof descendant === "string" &&
      componentMetas.has(descendant) &&
      canContainDescendant(descendant, descendantComponent, visited)
  );
};

const getComponentPartInsertError = ({
  component,
  ancestors,
}: {
  component: Instance["component"];
  ancestors: readonly Instance[];
}) => {
  const [parent] = ancestors;
  const allowedChildren =
    parent === undefined
      ? []
      : (componentMetas.get(parent.component)?.contentModel?.children ?? []);
  const allowedByAncestor = ancestors.some((ancestor) => {
    const descendants =
      componentMetas.get(ancestor.component)?.contentModel?.descendants ?? [];
    return descendants.includes(component) || descendants.includes("none");
  });
  if (
    allowedChildren.includes(component) ||
    allowedChildren.includes("none") ||
    allowedByAncestor
  ) {
    return;
  }
  const suggestions = Array.from(componentMetas.entries())
    .filter(([candidateComponent, candidateMeta]) => {
      if (candidateMeta.contentModel?.category === "none") {
        return false;
      }
      return canContainDescendant(candidateComponent, component);
    })
    .map(([candidateComponent]) => candidateComponent);
  const suggestion =
    suggestions.length === 0
      ? "Insert the nearest root component template that contains this component."
      : `Insert one of these template/root components instead: ${suggestions
          .map((suggestion) => `"${suggestion}"`)
          .join(", ")}.`;
  return `Component "${component}" cannot be inserted standalone because its contentModel.category is "none". ${suggestion} Required provider/parent components must be created by the template.`;
};

const getUnknownCoreComponentError = ({
  component,
  templates,
}: {
  component: Instance["component"];
  templates: ComponentTemplateRegistry;
}) => {
  if (
    component.startsWith("ws:") &&
    componentMetas.has(component) === false &&
    templates.has(component) === false
  ) {
    return `Component "${component}" does not exist. The "ws:" namespace contains Webstudio core components, not HTML tag shorthands. In structured instance data, create a native HTML element with component "ws:element" and its "tag" property.`;
  }
};

type ComponentInsertState = Pick<
  BuilderState,
  (typeof componentInsertReadNamespaces)[number]
>;

const getRequiredComponentInsertState = (state: ComponentInsertState) => {
  for (const namespace of componentInsertNamespaces) {
    if (state[namespace] === undefined) {
      return throwBuilderRuntimeError(
        "BAD_REQUEST",
        `${namespace} namespace is missing`
      );
    }
  }
  return state as {
    pages: Pages;
    instances: Instances;
    props: Props;
    dataSources: DataSources;
    resources: Resources;
    styleSources: StyleSources;
    styleSourceSelections: StyleSourceSelections;
    styles: Styles;
    breakpoints: Breakpoints;
    assets: WebstudioData["assets"];
  };
};

export const getRequiredComponentInsertData = (
  state: ComponentInsertState
): Omit<WebstudioData, "pages"> => {
  const required = getRequiredComponentInsertState(state);
  return {
    instances: required.instances,
    props: required.props,
    dataSources: required.dataSources,
    resources: required.resources,
    styleSources: required.styleSources,
    styleSourceSelections: required.styleSourceSelections,
    styles: required.styles,
    breakpoints: required.breakpoints,
    assets: required.assets,
  };
};

const isBlockTemplateFragment = ({
  data,
  fragment,
}: {
  data: Omit<WebstudioData, "pages">;
  fragment: WebstudioFragment;
}) =>
  Array.from(data.instances.values()).some(
    (instance) =>
      instance.component === blockTemplateComponent &&
      instance.children.some(
        (child) =>
          child.type === "id" &&
          equal(extractWebstudioFragment(data, child.value), fragment)
      )
  );

const cloneFragmentData = (
  state: ReturnType<typeof getRequiredComponentInsertState>
): Omit<WebstudioData, "pages"> => {
  const data = getRequiredComponentInsertData(state);
  return {
    instances: cloneMap(data.instances),
    props: cloneMap(data.props),
    dataSources: cloneMap(data.dataSources),
    resources: cloneMap(data.resources),
    styleSources: cloneMap(data.styleSources),
    styleSourceSelections: cloneMap(data.styleSourceSelections),
    styles: cloneMap(data.styles),
    breakpoints: cloneMap(data.breakpoints),
    assets: cloneMap(data.assets),
  };
};

const cloneMap = <Key, Value>(map: Map<Key, Value>) =>
  new Map(
    Array.from(map, ([key, value]) => [key, structuredClone(value)] as const)
  );

const getPageByInstanceId = (
  pages: Pages,
  instances: Instances,
  instanceId: Instance["id"]
): Page | PageTemplate | undefined => {
  const parentByChildId = new Map<Instance["id"], Instance["id"]>();
  for (const instance of instances.values()) {
    for (const child of instance.children ?? []) {
      if (child.type === "id") {
        parentByChildId.set(child.value, instance.id);
      }
    }
  }
  const rootInstanceIds = new Map<Instance["id"], Page | PageTemplate>();
  for (const page of pages.pages.values()) {
    rootInstanceIds.set(page.rootInstanceId, page);
  }
  for (const template of pages.pageTemplates?.values() ?? []) {
    rootInstanceIds.set(template.rootInstanceId, template);
  }
  const visited = new Set<Instance["id"]>();
  let currentId: Instance["id"] | undefined = instanceId;
  while (currentId !== undefined && visited.has(currentId) === false) {
    visited.add(currentId);
    const page = rootInstanceIds.get(currentId);
    if (page !== undefined) {
      return page;
    }
    currentId = parentByChildId.get(currentId);
  }
};

const getInsertionPage = (
  mutationState: ReturnType<typeof getRequiredComponentInsertState>,
  parent: Instance
) => {
  const page = getPageByInstanceId(
    mutationState.pages,
    mutationState.instances,
    parent.id
  );
  if (page === undefined) {
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      "Cannot insert component because the target page could not be determined."
    );
  }
  return page;
};

const createRecordAddPatches = <Value>({
  namespace,
  before,
  after,
  skip = new Set(),
}: {
  namespace: (typeof componentInsertNamespaces)[number];
  before: Map<string, Value>;
  after: Map<string, Value>;
  skip?: Set<string>;
}): BuilderPatch[] => {
  const patches: BuilderPatch[] = [];
  for (const [id, value] of after) {
    if (skip.has(id)) {
      continue;
    }
    const previous = before.get(id);
    if (previous !== undefined) {
      if (equal(previous, value) === false) {
        return throwBuilderRuntimeError(
          "CONFLICT",
          `Generated record ID already exists in ${namespace}.`,
          {
            issues: [
              {
                code: "generated_id_conflict",
                path: [],
                message: `Generated record ID conflicts with an existing ${namespace} record.`,
                constraint: `unique_generated_id:${namespace}`,
                detail: "stage:fragment-record-insertion",
              },
            ],
          }
        );
      }
      continue;
    }
    patches.push({ op: "add", path: [id], value });
  }
  return patches;
};

const createRecordUpsertPatches = <Value>({
  before,
  after,
}: {
  before: Map<string, Value>;
  after: Map<string, Value>;
}): BuilderPatch[] => {
  const patches: BuilderPatch[] = [];
  for (const [id, value] of after) {
    const previous = before.get(id);
    if (previous === undefined) {
      patches.push({ op: "add", path: [id], value });
      continue;
    }
    if (equal(previous, value) === false) {
      patches.push({ op: "replace", path: [id], value });
    }
  }
  return patches;
};

const createFragmentPayload = ({
  before,
  after,
  instancePatches,
}: {
  before: ReturnType<typeof getRequiredComponentInsertState>;
  after: Omit<WebstudioData, "pages">;
  instancePatches: BuilderPatch[];
}): BuilderPatchChange[] =>
  compactBuilderPatchPayload([
    {
      namespace: "assets",
      patches: createRecordAddPatches({
        namespace: "assets",
        before: before.assets,
        after: after.assets,
      }),
    },
    {
      namespace: "breakpoints",
      patches: createRecordAddPatches({
        namespace: "breakpoints",
        before: before.breakpoints,
        after: after.breakpoints,
      }),
    },
    {
      namespace: "dataSources",
      patches: createRecordAddPatches({
        namespace: "dataSources",
        before: before.dataSources,
        after: after.dataSources,
      }),
    },
    {
      namespace: "resources",
      patches: createRecordAddPatches({
        namespace: "resources",
        before: before.resources,
        after: after.resources,
      }),
    },
    {
      namespace: "styleSources",
      patches: createRecordAddPatches({
        namespace: "styleSources",
        before: before.styleSources,
        after: after.styleSources,
      }),
    },
    {
      namespace: "styleSourceSelections",
      patches: createRecordAddPatches({
        namespace: "styleSourceSelections",
        before: before.styleSourceSelections,
        after: after.styleSourceSelections,
      }),
    },
    {
      namespace: "styles",
      patches: createRecordUpsertPatches({
        before: before.styles,
        after: after.styles,
      }),
    },
    {
      namespace: "instances",
      patches: instancePatches,
    },
    {
      namespace: "props",
      patches: createRecordAddPatches({
        namespace: "props",
        before: before.props,
        after: after.props,
      }),
    },
  ]);

const createFragmentInsertPayload = ({
  before,
  after,
  parent,
  insertIndex,
  insertedChildren,
}: {
  before: ReturnType<typeof getRequiredComponentInsertState>;
  after: Omit<WebstudioData, "pages">;
  parent: Instance;
  insertIndex: number;
  insertedChildren: Instance["children"];
}): BuilderPatchChange[] => {
  const shouldSetChildrenArray =
    (parent.children ?? []).length === 0 && insertIndex === 0;
  return createFragmentPayload({
    before,
    after,
    instancePatches: [
      ...createRecordAddPatches({
        namespace: "instances",
        before: before.instances,
        after: after.instances,
        skip: new Set([parent.id]),
      }),
      ...(equal(after.instances.get(parent.id)?.children, parent.children)
        ? []
        : [
            {
              op: "replace" as const,
              path: [parent.id, "children"],
              value: after.instances.get(parent.id)?.children,
            },
          ]),
      ...(shouldSetChildrenArray
        ? [
            {
              op: "add" as const,
              path: [parent.id, "children"],
              value: insertedChildren,
            },
          ]
        : insertedChildren.map((child, index) => ({
            op: "add" as const,
            path: [parent.id, "children", insertIndex + index],
            value: child,
          }))),
    ],
  });
};

const createTokenFragmentInsertPayload = ({
  before,
  after,
}: {
  before: ReturnType<typeof getRequiredComponentInsertState>;
  after: Omit<WebstudioData, "pages">;
}): BuilderPatchChange[] =>
  compactBuilderPatchPayload([
    {
      namespace: "assets",
      patches: createRecordAddPatches({
        namespace: "assets",
        before: before.assets,
        after: after.assets,
      }),
    },
    {
      namespace: "breakpoints",
      patches: createRecordAddPatches({
        namespace: "breakpoints",
        before: before.breakpoints,
        after: after.breakpoints,
      }),
    },
    {
      namespace: "styleSources",
      patches: createRecordAddPatches({
        namespace: "styleSources",
        before: before.styleSources,
        after: after.styleSources,
      }),
    },
    {
      namespace: "styles",
      patches: createRecordUpsertPatches({
        before: before.styles,
        after: after.styles,
      }),
    },
  ]);

const validateFragmentComponent = ({
  instance,
  templates,
  page,
}: {
  instance: Instance;
  templates: ComponentTemplateRegistry;
  page: Page | PageTemplate;
}) => {
  const { component } = instance;
  const meta = componentMetas.get(component);
  const unknownCoreComponentError = getUnknownCoreComponentError({
    component,
    templates,
  });
  if (unknownCoreComponentError !== undefined) {
    return throwBuilderRuntimeError("BAD_REQUEST", unknownCoreComponentError);
  }
  if (
    component === "ws:element" &&
    (typeof instance.tag !== "string" || instance.tag.length === 0)
  ) {
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      'Component "ws:element" requires a non-empty tag. In JSX, use a lowercase HTML element such as <section>...</section>; in structured instance data, set component "ws:element" and tag "section".'
    );
  }
  const insertCategory = templates.get(component)?.category ?? meta?.category;
  if (
    isComponentAvailableForDocumentType({
      component,
      category: insertCategory,
      documentType: page.meta.documentType ?? "html",
    }) === false
  ) {
    if (insertCategory === "xml") {
      return throwBuilderRuntimeError(
        "BAD_REQUEST",
        `XML component "${component}" can only be inserted on pages with document type "xml". Change the page document type in page settings before inserting XML components.`
      );
    }
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      `Component "${component}" is not available for pages with document type "${page.meta.documentType ?? "html"}". Change the page document type in page settings or choose an available component.`
    );
  }
  if (meta === undefined && insertCategory === undefined) {
    return;
  }
};

const getSubtreeComponents = (
  root: Instance,
  instancesById: ReadonlyMap<Instance["id"], Instance>
) => {
  const components = new Set<Instance["component"]>();
  const visit = (instance: Instance) => {
    components.add(instance.component);
    for (const child of instance.children) {
      if (child.type !== "id") {
        continue;
      }
      const childInstance = instancesById.get(child.value);
      if (childInstance !== undefined) {
        visit(childInstance);
      }
    }
  };
  visit(root);
  return components;
};

const createComponentEdge = (
  parentComponent: Instance["component"],
  childComponent: Instance["component"]
) => `${parentComponent}\0${childComponent}`;

export const parseComponentEdge = (edge: string) => {
  const [parentComponent, childComponent] = edge.split("\0");
  return { parentComponent, childComponent };
};

const getSubtreeComponentEdges = (
  root: Instance,
  instancesById: ReadonlyMap<Instance["id"], Instance>
) => {
  const edges = new Set<string>();
  const visit = (instance: Instance) => {
    for (const child of instance.children) {
      if (child.type !== "id") {
        continue;
      }
      const childInstance = instancesById.get(child.value);
      if (childInstance === undefined) {
        continue;
      }
      edges.add(
        createComponentEdge(instance.component, childInstance.component)
      );
      visit(childInstance);
    }
  };
  visit(root);
  return edges;
};

export const getTemplateRequiredStructure = (
  component: Instance["component"],
  templates: ComponentTemplateRegistry
) => {
  const template = templates.get(component)?.template;
  if (template === undefined) {
    return { parts: [], edges: [] };
  }
  const templateInstancesById = new Map(
    template.instances.map((instance) => [instance.id, instance])
  );
  const requiredParts = new Set<Instance["component"]>();
  const requiredEdges = new Set<string>();
  for (const child of template.children) {
    if (child.type !== "id") {
      continue;
    }
    const rootInstance = templateInstancesById.get(child.value);
    if (rootInstance?.component !== component) {
      continue;
    }
    for (const edge of getSubtreeComponentEdges(
      rootInstance,
      templateInstancesById
    )) {
      const [, childComponent] = edge.split("\0");
      if (
        componentMetas.get(childComponent)?.contentModel?.category === "none"
      ) {
        requiredEdges.add(edge);
      }
    }
    for (const subtreeComponent of getSubtreeComponents(
      rootInstance,
      templateInstancesById
    )) {
      if (subtreeComponent === component) {
        continue;
      }
      if (
        componentMetas.get(subtreeComponent)?.contentModel?.category === "none"
      ) {
        requiredParts.add(subtreeComponent);
      }
    }
  }
  return {
    parts: Array.from(requiredParts),
    edges: Array.from(requiredEdges),
  };
};

const createInsertFragmentMutation = <
  Details extends Record<string, unknown> = Record<string, never>,
>({
  state,
  parentInstanceId,
  fragment,
  templates,
  mode = "append",
  insertIndex: explicitInsertIndex,
  conflictResolution,
  contentMode = false,
  additionalAvailableVariables = [],
  getResultDetails,
  validateContentModel = true,
  confirm,
  context,
}: {
  state: ComponentInsertState;
  parentInstanceId: Instance["id"];
  fragment: WebstudioFragment;
  templates: ComponentTemplateRegistry;
  mode?: z.infer<typeof instanceInsertModeInput>;
  insertIndex?: z.infer<typeof insertIndexInput>;
  conflictResolution?: ConflictResolution;
  contentMode?: boolean;
  additionalAvailableVariables?: DataSource[];
  getResultDetails?: (ids: {
    newInstanceIds: Map<string, string>;
    newDataSourceIds: Map<string, string>;
  }) => Details;
  validateContentModel?: boolean;
  confirm?: z.infer<typeof blockTemplateNameConfirmationInput>;
  context: BuilderRuntimeContext;
}) => {
  const mutationState = getRequiredComponentInsertState(state);
  const originalParent = mutationState.instances.get(parentInstanceId);
  if (originalParent === undefined) {
    return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
  }

  const page = getInsertionPage(mutationState, originalParent);
  for (const instance of fragment.instances) {
    validateFragmentComponent({
      instance,
      templates,
      page,
    });
  }

  const nextData = cloneFragmentData(mutationState);
  const copiesContentBlockTemplate =
    contentMode &&
    isBlockTemplateFragment({
      data: mutationState,
      fragment,
    });
  const normalizedSlotDropTarget = getSlotFragmentDropTargetMutable(
    nextData.instances,
    { parentSelector: [originalParent.id], position: "end" },
    context.createId
  );
  const parent =
    normalizedSlotDropTarget === undefined
      ? originalParent
      : nextData.instances.get(normalizedSlotDropTarget.parentSelector[0]);
  if (parent === undefined) {
    return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
  }
  const parentChildren = parent.children ?? [];
  const insertIndex =
    mode === "replace"
      ? (explicitInsertIndex ?? 0)
      : mode === "prepend"
        ? 0
        : (explicitInsertIndex ?? parentChildren.length);
  if (insertIndex > parentChildren.length) {
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      "Insert index is outside parent children"
    );
  }
  if (
    mode === "replace" &&
    explicitInsertIndex !== undefined &&
    insertIndex === parentChildren.length
  ) {
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      "Replace index is outside parent children"
    );
  }
  const replacedChildren =
    mode === "replace" && explicitInsertIndex !== undefined
      ? parentChildren.slice(insertIndex, insertIndex + 1)
      : parentChildren;

  const { newInstanceIds, newDataSourceIds, didMergeBreakpointsDueToLimit } =
    insertWebstudioFragmentCopy({
      data: nextData,
      fragment,
      availableVariables: [
        ...findAvailableVariables({
          startingInstanceId: originalParent.id,
          instances: mutationState.instances,
          dataSources: mutationState.dataSources,
        }),
        ...additionalAvailableVariables,
      ],
      projectId: context.projectId ?? "",
      conflictResolution,
      createId: context.createId,
      metas: componentMetas,
      contentModeCopyableProp: (input) =>
        isFragmentContentModeCopyableProp(input) ||
        (copiesContentBlockTemplate &&
          isContentModeTemplateDefaultPropType(input.prop.type)),
      contentMode,
    });
  for (const instanceId of newInstanceIds.values()) {
    if (
      instanceId !== ROOT_INSTANCE_ID &&
      mutationState.instances.has(instanceId)
    ) {
      return throwBuilderRuntimeError(
        "CONFLICT",
        "Generated record ID already exists in instances.",
        {
          issues: [
            {
              code: "generated_id_conflict",
              path: [],
              message:
                "Generated record ID conflicts with an existing instances record.",
              constraint: "unique_generated_id:instances",
              detail: "stage:fragment-instance-insertion",
            },
          ],
        }
      );
    }
  }
  const insertedChildren: Instance["children"] = fragment.children.map(
    (child) => {
      if (child.type === "id") {
        return createInstanceChild(
          newInstanceIds.get(child.value) ?? child.value
        );
      }
      return child;
    }
  );
  const insertionParent = nextData.instances.get(parent.id);
  if (insertionParent === undefined) {
    return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
  }
  const originalChildren = insertionParent.children;
  if (mode === "replace" && explicitInsertIndex !== undefined) {
    insertionParent.children = [
      ...originalChildren.slice(0, insertIndex),
      ...originalChildren.slice(insertIndex + 1),
    ];
  }
  const wrapped =
    insertedChildren.some((child) => child.type === "id") &&
    !(mode === "replace" && explicitInsertIndex === undefined)
      ? wrapEditableChildrenAroundInsertIndexMutable({
          instances: nextData.instances,
          props: nextData.props,
          metas: componentMetas,
          parentId: parent.id,
          position: insertIndex,
          createId: context.createId,
        })
      : undefined;
  if (wrapped === undefined) {
    insertionParent.children = originalChildren;
  }
  const effectiveInsertIndex = wrapped ?? insertIndex;
  assignUniqueBlockTemplateNamesMutable({
    instanceIds: insertedChildren.flatMap((child) =>
      child.type === "id" ? [child.value] : []
    ),
    parent,
    replacedInstanceIds:
      mode === "replace"
        ? replacedChildren.flatMap((child) =>
            child.type === "id" ? [child.value] : []
          )
        : [],
    instances: nextData.instances,
    components: componentMetas.keys(),
  });
  const requiredTemplateNameConfirmation =
    mode === "replace" && parent.component === blockTemplateComponent
      ? getBlockTemplateNameConfirmation({
          changes: replacedChildren.flatMap((child, index) => {
            if (child.type !== "id") {
              return [];
            }
            const instance = mutationState.instances.get(child.value);
            const inserted = insertedChildren[index];
            return instance === undefined
              ? []
              : [
                  {
                    instance,
                    nextInstance:
                      inserted?.type === "id"
                        ? nextData.instances.get(inserted.value)
                        : undefined,
                  },
                ];
          }),
          instances: mutationState.instances,
          props: mutationState.props.values(),
        })
      : undefined;

  if (validateContentModel) {
    const validationInstances = new Map(nextData.instances);
    const validationParent: Instance = {
      ...parent,
      children:
        wrapped !== undefined
          ? [
              ...insertionParent.children.slice(0, effectiveInsertIndex),
              ...insertedChildren,
              ...insertionParent.children.slice(effectiveInsertIndex),
            ]
          : mode === "replace"
            ? explicitInsertIndex === undefined
              ? insertedChildren
              : [
                  ...parentChildren.slice(0, insertIndex),
                  ...insertedChildren,
                  ...parentChildren.slice(insertIndex + 1),
                ]
            : [
                ...parentChildren.slice(0, insertIndex),
                ...insertedChildren,
                ...parentChildren.slice(insertIndex),
              ],
    };
    validationInstances.set(parent.id, validationParent);
    const { instanceSelector: parentSelector } =
      findPageAndSelectorByInstanceId(
        mutationState.pages,
        validationInstances,
        parent.id
      );
    const allowedWarnings = context.allowLegacyContentModelWarnings
      ? getFragmentPlacementContentModelWarnings({
          children: insertedChildren,
          instances: validationInstances,
          props: nextData.props,
          metas: componentMetas,
        })
      : [];
    const warnings = getFragmentPlacementContentModelWarnings({
      children: insertedChildren,
      instances: validationInstances,
      props: nextData.props,
      metas: componentMetas,
      parentSelector,
    });
    const [contentModelError] = getNewFragmentContentModelWarnings({
      warnings,
      allowedWarnings,
    });
    if (contentModelError !== undefined) {
      return throwBuilderRuntimeError("BAD_REQUEST", contentModelError.message);
    }
  }
  requireBlockTemplateNameConfirmation({
    required: requiredTemplateNameConfirmation,
    confirm,
    path: "mode",
  });

  const createResult = (
    parentInstanceId: string,
    removedInstanceIds: string[]
  ): ComponentInsertResult & Details =>
    ({
      instanceIds: Array.from(nextData.instances.keys()).filter(
        (instanceId) =>
          instanceId !== ROOT_INSTANCE_ID &&
          instanceId !== normalizedSlotDropTarget?.parentSelector[0] &&
          mutationState.instances.has(instanceId) === false
      ),
      rootInstanceIds: insertedChildren.flatMap((child) =>
        child.type === "id" ? [child.value] : []
      ),
      removedInstanceIds,
      parentInstanceId,
      ...(getResultDetails?.({ newInstanceIds, newDataSourceIds }) ??
        ({} as Details)),
      ...(didMergeBreakpointsDueToLimit
        ? { didMergeBreakpointsDueToLimit: true as const }
        : {}),
    }) as ComponentInsertResult & Details;

  if (normalizedSlotDropTarget !== undefined) {
    if (mode === "replace") {
      return throwBuilderRuntimeError(
        "BAD_REQUEST",
        'Insert mode "replace" is not supported for Slot content'
      );
    }
    if (mode === "prepend") {
      parent.children.splice(0, 0, ...insertedChildren);
    } else {
      parent.children.splice(effectiveInsertIndex, 0, ...insertedChildren);
    }
    const insertPayload = createFragmentPayload({
      before: mutationState,
      after: nextData,
      instancePatches: createRecordUpsertPatches({
        before: mutationState.instances,
        after: nextData.instances,
      }),
    });
    return createRuntimeMutation({
      payload: insertPayload,
      result: createResult(parent.id, []),
      invalidatesNamespaces: componentInsertNamespaces,
    });
  }

  const { payload: replacementPayload, replacedInstanceIds } =
    createInstanceAppendPayload({
      parent,
      instances: mutationState.instances,
      createdInstances: [],
      insertIndex,
      mode,
      props: mutationState.props.values(),
      dataSources: mutationState.dataSources.values(),
      styleSources: mutationState.styleSources.values(),
      styleSourceSelections: mutationState.styleSourceSelections.values(),
      styles: mutationState.styles.values(),
      replaceIndex:
        mode === "replace" && explicitInsertIndex !== undefined
          ? insertIndex
          : undefined,
    });
  const insertPayload = createFragmentInsertPayload({
    before: mutationState,
    after: nextData,
    parent,
    insertIndex: effectiveInsertIndex,
    insertedChildren,
  });
  return createRuntimeMutation({
    payload: compactBuilderPatchPayload([
      ...replacementPayload,
      ...insertPayload,
    ]),
    result: createResult(parent.id, replacedInstanceIds),
    invalidatesNamespaces: componentInsertNamespaces,
  });
};

const requireFragmentTokenConflictResolution = ({
  fragment,
  targetData,
  conflictResolution,
}: {
  fragment: WebstudioFragment;
  targetData: ReturnType<typeof getRequiredComponentInsertState>;
  conflictResolution?: ConflictResolution;
}) => {
  if (conflictResolution !== undefined) {
    return;
  }
  const conflicts = detectFragmentTokenConflicts({ fragment, targetData });
  if (conflicts.length > 0) {
    return throwBuilderRuntimeError(
      "CONFLICT",
      `Design token conflicts require an explicit conflictResolution (ours, theirs, or merge): ${conflicts
        .map(({ tokenName }) => tokenName)
        .join(", ")}`
    );
  }
};

export const insertComponent = (
  state: ComponentInsertState,
  input: z.infer<typeof insertComponentInput>,
  context: BuilderRuntimeContext
) => {
  const mutationState = getRequiredComponentInsertState(state);
  const parent = mutationState.instances.get(input.parentInstanceId);
  if (parent === undefined) {
    return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
  }

  if (
    input.component !== elementComponent &&
    !hasMdxComponentAdapter(input.component)
  ) {
    const { instanceSelector } = findPageAndSelectorByInstanceId(
      mutationState.pages,
      mutationState.instances,
      parent.id
    );
    let insideBody = false;
    for (const id of instanceSelector) {
      const ancestor = mutationState.instances.get(id);
      if (ancestor?.component === blockTemplateComponent) {
        break;
      }
      if (ancestor?.component === blockBodyComponent) {
        insideBody = true;
      }
      if (ancestor?.component !== blockComponent) {
        continue;
      }
      const source = getContentBlockSource({
        blockInstanceId: id,
        props: mutationState.props.values(),
      });
      if (
        source !== undefined &&
        (insideBody ||
          findContentBlockBodyContainers({
            blockInstance: ancestor,
            instances: mutationState.instances,
          }).length === 0)
      ) {
        return throwBuilderRuntimeError(
          "BAD_REQUEST",
          "To add this component to MDX content, add it to this Content Block’s Templates and insert it from the template picker. You can add a one-off instance outside MDX content."
        );
      }
      break;
    }
  }

  const templates = getComponentTemplates();
  const template = templates.get(input.component);
  const meta = componentMetas.get(input.component);
  const unknownCoreComponentError = getUnknownCoreComponentError({
    component: input.component,
    templates,
  });
  if (unknownCoreComponentError !== undefined) {
    return throwBuilderRuntimeError("BAD_REQUEST", unknownCoreComponentError);
  }
  const insertCategory = template?.category ?? meta?.category;
  const page = getInsertionPage(mutationState, parent);
  if (
    isComponentAvailableForDocumentType({
      component: input.component,
      category: insertCategory,
      documentType: page.meta.documentType ?? "html",
    }) === false
  ) {
    if (insertCategory === "xml") {
      return throwBuilderRuntimeError(
        "BAD_REQUEST",
        `XML component "${input.component}" can only be inserted on pages with document type "xml". Change the page document type in page settings before inserting XML components.`
      );
    }
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      `Component "${input.component}" is not available for pages with document type "${page.meta.documentType ?? "html"}". Change the page document type in page settings or choose an available component.`
    );
  }
  if (input.component === elementComponent && input.tag === undefined) {
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      'Component "ws:element" requires "tag", for example { "component": "ws:element", "tag": "section" }. Use a Webstudio component such as "Box" when you do not need a specific HTML tag.'
    );
  }
  if (input.component !== elementComponent && input.tag !== undefined) {
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      `"tag" can only be used with component "ws:element"; remove "tag" or use component "ws:element".`
    );
  }

  const fragment = createComponentTemplateFragment({
    component: input.component,
    templates,
    getFallbackError: (component) => {
      if (componentMetas.get(component)?.contentModel?.category !== "none") {
        return;
      }
      const { instanceSelector } = findPageAndSelectorByInstanceId(
        mutationState.pages,
        mutationState.instances,
        parent.id
      );
      const ancestors = instanceSelector.flatMap((instanceId) => {
        const instance = mutationState.instances.get(instanceId);
        return instance === undefined ? [] : [instance];
      });
      return getComponentPartInsertError({ component, ancestors });
    },
    createId: context.createId,
  });
  if (input.component === elementComponent) {
    for (const instance of fragment.instances) {
      if (instance.component === elementComponent) {
        instance.tag = input.tag;
      }
    }
  }
  return createInsertFragmentMutation({
    state,
    parentInstanceId: input.parentInstanceId,
    fragment,
    templates,
    mode: input.mode,
    insertIndex: input.insertIndex,
    validateContentModel: false,
    confirm: input.templateNameConfirmation,
    context,
  });
};

export const insertCollection = (
  state: ComponentInsertState,
  input: z.infer<typeof insertCollectionInput>,
  context: BuilderRuntimeContext
) => {
  const mutationState = getRequiredComponentInsertState(state);
  if (mutationState.instances.has(input.parentInstanceId) === false) {
    return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");
  }
  const templates = getComponentTemplates();
  const collection = createCollectionFragment({
    state: mutationState,
    input,
    templates,
  });
  requireFragmentTokenConflictResolution({
    fragment: collection.fragment,
    targetData: mutationState,
    conflictResolution: input.conflictResolution,
  });
  const getMappedId = (ids: Map<string, string>, sourceId: string) => {
    const id = ids.get(sourceId);
    if (id === undefined) {
      return throwBuilderRuntimeError(
        "CONFLICT",
        `Collection insertion did not map generated id "${sourceId}".`
      );
    }
    return id;
  };
  return createInsertFragmentMutation<
    Omit<InsertCollectionResult, keyof ComponentInsertResult>
  >({
    state,
    parentInstanceId: input.parentInstanceId,
    fragment: collection.fragment,
    templates,
    mode: input.mode,
    insertIndex: input.insertIndex,
    conflictResolution: input.conflictResolution,
    additionalAvailableVariables: collection.parameterDataSources,
    getResultDetails: ({ newInstanceIds, newDataSourceIds }) => ({
      collectionInstanceId: getMappedId(
        newInstanceIds,
        collection.collectionInstanceId
      ),
      itemRootInstanceId: getMappedId(
        newInstanceIds,
        collection.itemRootInstanceId
      ),
      itemParameterId: getMappedId(
        newDataSourceIds,
        collection.itemParameterId
      ),
      itemKeyParameterId: getMappedId(
        newDataSourceIds,
        collection.itemKeyParameterId
      ),
    }),
    context,
  });
};

const createInsertTokenFragmentMutation = ({
  state,
  fragment,
  conflictResolution,
  context,
}: {
  state: ComponentInsertState;
  fragment: WebstudioFragment;
  conflictResolution?: ConflictResolution;
  context: BuilderRuntimeContext;
}) => {
  const mutationState = getRequiredComponentInsertState(state);
  const nextData = cloneFragmentData(mutationState);
  const { didMergeBreakpointsDueToLimit } = insertWebstudioFragmentCopy({
    data: nextData,
    fragment,
    availableVariables: [],
    projectId: context.projectId ?? "",
    conflictResolution,
    createId: context.createId,
  });
  return createRuntimeMutation({
    payload: createTokenFragmentInsertPayload({
      before: mutationState,
      after: nextData,
    }),
    result: {
      instanceIds: [],
      rootInstanceIds: [],
      removedInstanceIds: [],
      ...(didMergeBreakpointsDueToLimit
        ? { didMergeBreakpointsDueToLimit }
        : {}),
    },
    invalidatesNamespaces: componentInsertNamespaces,
  });
};

export const insertFragment = (
  state: ComponentInsertState,
  input: z.infer<typeof insertFragmentInput>,
  context: BuilderRuntimeContext
): BuilderRuntimeMutation<FragmentInsertResult> => {
  const htmlEmbedError = validateFragmentHtmlEmbedCode(input.fragment);
  if (htmlEmbedError !== undefined) {
    return throwBuilderRuntimeError("BAD_REQUEST", htmlEmbedError.message);
  }
  requireFragmentTokenConflictResolution({
    fragment: input.fragment,
    targetData: getRequiredComponentInsertState(state),
    conflictResolution: input.conflictResolution,
  });
  if (input.fragment.children.length === 0) {
    return createInsertTokenFragmentMutation({
      state,
      fragment: input.fragment,
      conflictResolution: input.conflictResolution,
      context,
    });
  }
  if (input.parentInstanceId === undefined) {
    return throwBuilderRuntimeError(
      "BAD_REQUEST",
      "Parent instance is required when inserting a fragment with children"
    );
  }
  const templates = getComponentTemplates();
  return createInsertFragmentMutation({
    state,
    parentInstanceId: input.parentInstanceId,
    fragment: input.fragment,
    templates,
    mode: input.mode,
    insertIndex: input.insertIndex,
    conflictResolution: input.conflictResolution,
    contentMode: input.contentMode,
    confirm: input.templateNameConfirmation,
    context,
  });
};