| 1 |
import { __ } from "@wordpress/i18n"; |
| 2 |
import { registerFormatType, slice, toHTMLString } from "@wordpress/rich-text"; |
| 3 |
import { RichTextToolbarButton } from "@wordpress/block-editor"; |
| 4 |
import { dispatch, select } from "@wordpress/data"; |
| 5 |
import { STORE_KEY } from "./store"; |
| 6 |
|
| 7 |
const FORMAT_NAME = "betterdocs/ai-edit"; |
| 8 |
|
| 9 |
const aiIcon = ( |
| 10 |
<svg width="20" height="20" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"> |
| 11 |
<path d="M12 3l1.9 4.6L18.5 9.5 13.9 11.4 12 16l-1.9-4.6L5.5 9.5l4.6-1.9L12 3zm7 10l.95 2.3L22.25 16.25l-2.3.95L19 19.5l-.95-2.3L15.75 16.25l2.3-.95L19 13zM5 15l.7 1.7 1.7.7-1.7.7L5 19.8l-.7-1.7L2.6 17.4l1.7-.7L5 15z" fill="currentColor"/> |
| 12 |
</svg> |
| 13 |
); |
| 14 |
|
| 15 |
const Edit = ({ value, isActive, onChange }) => { |
| 16 |
const onClick = () => { |
| 17 |
const start = typeof value.start === "number" ? value.start : 0; |
| 18 |
const end = typeof value.end === "number" ? value.end : start; |
| 19 |
|
| 20 |
if (end <= start) { |
| 21 |
return; |
| 22 |
} |
| 23 |
|
| 24 |
const sliced = slice(value, start, end); |
| 25 |
const plain = sliced.text || ""; |
| 26 |
const html = toHTMLString({ value: sliced }); |
| 27 |
|
| 28 |
const selectedBlock = select("core/block-editor").getSelectedBlock(); |
| 29 |
|
| 30 |
dispatch(STORE_KEY).openModal({ |
| 31 |
selectionType: "inline", |
| 32 |
selectionText: plain, |
| 33 |
selectionHtml: html, |
| 34 |
blockClientId: selectedBlock ? selectedBlock.clientId : null, |
| 35 |
inlineContext: { |
| 36 |
start, |
| 37 |
end, |
| 38 |
formatName: FORMAT_NAME, |
| 39 |
}, |
| 40 |
}); |
| 41 |
}; |
| 42 |
|
| 43 |
return ( |
| 44 |
<RichTextToolbarButton |
| 45 |
icon={aiIcon} |
| 46 |
title={__("Edit with BetterDocs AI", "betterdocs")} |
| 47 |
onClick={onClick} |
| 48 |
isActive={isActive} |
| 49 |
/> |
| 50 |
); |
| 51 |
}; |
| 52 |
|
| 53 |
registerFormatType(FORMAT_NAME, { |
| 54 |
title: __("BetterDocs AI", "betterdocs"), |
| 55 |
tagName: "span", |
| 56 |
className: "betterdocs-ai-edit-marker", |
| 57 |
edit: Edit, |
| 58 |
}); |
| 59 |
|