// Block editor: the Accessibility sidebar. Check now saves an autosave when the post has unsaved changes (as the // Preview button does), checks that preview and stores the result; with check on save on, a finished manual save // starts a check afterwards, so saving itself is never delayed. import { dispatch, select, subscribe, useSelect } from "@wordpress/data"; import { PluginSidebar, PluginSidebarMoreMenuItem } from "@wordpress/editor"; import { useCallback, useEffect } from "@wordpress/element"; import { __ } from "@wordpress/i18n"; import { registerPlugin } from "@wordpress/plugins"; import { waysillData } from "./data"; import { useChecker, useCheckOnSave } from "./ui/checker"; import { Results } from "./ui/results"; const SIDEBAR = "waysill-accessibility"; const ICON = "universal-access-alt"; /** The URL of the current content: an autosave first when there are unsaved changes. */ async function previewOfCurrentContent(): Promise { const editor = select("core/editor"); if (!editor.isEditedPostSaveable()) throw new Error(__("Add some content to the post first, then check again.", "waysill")); if (editor.isEditedPostDirty()) await dispatch("core/editor").autosave({ isPreview: true }); const url = select("core/editor").getEditedPostPreviewLink() ?? waysillData().previewUrl; if (!url) throw new Error(__("The post has no preview yet. Save a draft first.", "waysill")); return url; } function Sidebar() { const data = waysillData(); const { postId, previewUrl } = useSelect((s) => ({ postId: s("core/editor").getCurrentPostId(), previewUrl: s("core/editor").getEditedPostPreviewLink() }), []); const checker = useChecker(postId, useCallback(previewOfCurrentContent, [])); const [checkOnSave, setCheckOnSave] = useCheckOnSave(); const { run } = checker; useEffect(() => { if (!checkOnSave) return undefined; let wasSaving = false; return subscribe(() => { const editor = select("core/editor"); // Autosaves (including the one Check now makes) do not count as a save. const saving = editor.isSavingPost() && !editor.isAutosavingPost(); if (wasSaving && !saving && editor.didPostSaveRequestSucceed()) void run(); wasSaving = saving; }); }, [checkOnSave, run]); return ( <> {__("Accessibility", "waysill")}
); } registerPlugin("waysill", { render: Sidebar, icon: ICON });