import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import * as React from "react";
import { useComposedRefs, Button, PopoverPrimitives, Flex, Tag, Typography, HeaderLayout, ActionLayout, ContentLayout, lightTheme, useCollator, Combobox, ComboboxOption, Tooltip, IconButton, Popover, TextButton, BaseCheckbox, Badge, Avatar, AvatarGroup, useNotifyAT, Loader } from "@strapi/design-system";
import { Filter, Plus, Cross, Cog, Layer } from "@strapi/icons";
import isEqual from "lodash/isEqual";
import { J as requiredArgs, K as toInteger, L as millisecondsInHour, M as millisecondsInMinute, c as createContext, N as useControllableState, i as useQueryParams, F as Form, I as InputRenderer, u as useTracking, f as useNotification, h as useAPIErrorHandler, d as useDoc, z as useDocumentLayout, O as usePrev, j as buildValidParams, Q as useGetAllDocumentsQuery, T as lib, o as useDocumentRBAC, U as useEnterprise, l as useStrapiApp, g as getTranslation, P as Page, V as BackButton, W as InjectionZone, X as SearchInput, Y as Table, Z as DocumentStatus, a0 as getDisplayName, a1 as TableActions, a2 as Pagination, G as DocumentRBAC, a3 as useAuth, a4 as useContentTypeSchema, a5 as useAdminUsers, a6 as useGetContentTypeConfigurationQuery, a7 as CREATOR_FIELDS, a8 as getMainField, a as useField, a9 as useTypedSelector, aa as useRBAC, ab as checkIfAttributeIsDisplayable, ac as HOOKS, ad as convertListLayoutToFieldLayouts, p as prefixFileUrlWithBackendUrl, ae as getRelationLabel, af as useGetRelationsQuery } from "./index--h1ljeG8-PYl4iNtw.mjs";
import { H as HelmetExport } from "./Helmet-En-SEnNC.mjs";
import { useIntl } from "react-intl";
import { useNavigate, Link, NavLink } from "react-router-dom";
import styled from "styled-components";
import { u as useSyncRbac } from "./useSyncRbac-Od0wrAnD-NsSU7-VV.mjs";
import isEmpty from "lodash/isEmpty";
import toString from "lodash/toString";
import { Menu, LinkButton } from "@strapi/design-system/v2";
function parseISO(argument, options) {
  var _options$additionalDi;
  requiredArgs(1, arguments);
  var additionalDigits = toInteger((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2);
  if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {
    throw new RangeError("additionalDigits must be 0, 1 or 2");
  }
  if (!(typeof argument === "string" || Object.prototype.toString.call(argument) === "[object String]")) {
    return /* @__PURE__ */ new Date(NaN);
  }
  var dateStrings = splitDateString(argument);
  var date;
  if (dateStrings.date) {
    var parseYearResult = parseYear(dateStrings.date, additionalDigits);
    date = parseDate(parseYearResult.restDateString, parseYearResult.year);
  }
  if (!date || isNaN(date.getTime())) {
    return /* @__PURE__ */ new Date(NaN);
  }
  var timestamp = date.getTime();
  var time = 0;
  var offset;
  if (dateStrings.time) {
    time = parseTime(dateStrings.time);
    if (isNaN(time)) {
      return /* @__PURE__ */ new Date(NaN);
    }
  }
  if (dateStrings.timezone) {
    offset = parseTimezone(dateStrings.timezone);
    if (isNaN(offset)) {
      return /* @__PURE__ */ new Date(NaN);
    }
  } else {
    var dirtyDate = new Date(timestamp + time);
    var result = /* @__PURE__ */ new Date(0);
    result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate());
    result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds());
    return result;
  }
  return new Date(timestamp + time + offset);
}
var patterns = {
  dateTimeDelimiter: /[T ]/,
  timeZoneDelimiter: /[Z ]/i,
  timezone: /([Z+-].*)$/
};
var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
function splitDateString(dateString) {
  var dateStrings = {};
  var array = dateString.split(patterns.dateTimeDelimiter);
  var timeString;
  if (array.length > 2) {
    return dateStrings;
  }
  if (/:/.test(array[0])) {
    timeString = array[0];
  } else {
    dateStrings.date = array[0];
    timeString = array[1];
    if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
      dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
      timeString = dateString.substr(dateStrings.date.length, dateString.length);
    }
  }
  if (timeString) {
    var token = patterns.timezone.exec(timeString);
    if (token) {
      dateStrings.time = timeString.replace(token[1], "");
      dateStrings.timezone = token[1];
    } else {
      dateStrings.time = timeString;
    }
  }
  return dateStrings;
}
function parseYear(dateString, additionalDigits) {
  var regex = new RegExp("^(?:(\\d{4}|[+-]\\d{" + (4 + additionalDigits) + "})|(\\d{2}|[+-]\\d{" + (2 + additionalDigits) + "})$)");
  var captures = dateString.match(regex);
  if (!captures)
    return {
      year: NaN,
      restDateString: ""
    };
  var year = captures[1] ? parseInt(captures[1]) : null;
  var century = captures[2] ? parseInt(captures[2]) : null;
  return {
    year: century === null ? year : century * 100,
    restDateString: dateString.slice((captures[1] || captures[2]).length)
  };
}
function parseDate(dateString, year) {
  if (year === null)
    return /* @__PURE__ */ new Date(NaN);
  var captures = dateString.match(dateRegex);
  if (!captures)
    return /* @__PURE__ */ new Date(NaN);
  var isWeekDate = !!captures[4];
  var dayOfYear = parseDateUnit(captures[1]);
  var month = parseDateUnit(captures[2]) - 1;
  var day = parseDateUnit(captures[3]);
  var week = parseDateUnit(captures[4]);
  var dayOfWeek = parseDateUnit(captures[5]) - 1;
  if (isWeekDate) {
    if (!validateWeekDate(year, week, dayOfWeek)) {
      return /* @__PURE__ */ new Date(NaN);
    }
    return dayOfISOWeekYear(year, week, dayOfWeek);
  } else {
    var date = /* @__PURE__ */ new Date(0);
    if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
      return /* @__PURE__ */ new Date(NaN);
    }
    date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
    return date;
  }
}
function parseDateUnit(value) {
  return value ? parseInt(value) : 1;
}
function parseTime(timeString) {
  var captures = timeString.match(timeRegex);
  if (!captures)
    return NaN;
  var hours = parseTimeUnit(captures[1]);
  var minutes = parseTimeUnit(captures[2]);
  var seconds = parseTimeUnit(captures[3]);
  if (!validateTime(hours, minutes, seconds)) {
    return NaN;
  }
  return hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1e3;
}
function parseTimeUnit(value) {
  return value && parseFloat(value.replace(",", ".")) || 0;
}
function parseTimezone(timezoneString) {
  if (timezoneString === "Z")
    return 0;
  var captures = timezoneString.match(timezoneRegex);
  if (!captures)
    return 0;
  var sign = captures[1] === "+" ? -1 : 1;
  var hours = parseInt(captures[2]);
  var minutes = captures[3] && parseInt(captures[3]) || 0;
  if (!validateTimezone(hours, minutes)) {
    return NaN;
  }
  return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute);
}
function dayOfISOWeekYear(isoWeekYear, week, day) {
  var date = /* @__PURE__ */ new Date(0);
  date.setUTCFullYear(isoWeekYear, 0, 4);
  var fourthOfJanuaryDay = date.getUTCDay() || 7;
  var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
  date.setUTCDate(date.getUTCDate() + diff);
  return date;
}
var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function isLeapYearIndex(year) {
  return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
function validateDate(year, month, date) {
  return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28));
}
function validateDayOfYearDate(year, dayOfYear) {
  return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
}
function validateWeekDate(_year, week, day) {
  return week >= 1 && week <= 53 && day >= 0 && day <= 6;
}
function validateTime(hours, minutes, seconds) {
  if (hours === 24) {
    return minutes === 0 && seconds === 0;
  }
  return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
}
function validateTimezone(_hours, minutes) {
  return minutes >= 0 && minutes <= 59;
}
const BASE_FILTERS = [
  {
    label: { id: "components.FilterOptions.FILTER_TYPES.$eq", defaultMessage: "is" },
    value: "$eq"
  },
  {
    label: { id: "components.FilterOptions.FILTER_TYPES.$ne", defaultMessage: "is not" },
    value: "$ne"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$null",
      defaultMessage: "is null"
    },
    value: "$null"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$notNull",
      defaultMessage: "is not null"
    },
    value: "$notNull"
  }
];
const NUMERIC_FILTERS = [
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$gt",
      defaultMessage: "is greater than"
    },
    value: "$gt"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$gte",
      defaultMessage: "is greater than or equal to"
    },
    value: "$gte"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$lt",
      defaultMessage: "is less than"
    },
    value: "$lt"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$lte",
      defaultMessage: "is less than or equal to"
    },
    value: "$lte"
  }
];
const IS_SENSITIVE_FILTERS = [
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$eqi",
      defaultMessage: "is (case insensitive)"
    },
    value: "$eqi"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$nei",
      defaultMessage: "is not (case insensitive)"
    },
    value: "$nei"
  }
];
const CONTAINS_FILTERS = [
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$contains",
      defaultMessage: "contains"
    },
    value: "$contains"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$containsi",
      defaultMessage: "contains (case insensitive)"
    },
    value: "$containsi"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$notContains",
      defaultMessage: "not contains"
    },
    value: "$notContains"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$notContainsi",
      defaultMessage: "not contains (case insensitive)"
    },
    value: "$notContainsi"
  }
];
const STRING_PARSE_FILTERS = [
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$startsWith",
      defaultMessage: "starts with"
    },
    value: "$startsWith"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$startsWithi",
      defaultMessage: "starts with (case insensitive)"
    },
    value: "$startsWithi"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$endsWith",
      defaultMessage: "ends with"
    },
    value: "$endsWith"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$endsWithi",
      defaultMessage: "ends with (case insensitive)"
    },
    value: "$endsWithi"
  }
];
const [FiltersProvider, useFilters] = createContext("Filters");
const Root = ({
  children,
  disabled = false,
  onChange,
  onOpenChange,
  open: openProp,
  defaultOpen,
  options = []
}) => {
  const [triggerNode, setTriggerNode] = React.useState(null);
  const [open = false, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen,
    onChange: onOpenChange
  });
  const handleChange = (data) => {
    if (onChange) {
      onChange(data);
    }
  };
  return /* @__PURE__ */ jsx(
    FiltersProvider,
    {
      disabled,
      onChange: handleChange,
      open,
      options,
      setOpen,
      setTriggerNode,
      triggerNode,
      children
    }
  );
};
const Trigger = React.forwardRef(
  ({ label }, forwardedRef) => {
    const { formatMessage } = useIntl();
    const { setTriggerNode, setOpen } = useFilters("Trigger", ({ setTriggerNode: setTriggerNode2, setOpen: setOpen2 }) => ({
      setTriggerNode: setTriggerNode2,
      setOpen: setOpen2
    }));
    const disabled = useFilters("Trigger", ({ disabled: disabled2 }) => disabled2);
    const open = useFilters("Trigger", ({ open: open2 }) => open2);
    const composedRefs = useComposedRefs(forwardedRef, setTriggerNode);
    const handleClick = () => setOpen(!open);
    return /* @__PURE__ */ jsx(
      Button,
      {
        variant: "tertiary",
        ref: composedRefs,
        startIcon: /* @__PURE__ */ jsx(Filter, {}),
        onClick: handleClick,
        size: "S",
        disabled,
        children: label || formatMessage({ id: "app.utils.filters", defaultMessage: "Filters" })
      }
    );
  }
);
const PopoverImpl = () => {
  const [{ query }, setQuery] = useQueryParams();
  const { formatMessage } = useIntl();
  const open = useFilters("Popover", ({ open: open2 }) => open2);
  const options = useFilters("Popover", ({ options: options2 }) => options2);
  const triggerNode = useFilters("Popover", ({ triggerNode: triggerNode2 }) => triggerNode2);
  const setOpen = useFilters("Popover", ({ setOpen: setOpen2 }) => setOpen2);
  const onChange = useFilters("Popover", ({ onChange: onChange2 }) => onChange2);
  if (!open || options.length === 0 || !triggerNode) {
    return null;
  }
  const handleSubmit = (data) => {
    if (!data.value) {
      return;
    }
    if (onChange) {
      onChange(data);
    }
    const filterType = options.find((filter) => filter.name === data.name).type;
    const operatorValuePairing = {
      [data.filter]: data.value
    };
    const newFilterQuery = {
      ...query.filters,
      $and: [
        ...query.filters?.$and ?? [],
        {
          [data.name]: filterType === "relation" ? {
            id: operatorValuePairing
          } : operatorValuePairing
        }
      ]
    };
    setQuery({ filters: newFilterQuery, page: 1 });
    setOpen(false);
  };
  return /* @__PURE__ */ jsx(
    PopoverPrimitives.Content,
    {
      source: { current: triggerNode },
      onDismiss: () => setOpen(false),
      padding: 3,
      spacing: 4,
      maxHeight: "unset",
      children: /* @__PURE__ */ jsx(
        Form,
        {
          method: "POST",
          initialValues: {
            name: options[0]?.name,
            filter: BASE_FILTERS[0].value
          },
          onSubmit: handleSubmit,
          children: ({ values: formValues, modified, isSubmitting }) => {
            const filter = options.find((filter2) => filter2.name === formValues.name);
            const Input = filter?.input || InputRenderer;
            return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, style: { minWidth: 184 }, children: [
              [
                {
                  ["aria-label"]: formatMessage({
                    id: "app.utils.select-field",
                    defaultMessage: "Select field"
                  }),
                  name: "name",
                  options: options.map((filter2) => ({
                    label: filter2.label,
                    value: filter2.name
                  })),
                  placholder: formatMessage({
                    id: "app.utils.select-field",
                    defaultMessage: "Select field"
                  }),
                  type: "enumeration"
                },
                {
                  ["aria-label"]: formatMessage({
                    id: "app.utils.select-filter",
                    defaultMessage: "Select filter"
                  }),
                  name: "filter",
                  options: filter?.operators || getFilterList(filter).map((opt) => ({
                    label: formatMessage(opt.label),
                    value: opt.value
                  })),
                  placeholder: formatMessage({
                    id: "app.utils.select-filter",
                    defaultMessage: "Select filter"
                  }),
                  type: "enumeration"
                }
              ].map((field) => /* @__PURE__ */ jsx(InputRenderer, { ...field }, field.name)),
              filter && formValues.filter && formValues.filter !== "$null" && formValues.filter !== "$notNull" ? /* @__PURE__ */ jsx(
                Input,
                {
                  ...filter,
                  label: null,
                  "aria-label": filter.label,
                  name: "value",
                  type: filter.mainField?.type ?? filter.type
                }
              ) : null,
              /* @__PURE__ */ jsx(
                Button,
                {
                  disabled: !modified || isSubmitting,
                  size: "L",
                  variant: "secondary",
                  startIcon: /* @__PURE__ */ jsx(Plus, {}),
                  type: "submit",
                  fullWidth: true,
                  children: formatMessage({ id: "app.utils.add-filter", defaultMessage: "Add filter" })
                }
              )
            ] });
          }
        }
      )
    }
  );
};
const getFilterList = (filter) => {
  if (!filter) {
    return [];
  }
  const type = filter.mainField?.type ? filter.mainField.type : filter.type;
  switch (type) {
    case "email":
    case "text":
    case "enumeration":
    case "string": {
      return [
        ...BASE_FILTERS,
        ...IS_SENSITIVE_FILTERS,
        ...CONTAINS_FILTERS,
        ...STRING_PARSE_FILTERS
      ];
    }
    case "float":
    case "integer":
    case "biginteger":
    case "decimal": {
      return [...BASE_FILTERS, ...NUMERIC_FILTERS];
    }
    case "time":
    case "date": {
      return [...BASE_FILTERS, ...NUMERIC_FILTERS, ...CONTAINS_FILTERS];
    }
    case "datetime": {
      return [...BASE_FILTERS, ...NUMERIC_FILTERS];
    }
    default:
      return [...BASE_FILTERS, ...IS_SENSITIVE_FILTERS];
  }
};
const List = () => {
  const [{ query }, setQuery] = useQueryParams();
  const options = useFilters("List", ({ options: options2 }) => options2);
  const handleClick = (data) => {
    const nextFilters = (query?.filters?.$and ?? []).filter((filter) => {
      const [attributeName] = Object.keys(filter);
      if (attributeName !== data.name) {
        return true;
      }
      const { type, mainField } = options.find(({ name }) => name === attributeName);
      if (type === "relation") {
        const filterObj = filter[attributeName][mainField?.name ?? "id"];
        if (typeof filterObj === "object") {
          const [operator] = Object.keys(filterObj);
          const value = filterObj[operator];
          return !(operator === data.filter && value === data.value);
        }
        return true;
      } else {
        const filterObj = filter[attributeName];
        const [operator] = Object.keys(filterObj);
        const value = filterObj[operator];
        return !(operator === data.filter && value === data.value);
      }
    });
    setQuery({ filters: { $and: nextFilters }, page: 1 });
  };
  if (!query?.filters?.$and?.length) {
    return null;
  }
  return /* @__PURE__ */ jsx(Fragment, { children: query?.filters?.$and?.map((queryFilter) => {
    const [attributeName] = Object.keys(queryFilter);
    const filter = options.find(({ name }) => name === attributeName);
    const filterObj = queryFilter[attributeName];
    if (!filter || typeof filterObj !== "object" || filterObj === null) {
      return null;
    }
    if (filter.type === "relation") {
      const modelFilter = filterObj[filter.mainField?.name ?? "id"];
      if (typeof modelFilter === "object") {
        const [operator] = Object.keys(modelFilter);
        const value = modelFilter[operator];
        return /* @__PURE__ */ jsx(
          AttributeTag,
          {
            ...filter,
            onClick: handleClick,
            operator,
            value
          },
          `${attributeName}-${operator}-${value}`
        );
      }
      return null;
    } else {
      const [operator] = Object.keys(filterObj);
      const value = filterObj[operator];
      if (typeof value === "object") {
        return null;
      }
      return /* @__PURE__ */ jsx(
        AttributeTag,
        {
          ...filter,
          onClick: handleClick,
          operator,
          value
        },
        `${attributeName}-${operator}-${value}`
      );
    }
  }) });
};
const AttributeTag = ({
  input,
  label,
  mainField,
  name,
  onClick,
  operator,
  options,
  value,
  ...filter
}) => {
  const { formatMessage, formatDate, formatTime, formatNumber } = useIntl();
  const handleClick = () => {
    onClick({ name, value, filter: operator });
  };
  const type = mainField?.type ? mainField.type : filter.type;
  let formattedValue = value;
  switch (type) {
    case "date":
      formattedValue = formatDate(value, { dateStyle: "full" });
      break;
    case "datetime":
      formattedValue = formatDate(value, { dateStyle: "full", timeStyle: "short" });
      break;
    case "time":
      const [hour, minute] = value.split(":");
      const date = /* @__PURE__ */ new Date();
      date.setHours(Number(hour));
      date.setMinutes(Number(minute));
      formattedValue = formatTime(date, {
        hour: "numeric",
        minute: "numeric"
      });
      break;
    case "float":
    case "integer":
    case "biginteger":
    case "decimal":
      formattedValue = formatNumber(Number(value));
      break;
  }
  if (input && options) {
    const selectedOption = options.find((option) => {
      return (typeof option === "string" ? option : option.value) === value;
    });
    formattedValue = selectedOption ? typeof selectedOption === "string" ? selectedOption : selectedOption.label ?? selectedOption.value : value;
  }
  const content = `${label} ${formatMessage({
    id: `components.FilterOptions.FILTER_TYPES.${operator}`,
    defaultMessage: operator
  })} ${operator !== "$null" && operator !== "$notNull" ? formattedValue : ""}`;
  return /* @__PURE__ */ jsx(Tag, { padding: 1, onClick: handleClick, icon: /* @__PURE__ */ jsx(Cross, {}), children: content });
};
const Filters = {
  List,
  Popover: PopoverImpl,
  Root,
  Trigger
};
const REVIEW_WORKFLOW_FILTER_CE = [];
const NOT_ALLOWED_FILTERS = [
  "json",
  "component",
  "media",
  "richtext",
  "dynamiczone",
  "password",
  "blocks"
];
const DEFAULT_ALLOWED_FILTERS = ["createdAt", "updatedAt"];
const USER_FILTER_ATTRIBUTES = [...CREATOR_FIELDS, "strapi_assignee"];
const FiltersImpl = ({ disabled, schema }) => {
  const { attributes, uid: model, options } = schema;
  const { formatMessage, locale } = useIntl();
  const { trackUsage } = useTracking();
  const allPermissions = useAuth("FiltersImpl", (state) => state.permissions);
  const [{ query }] = useQueryParams();
  const { schemas } = useContentTypeSchema();
  const canReadAdminUsers = React.useMemo(
    () => allPermissions.filter(
      (permission) => permission.action === "admin::users.read" && permission.subject === null
    ).length > 0,
    [allPermissions]
  );
  const selectedUserIds = (query?.filters?.$and ?? []).reduce((acc, filter) => {
    const [key, value] = Object.entries(filter)[0];
    if (typeof value.id !== "object") {
      return acc;
    }
    const id = value.id.$eq || value.id.$ne;
    if (id && USER_FILTER_ATTRIBUTES.includes(key) && !acc.includes(id)) {
      acc.push(id);
    }
    return acc;
  }, []);
  const { data: userData, isLoading: isLoadingAdminUsers } = useAdminUsers(
    { filters: { id: { $in: selectedUserIds } } },
    {
      // fetch the list of admin users only if the filter contains users and the
      // current user has permissions to display users
      skip: selectedUserIds.length === 0 || !canReadAdminUsers
    }
  );
  const { users = [] } = userData ?? {};
  const { metadata } = useGetContentTypeConfigurationQuery(model, {
    selectFromResult: ({ data }) => ({ metadata: data?.contentType.metadatas ?? {} })
  });
  const formatter = useCollator(locale, {
    sensitivity: "base"
  });
  const displayedAttributeFilters = React.useMemo(() => {
    const [{ properties: { fields = [] } = { fields: [] } }] = allPermissions.filter(
      (permission) => permission.action === "plugin::content-manager.explorer.read" && permission.subject === model
    );
    const allowedFields = fields.filter((field) => {
      const attribute = attributes[field] ?? {};
      return attribute.type && !NOT_ALLOWED_FILTERS.includes(attribute.type);
    });
    return [
      "id",
      ...allowedFields,
      ...DEFAULT_ALLOWED_FILTERS,
      ...canReadAdminUsers ? CREATOR_FIELDS : []
    ].map((name) => {
      const attribute = attributes[name];
      if (NOT_ALLOWED_FILTERS.includes(attribute.type)) {
        return null;
      }
      const { mainField: mainFieldName = "", label } = metadata[name].list;
      let filter = {
        name,
        label: label ?? "",
        mainField: getMainField(attribute, mainFieldName, { schemas, components: {} }),
        // @ts-expect-error – TODO: this is filtered out above in the `allowedFields` call but TS complains, is there a better way to solve this?
        type: attribute.type
      };
      if (attribute.type === "relation" && "target" in attribute && attribute.target === "admin::user") {
        filter = {
          ...filter,
          input: AdminUsersFilter,
          options: users.map((user) => ({
            label: getDisplayName(user, formatMessage),
            value: user.id.toString()
          })),
          operators: [
            {
              label: formatMessage({
                id: "components.FilterOptions.FILTER_TYPES.$eq",
                defaultMessage: "is"
              }),
              value: "$eq"
            },
            {
              label: formatMessage({
                id: "components.FilterOptions.FILTER_TYPES.$ne",
                defaultMessage: "is not"
              }),
              value: "$ne"
            }
          ],
          mainField: {
            name: "id",
            type: "integer"
          }
        };
      }
      return filter;
    }).filter(Boolean);
  }, [
    allPermissions,
    model,
    canReadAdminUsers,
    attributes,
    metadata,
    schemas,
    users,
    formatMessage
  ]);
  const reviewWorkflowFilter = useEnterprise(
    REVIEW_WORKFLOW_FILTER_CE,
    async () => (await import("./constants-VMWcn5Dg-z8ZNCCYd.mjs")).REVIEW_WORKFLOW_FILTERS,
    {
      combine(ceFilters, eeFilters) {
        return [
          ...ceFilters,
          ...eeFilters.filter((eeFilter) => {
            if (eeFilter.name === "strapi_assignee") {
              return canReadAdminUsers;
            }
            return true;
          }).map((eeFilter) => ({
            ...eeFilter,
            "aria-label": formatMessage(eeFilter.label),
            options: (
              // TODO: strapi_assignee should not be in here and rather defined
              // in the ee directory.
              eeFilter.name === "strapi_assignee" ? users.map((user) => ({
                label: getDisplayName(user, formatMessage),
                value: user.id.toString()
              })) : void 0
            )
          }))
        ];
      },
      defaultValue: [],
      // we have to wait for admin users to be fully loaded, because otherwise
      // combine is called to early and does not contain the latest state of
      // the users array
      enabled: !!options?.reviewWorkflows && !isLoadingAdminUsers
    }
    /**
     * this is cast because the data returns MessageDescriptor
     * as `metadatas.label` _then_ we turn it to a string.
     */
  );
  const onOpenChange = (isOpen) => {
    if (isOpen) {
      trackUsage("willFilterEntries");
    }
  };
  const displayedFilters = [...displayedAttributeFilters, ...reviewWorkflowFilter].sort(
    (a, b) => formatter.compare(a.label, b.label)
  );
  const handleFilterChange = (data) => {
    const attribute = attributes[data.name];
    if (attribute) {
      trackUsage("didFilterEntries", {
        useRelation: attribute.type === "relation"
      });
    }
  };
  return /* @__PURE__ */ jsxs(
    Filters.Root,
    {
      disabled,
      options: displayedFilters,
      onOpenChange,
      onChange: handleFilterChange,
      children: [
        /* @__PURE__ */ jsx(Filters.Trigger, {}),
        /* @__PURE__ */ jsx(Filters.Popover, {}),
        /* @__PURE__ */ jsx(Filters.List, {})
      ]
    }
  );
};
const AdminUsersFilter = ({ name }) => {
  const [page, setPage] = React.useState(1);
  const { formatMessage } = useIntl();
  const { data, isLoading } = useAdminUsers({
    page
  });
  const field = useField(name);
  const handleOpenChange = (isOpen) => {
    if (!isOpen) {
      setPage(1);
    }
  };
  const users = data?.users || [];
  return /* @__PURE__ */ jsx(
    Combobox,
    {
      value: field.value,
      "aria-label": formatMessage({
        id: "content-manager.components.Filters.usersSelect.label",
        defaultMessage: "Search and select a user to filter"
      }),
      onOpenChange: handleOpenChange,
      onChange: (value) => field.onChange(name, value),
      loading: isLoading,
      onLoadMore: () => setPage((prev) => prev + 1),
      children: users.map((user) => {
        return /* @__PURE__ */ jsx(ComboboxOption, { value: user.id.toString(), children: getDisplayName(user, formatMessage) }, user.id);
      })
    }
  );
};
const CellValue = ({ type, value }) => {
  const { formatDate, formatTime, formatNumber } = useIntl();
  let formattedValue = value;
  if (type === "date") {
    formattedValue = formatDate(parseISO(value), { dateStyle: "full" });
  }
  if (type === "datetime") {
    formattedValue = formatDate(value, { dateStyle: "full", timeStyle: "short" });
  }
  if (type === "time") {
    const [hour, minute, second] = value.split(":");
    const date = /* @__PURE__ */ new Date();
    date.setHours(hour);
    date.setMinutes(minute);
    date.setSeconds(second);
    formattedValue = formatTime(date, {
      timeStyle: "short"
    });
  }
  if (["float", "decimal"].includes(type)) {
    formattedValue = formatNumber(value, {
      // Should be kept in sync with the corresponding value
      // in the design-system/NumberInput: https://github.com/strapi/design-system/blob/main/packages/strapi-design-system/src/NumberInput/NumberInput.js#L53
      maximumFractionDigits: 20
    });
  }
  if (["integer", "biginteger"].includes(type)) {
    formattedValue = formatNumber(value, { maximumFractionDigits: 0 });
  }
  return toString(formattedValue);
};
const SingleComponent = ({ content, mainField }) => {
  if (!mainField) {
    return null;
  }
  return /* @__PURE__ */ jsx(Tooltip, { label: content[mainField.name], children: /* @__PURE__ */ jsx(SingleComponentTypography, { textColor: "neutral800", ellipsis: true, children: /* @__PURE__ */ jsx(CellValue, { type: mainField.type, value: content[mainField.name] }) }) });
};
const SingleComponentTypography = styled(Typography)`
  max-width: 250px;
`;
const RepeatableComponent = ({ content, mainField }) => {
  const { formatMessage } = useIntl();
  if (!mainField) {
    return null;
  }
  return /* @__PURE__ */ jsxs(Menu.Root, { children: [
    /* @__PURE__ */ jsxs(MenuTrigger$1, { onClick: (e) => e.stopPropagation(), children: [
      /* @__PURE__ */ jsx(Badge, { children: content.length }),
      " ",
      formatMessage(
        {
          id: "content-manager.containers.list.items",
          defaultMessage: "{number, plural, =0 {items} one {item} other {items}}"
        },
        { number: content.length }
      )
    ] }),
    /* @__PURE__ */ jsx(Menu.Content, { children: content.map((item) => /* @__PURE__ */ jsx(Menu.Item, { disabled: true, children: /* @__PURE__ */ jsx(RepeatableComponentTypography, { ellipsis: true, children: /* @__PURE__ */ jsx(CellValue, { type: mainField.type, value: item[mainField.name] }) }) }, item.id)) })
  ] });
};
const RepeatableComponentTypography = styled(Typography)`
  max-width: 500px;
`;
const MenuTrigger$1 = styled(Menu.Trigger)`
  svg {
    width: ${6 / 16}rem;
    height: ${4 / 16}rem;
  }
`;
const getFileExtension = (ext) => ext && ext[0] === "." ? ext.substring(1) : ext;
const MediaSingle = ({ url, mime, alternativeText, name, ext, formats }) => {
  const fileURL = prefixFileUrlWithBackendUrl(url);
  if (mime.includes("image")) {
    const thumbnail = formats?.thumbnail?.url;
    const mediaURL = prefixFileUrlWithBackendUrl(thumbnail) || fileURL;
    return /* @__PURE__ */ jsx(Avatar, { src: mediaURL, alt: alternativeText || name, preview: true });
  }
  const fileExtension = getFileExtension(ext);
  const fileName = name.length > 100 ? `${name.substring(0, 100)}...` : name;
  return /* @__PURE__ */ jsx(Tooltip, { description: fileName, children: /* @__PURE__ */ jsx(FileWrapper, { children: fileExtension }) });
};
const FileWrapper = ({ children }) => {
  return /* @__PURE__ */ jsx(
    Flex,
    {
      as: "span",
      position: "relative",
      borderRadius: "50%",
      width: "26px",
      height: "26px",
      borderColor: "neutral200",
      background: "neutral150",
      paddingLeft: "1px",
      justifyContent: "center",
      alignItems: "center",
      children: /* @__PURE__ */ jsx(FileTypography, { variant: "sigma", textColor: "neutral600", children })
    }
  );
};
const FileTypography = styled(Typography)`
  font-size: 0.6rem;
  line-height: 0.6rem;
`;
const MediaMultiple = ({ content }) => {
  return /* @__PURE__ */ jsx(AvatarGroup, { children: content.map((file, index) => {
    const key = `${file.id}${index}`;
    if (index === 3) {
      const remainingFiles = `+${content.length - 3}`;
      return /* @__PURE__ */ jsx(FileWrapper, { children: remainingFiles }, key);
    }
    if (index > 3) {
      return null;
    }
    return /* @__PURE__ */ jsx(MediaSingle, { ...file }, key);
  }) });
};
const RelationSingle = ({ mainField, content }) => {
  return /* @__PURE__ */ jsx(TypographyMaxWidth$1, { textColor: "neutral800", ellipsis: true, children: getRelationLabel(content, mainField) });
};
const TypographyMaxWidth$1 = styled(Typography)`
  max-width: 500px;
`;
const RelationMultiple = ({ mainField, content, rowId, name }) => {
  const { model } = useDoc();
  const { formatMessage } = useIntl();
  const { notifyStatus } = useNotifyAT();
  const [isOpen, setIsOpen] = React.useState(false);
  const [targetField] = name.split(".");
  const { data, isLoading } = useGetRelationsQuery(
    {
      model,
      id: rowId,
      targetField
    },
    {
      skip: !isOpen,
      refetchOnMountOrArgChange: true
    }
  );
  React.useEffect(() => {
    if (data) {
      notifyStatus(
        formatMessage({
          id: getTranslation("DynamicTable.relation-loaded"),
          defaultMessage: "Relations have been loaded"
        })
      );
    }
  }, [data, formatMessage, notifyStatus]);
  return /* @__PURE__ */ jsxs(Menu.Root, { onOpenChange: (isOpen2) => setIsOpen(isOpen2), children: [
    /* @__PURE__ */ jsx(MenuTrigger, { onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsxs(Flex, { gap: 1, wrap: "nowrap", children: [
      /* @__PURE__ */ jsx(Badge, { children: content.count }),
      formatMessage(
        {
          id: "content-manager.containers.list.items",
          defaultMessage: "{number, plural, =0 {items} one {item} other {items}}"
        },
        { number: content.count }
      )
    ] }) }),
    /* @__PURE__ */ jsxs(Menu.Content, { children: [
      isLoading && /* @__PURE__ */ jsx(Menu.Item, { disabled: true, children: /* @__PURE__ */ jsx(Loader, { small: true, children: formatMessage({
        id: getTranslation("ListViewTable.relation-loading"),
        defaultMessage: "Relations are loading"
      }) }) }),
      data?.results && /* @__PURE__ */ jsxs(Fragment, { children: [
        data.results.map((entry) => /* @__PURE__ */ jsx(Menu.Item, { disabled: true, children: /* @__PURE__ */ jsx(TypographyMaxWidth$1, { ellipsis: true, children: getRelationLabel(entry, mainField) }) }, entry.documentId)),
        data?.pagination && data?.pagination.total > 10 && /* @__PURE__ */ jsx(
          Menu.Item,
          {
            "aria-disabled": true,
            "aria-label": formatMessage({
              id: getTranslation("ListViewTable.relation-more"),
              defaultMessage: "This relation contains more entities than displayed"
            }),
            children: /* @__PURE__ */ jsx(Typography, { children: "…" })
          }
        )
      ] })
    ] })
  ] });
};
const MenuTrigger = styled(Menu.Trigger)`
  svg {
    width: ${6 / 16}rem;
    height: ${4 / 16}rem;
  }
`;
const CellContent = ({ content, mainField, attribute, rowId, name }) => {
  if (!hasContent(content, mainField, attribute)) {
    return /* @__PURE__ */ jsx(Typography, { textColor: "neutral800", children: "-" });
  }
  switch (attribute.type) {
    case "media":
      if (!attribute.multiple) {
        return /* @__PURE__ */ jsx(MediaSingle, { ...content });
      }
      return /* @__PURE__ */ jsx(MediaMultiple, { content });
    case "relation": {
      if (isSingleRelation(attribute.relation)) {
        return /* @__PURE__ */ jsx(RelationSingle, { mainField, content });
      }
      return /* @__PURE__ */ jsx(RelationMultiple, { rowId, mainField, content, name });
    }
    case "component":
      if (attribute.repeatable) {
        return /* @__PURE__ */ jsx(RepeatableComponent, { mainField, content });
      }
      return /* @__PURE__ */ jsx(SingleComponent, { mainField, content });
    case "string":
      return /* @__PURE__ */ jsx(Tooltip, { description: content, children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: /* @__PURE__ */ jsx(CellValue, { type: attribute.type, value: content }) }) });
    default:
      return /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: /* @__PURE__ */ jsx(CellValue, { type: attribute.type, value: content }) });
  }
};
const TypographyMaxWidth = styled(Typography)`
  max-width: 300px;
`;
const hasContent = (content, mainField, attribute) => {
  if (attribute.type === "component") {
    if (attribute.repeatable || !mainField) {
      return content?.length > 0;
    }
    const value = content?.[mainField.name];
    if (mainField.name === "id" && ![void 0, null].includes(value)) {
      return true;
    }
    return !isEmpty(value);
  }
  if (attribute.type === "relation") {
    if (isSingleRelation(attribute.relation)) {
      return !isEmpty(content);
    }
    return content?.count > 0;
  }
  if (["integer", "decimal", "float", "number"].includes(attribute.type)) {
    return typeof content === "number";
  }
  if (attribute.type === "boolean") {
    return content !== null;
  }
  return !isEmpty(content);
};
const isSingleRelation = (type) => ["oneToOne", "manyToOne", "oneToOneMorph"].includes(type);
const ViewSettingsMenu = (props) => {
  const [isVisible, setIsVisible] = React.useState(false);
  const cogButtonRef = React.useRef(null);
  const permissions = useTypedSelector(
    (state) => state.admin_app.permissions.contentManager?.collectionTypesConfigurations ?? []
  );
  const [{ query }] = useQueryParams();
  const { formatMessage } = useIntl();
  const {
    allowedActions: { canViewConfiguration }
  } = useRBAC({
    viewConfiguration: permissions
  });
  const handleToggle = () => {
    setIsVisible((prev) => !prev);
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      IconButton,
      {
        icon: /* @__PURE__ */ jsx(Cog, {}),
        label: formatMessage({
          id: "components.ViewSettings.tooltip",
          defaultMessage: "View Settings"
        }),
        ref: cogButtonRef,
        onClick: handleToggle
      }
    ),
    isVisible && /* @__PURE__ */ jsx(
      Popover,
      {
        placement: "bottom-end",
        source: cogButtonRef,
        onDismiss: handleToggle,
        spacing: 4,
        padding: 3,
        children: /* @__PURE__ */ jsxs(Flex, { alignItems: "stretch", direction: "column", gap: 3, children: [
          canViewConfiguration ? /* @__PURE__ */ jsx(
            LinkButton,
            {
              size: "S",
              startIcon: /* @__PURE__ */ jsx(Layer, {}),
              variant: "secondary",
              as: NavLink,
              to: {
                pathname: "configurations/list",
                search: query.plugins ? lib.stringify({ plugins: query.plugins }, { encode: false }) : ""
              },
              children: formatMessage({
                id: "app.links.configure-view",
                defaultMessage: "Configure the view"
              })
            }
          ) : null,
          /* @__PURE__ */ jsx(FieldPicker, { ...props })
        ] })
      }
    )
  ] });
};
const FieldPicker = ({ headers = [], resetHeaders, setHeaders }) => {
  const { trackUsage } = useTracking();
  const { formatMessage, locale } = useIntl();
  const { schema, model } = useDoc();
  const { list } = useDocumentLayout(model);
  const formatter = useCollator(locale, {
    sensitivity: "base"
  });
  const attributes = schema?.attributes ?? {};
  const columns = Object.keys(attributes).filter((name) => checkIfAttributeIsDisplayable(attributes[name])).map((name) => ({
    name,
    label: list.metadatas[name]?.label ?? ""
  })).sort((a, b) => formatter.compare(a.label, b.label));
  const handleChange = (name) => {
    trackUsage("didChangeDisplayedFields");
    const newHeaders = headers.includes(name) ? headers.filter((header) => header !== name) : [...headers, name];
    setHeaders(newHeaders);
  };
  const handleReset = () => {
    resetHeaders();
  };
  return /* @__PURE__ */ jsxs(Flex, { as: "fieldset", direction: "column", alignItems: "stretch", gap: 3, children: [
    /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", children: [
      /* @__PURE__ */ jsx(Typography, { as: "legend", variant: "pi", fontWeight: "bold", children: formatMessage({
        id: "containers.list.displayedFields",
        defaultMessage: "Displayed fields"
      }) }),
      /* @__PURE__ */ jsx(TextButton, { onClick: handleReset, children: formatMessage({
        id: "app.components.Button.reset",
        defaultMessage: "Reset"
      }) })
    ] }),
    /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", children: columns.map((header) => {
      const isActive = headers.includes(header.name);
      return /* @__PURE__ */ jsxs(
        ChackboxWrapper,
        {
          wrap: "wrap",
          gap: 2,
          as: "label",
          background: isActive ? "primary100" : "transparent",
          hasRadius: true,
          padding: 2,
          children: [
            /* @__PURE__ */ jsx(
              BaseCheckbox,
              {
                onChange: () => handleChange(header.name),
                value: isActive,
                name: header.name
              }
            ),
            /* @__PURE__ */ jsx(Typography, { fontSize: 1, children: header.label })
          ]
        },
        header.name
      );
    }) })
  ] });
};
const ChackboxWrapper = styled(Flex)`
  :hover {
    background-color: ${(props) => props.theme.colors.primary100};
  }
`;
const { INJECT_COLUMN_IN_TABLE } = HOOKS;
const REVIEW_WORKFLOW_COLUMNS_CE = null;
const REVIEW_WORKFLOW_COLUMNS_CELL_CE = {
  ReviewWorkflowsStageEE: () => null,
  ReviewWorkflowsAssigneeEE: () => null
};
const ListViewPage = () => {
  const { trackUsage } = useTracking();
  const navigate = useNavigate();
  const { formatMessage } = useIntl();
  const { toggleNotification } = useNotification();
  const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler(getTranslation);
  const { collectionType, model, schema } = useDoc();
  const { list } = useDocumentLayout(model);
  const [displayedHeaders, setDisplayedHeaders] = React.useState([]);
  const listLayout = usePrev(list.layout);
  React.useEffect(() => {
    if (!isEqual(listLayout, list.layout)) {
      setDisplayedHeaders(list.layout);
    }
  }, [list.layout, listLayout]);
  const handleSetHeaders = (headers) => {
    setDisplayedHeaders(
      convertListLayoutToFieldLayouts(headers, schema.attributes, list.metadatas)
    );
  };
  const [{ query }] = useQueryParams({
    page: "1",
    pageSize: list.settings.pageSize.toString(),
    sort: list.settings.defaultSortBy ? `${list.settings.defaultSortBy}:${list.settings.defaultSortOrder}` : ""
  });
  const params = React.useMemo(() => buildValidParams(query), [query]);
  const { data, error, isLoading } = useGetAllDocumentsQuery({
    model,
    params
  });
  React.useEffect(() => {
    if (error) {
      toggleNotification({
        type: "danger",
        message: formatAPIError(error)
      });
    }
  }, [error, formatAPIError, toggleNotification]);
  const { results = [], pagination } = data ?? {};
  React.useEffect(() => {
    if (pagination && pagination.pageCount > 0 && pagination.page > pagination.pageCount) {
      navigate(
        {
          search: lib.stringify({
            ...query,
            page: pagination.pageCount
          })
        },
        { replace: true }
      );
    }
  }, [pagination, formatMessage, query, navigate]);
  const { canCreate } = useDocumentRBAC("ListViewPage", ({ canCreate: canCreate2 }) => ({
    canCreate: canCreate2
  }));
  const reviewWorkflowColumns = useEnterprise(
    REVIEW_WORKFLOW_COLUMNS_CE,
    async () => (await import("./constants-VMWcn5Dg-z8ZNCCYd.mjs")).REVIEW_WORKFLOW_COLUMNS_EE,
    {
      enabled: !!schema?.options?.reviewWorkflows
    }
  );
  const ReviewWorkflowsColumns = useEnterprise(
    REVIEW_WORKFLOW_COLUMNS_CELL_CE,
    async () => {
      const { ReviewWorkflowsStageEE, ReviewWorkflowsAssigneeEE } = await import("./ReviewWorkflowsColumn-6zZJluSU-OxQnKLyn.mjs");
      return { ReviewWorkflowsStageEE, ReviewWorkflowsAssigneeEE };
    },
    {
      enabled: !!schema?.options?.reviewWorkflows
    }
  );
  const runHookWaterfall = useStrapiApp("ListViewPage", ({ runHookWaterfall: runHookWaterfall2 }) => runHookWaterfall2);
  const tableHeaders = React.useMemo(() => {
    const headers = runHookWaterfall(INJECT_COLUMN_IN_TABLE, {
      displayedHeaders,
      layout: list
    });
    const formattedHeaders = headers.displayedHeaders.map((header) => {
      return {
        ...header,
        label: typeof header.label === "string" ? header.label : formatMessage(header.label),
        name: `${header.name}${header.mainField ? `.${header.mainField}` : ""}`
      };
    });
    if (schema?.options?.draftAndPublish) {
      formattedHeaders.push({
        attribute: {
          type: "custom"
        },
        name: "status",
        label: formatMessage({
          id: getTranslation(`containers.list.table-headers.status`),
          defaultMessage: "status"
        }),
        searchable: false,
        sortable: false
      });
    }
    if (reviewWorkflowColumns) {
      formattedHeaders.push(
        ...reviewWorkflowColumns.map((column) => ({
          ...column,
          label: formatMessage(column.label)
        }))
      );
    }
    return formattedHeaders;
  }, [
    displayedHeaders,
    formatMessage,
    list,
    reviewWorkflowColumns,
    runHookWaterfall,
    schema?.options?.draftAndPublish
  ]);
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page.Loading, {});
  }
  if (error) {
    return /* @__PURE__ */ jsx(Page.Error, {});
  }
  const contentTypeTitle = schema?.info.displayName ?? "Untitled";
  const handleRowClick = (id) => () => {
    trackUsage("willEditEntryFromList");
    navigate({
      pathname: id.toString(),
      search: lib.stringify({ plugins: query.plugins })
    });
  };
  return /* @__PURE__ */ jsxs(Page.Main, { children: [
    /* @__PURE__ */ jsx(HelmetExport, { title: `${contentTypeTitle} | Strapi` }),
    /* @__PURE__ */ jsx(
      HeaderLayout,
      {
        primaryAction: canCreate ? /* @__PURE__ */ jsx(CreateButton, {}) : null,
        subtitle: formatMessage(
          {
            id: getTranslation("pages.ListView.header-subtitle"),
            defaultMessage: "{number, plural, =0 {# entries} one {# entry} other {# entries}} found"
          },
          { number: pagination?.total }
        ),
        title: contentTypeTitle,
        navigationAction: /* @__PURE__ */ jsx(BackButton, {})
      }
    ),
    /* @__PURE__ */ jsx(
      ActionLayout,
      {
        endActions: /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(InjectionZone, { area: "contentManager.listView.actions" }),
          /* @__PURE__ */ jsx(
            ViewSettingsMenu,
            {
              setHeaders: handleSetHeaders,
              resetHeaders: () => setDisplayedHeaders(list.layout),
              headers: displayedHeaders.map((header) => header.name)
            }
          )
        ] }),
        startActions: /* @__PURE__ */ jsxs(Fragment, { children: [
          list.settings.searchable && /* @__PURE__ */ jsx(
            SearchInput,
            {
              disabled: results.length === 0,
              label: formatMessage(
                { id: "app.component.search.label", defaultMessage: "Search for {target}" },
                { target: contentTypeTitle }
              ),
              placeholder: formatMessage({
                id: "global.search",
                defaultMessage: "Search"
              }),
              trackedEvent: "didSearch"
            }
          ),
          list.settings.filterable && schema ? /* @__PURE__ */ jsx(FiltersImpl, { disabled: results.length === 0, schema }) : null
        ] })
      }
    ),
    /* @__PURE__ */ jsx(ContentLayout, { children: /* @__PURE__ */ jsxs(Flex, { gap: 4, direction: "column", alignItems: "stretch", children: [
      /* @__PURE__ */ jsxs(Table.Root, { rows: results, headers: tableHeaders, isLoading, children: [
        /* @__PURE__ */ jsx(Table.ActionBar, {}),
        /* @__PURE__ */ jsxs(Table.Content, { children: [
          /* @__PURE__ */ jsxs(Table.Head, { children: [
            /* @__PURE__ */ jsx(Table.HeaderCheckboxCell, {}),
            tableHeaders.map((header) => /* @__PURE__ */ jsx(Table.HeaderCell, { ...header }, header.name))
          ] }),
          /* @__PURE__ */ jsx(Table.Loading, {}),
          /* @__PURE__ */ jsx(Table.Empty, { action: canCreate ? /* @__PURE__ */ jsx(CreateButton, { variant: "secondary" }) : null }),
          /* @__PURE__ */ jsx(Table.Body, { children: results.map((row) => {
            return /* @__PURE__ */ jsxs(
              Table.Row,
              {
                cursor: "pointer",
                onClick: handleRowClick(row.documentId),
                children: [
                  /* @__PURE__ */ jsx(Table.CheckboxCell, { id: row.id }),
                  tableHeaders.map(({ cellFormatter, ...header }) => {
                    if (header.name === "status") {
                      const { status } = row;
                      return /* @__PURE__ */ jsx(Table.Cell, { children: /* @__PURE__ */ jsx(DocumentStatus, { status, maxWidth: "min-content" }) }, header.name);
                    }
                    if (schema?.options?.reviewWorkflows) {
                      if (header.name === "strapi_stage") {
                        return /* @__PURE__ */ jsx(Table.Cell, { children: row.strapi_stage ? /* @__PURE__ */ jsx(
                          ReviewWorkflowsColumns.ReviewWorkflowsStageEE,
                          {
                            color: row.strapi_stage.color ?? lightTheme.colors.primary600,
                            name: row.strapi_stage.name
                          }
                        ) : /* @__PURE__ */ jsx(Typography, { textColor: "neutral800", children: "-" }) }, header.name);
                      }
                      if (header.name === "strapi_assignee") {
                        return /* @__PURE__ */ jsx(Table.Cell, { children: row.strapi_assignee ? /* @__PURE__ */ jsx(
                          ReviewWorkflowsColumns.ReviewWorkflowsAssigneeEE,
                          {
                            user: row.strapi_assignee
                          }
                        ) : /* @__PURE__ */ jsx(Typography, { textColor: "neutral800", children: "-" }) }, header.name);
                      }
                    }
                    if (["createdBy", "updatedBy"].includes(header.name.split(".")[0])) {
                      return /* @__PURE__ */ jsx(Table.Cell, { children: /* @__PURE__ */ jsx(Typography, { textColor: "neutral800", children: row[header.name.split(".")[0]] ? getDisplayName(row[header.name.split(".")[0]], formatMessage) : "-" }) }, header.name);
                    }
                    if (typeof cellFormatter === "function") {
                      return /* @__PURE__ */ jsx(Table.Cell, { children: cellFormatter(row, header, { collectionType, model }) }, header.name);
                    }
                    return /* @__PURE__ */ jsx(Table.Cell, { children: /* @__PURE__ */ jsx(
                      CellContent,
                      {
                        content: row[header.name.split(".")[0]],
                        rowId: row.documentId,
                        ...header
                      }
                    ) }, header.name);
                  }),
                  /* @__PURE__ */ jsx(ActionsCell, { onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsx(TableActions, { document: row }) })
                ]
              },
              row.id
            );
          }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(
        Pagination.Root,
        {
          ...pagination,
          onPageSizeChange: () => trackUsage("willChangeNumberOfEntriesPerPage"),
          children: [
            /* @__PURE__ */ jsx(Pagination.PageSize, {}),
            /* @__PURE__ */ jsx(Pagination.Links, {})
          ]
        }
      )
    ] }) })
  ] });
};
const ActionsCell = styled(Table.Cell)`
  display: flex;
  justify-content: flex-end;
`;
const CreateButton = ({ variant }) => {
  const { formatMessage } = useIntl();
  const { trackUsage } = useTracking();
  const [{ query }] = useQueryParams();
  return /* @__PURE__ */ jsx(
    Button,
    {
      variant,
      forwardedAs: Link,
      onClick: () => {
        trackUsage("willCreateEntry", { status: "draft" });
      },
      startIcon: /* @__PURE__ */ jsx(Plus, {}),
      style: { textDecoration: "none" },
      to: {
        pathname: "create",
        search: lib.stringify({ plugins: query.plugins })
      },
      children: formatMessage({
        id: getTranslation("HeaderLayout.button.label-add-entry"),
        defaultMessage: "Create new entry"
      })
    }
  );
};
const ProtectedListViewPage = () => {
  const { model } = useDoc();
  const [{ query }] = useQueryParams();
  const { permissions = [], isLoading, isError } = useSyncRbac(model, query, "editView");
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page.Loading, {});
  }
  if (isError) {
    return /* @__PURE__ */ jsx(Page.Error, {});
  }
  return /* @__PURE__ */ jsx(Page.Protect, { permissions, children: ({ permissions: permissions2 }) => /* @__PURE__ */ jsx(DocumentRBAC, { permissions: permissions2, children: /* @__PURE__ */ jsx(ListViewPage, {}) }) });
};
export {
  ListViewPage,
  ProtectedListViewPage
};
//# sourceMappingURL=ListViewPage-TJbHzMdV-Rx9tWeSb.mjs.map
