import { useUIState } from "src/useUIState";
import { BlockLayout, BlockProps } from "./Block";
import { useMemo } from "react";
import { AsyncValueInput } from "components/Input";
import { focusElement } from "src/utils/focusElement";
import { useEntitySetContext } from "components/EntitySetProvider";
import { useEntity, useReplicache } from "src/replicache";
import { v7 } from "uuid";
import { elementId } from "src/utils/elementId";
import { CloseTiny } from "components/Icons/CloseTiny";
import { useLeafletPublicationData } from "components/PageSWRDataProvider";
import {
PubLeafletBlocksPoll,
PubLeafletPagesLinearDocument,
} from "lexicons/api";
import { getDocumentPages } from "src/utils/normalizeRecords";
import { ids } from "lexicons/api/lexicons";
/**
* PublicationPollBlock is used for editing polls in publication documents.
* It allows adding/editing options when the poll hasn't been published yet,
* but disables adding new options once the poll record exists (indicated by pollUri).
*/
export const PublicationPollBlock = (
props: BlockProps & {
areYouSure?: boolean;
setAreYouSure?: (value: boolean) => void;
},
) => {
let { data: publicationData, normalizedDocument } =
useLeafletPublicationData();
let isSelected = useUIState((s) =>
s.selectedBlocks.find((b) => b.value === props.entityID),
);
// Check if this poll has been published in a publication document
const isPublished = useMemo(() => {
if (!normalizedDocument) return false;
const pages = getDocumentPages(normalizedDocument);
if (!pages) return false;
// Search through all pages and blocks to find if this poll entity has been published
for (const page of pages) {
if (page.$type === "pub.leaflet.pages.linearDocument") {
const linearPage = page as PubLeafletPagesLinearDocument.Main;
for (const blockWrapper of linearPage.blocks || []) {
if (blockWrapper.block?.$type === ids.PubLeafletBlocksPoll) {
const pollBlock = blockWrapper.block as PubLeafletBlocksPoll.Main;
// Check if this poll's rkey matches our entity ID
const rkey = pollBlock.pollRef.uri.split("/").pop();
if (rkey === props.entityID) {
return true;
}
}
}
}
}
return false;
}, [normalizedDocument, props.entityID]);
return (