Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/content embed: add support for an editable flag
Adorian Doran3361e31f62cc
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.tsindex 91d4e6a3b1..994f66ade8 100644--- a/apps/client/src/menus/link_context_menu.spec.ts+++ b/apps/client/src/menus/link_context_menu.spec.ts@@ -506,6 +506,27 @@ describe("openContextMenu", () => {expect(execute).not.toHaveBeenCalled();});+ it("offers Editable above the size, for content that has an editable mode", async () => {+ state = { ...state, isEditable: true, isEditableToggleable: true };+ const items = await openOn(editable.querySelector("a"));++ expect(items.slice(6, 9)).toMatchObject([+ { kind: "separator" },+ {+ title: "link_context_menu.editable",+ uiIcon: "bx bx-edit-alt",+ trailingIcon: CHECK+ },+ { title: "link_context_menu.include_size" }+ ]);+ expect(items).toHaveLength(14);+ expect(pick(items[7])).toEqual([ [ "toggleContentEmbedEditable", undefined ] ]);++ state = { ...state, isEditable: false };+ expect((await openOn(editable.querySelector("a")))[7])+ .toMatchObject({ title: "link_context_menu.editable", trailingIcon: undefined });+ });+it("appends the commands of an embedded note, its conversion in a group of its own", async () => {embed().removeAttribute("data-attachment-id");embed().setAttribute("data-note-id", "n1");diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.tsindex b70ce34f21..f5a7d19a7c 100644--- a/apps/client/src/menus/link_context_menu.ts+++ b/apps/client/src/menus/link_context_menu.ts@@ -236,7 +236,10 @@ function getMenuEmbed(e: LinkMenuOrigin, editor: CKTextEditor): MenuEmbed | nullreturn state ? { editor, element, state } : null;}-/** The commands that the toolbar of an embed offers, with what each shows checked. */+/**+ * The commands that the toolbar of an embed offers, with what each shows checked. Editable is+ * offered only for content that has an editable mode.+ */function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {const { editor, state } = embed;const sizeItems = editor.plugins.get("ContentEmbed").getBoxSizes()@@ -245,8 +248,15 @@ function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {trailingIcon: value === state.boxSize ? CHECK_ICON : undefined,handler: () => runEmbedCommand(embed, "contentEmbedBoxSize", { value })}));+ const editableItems: MenuItem<CommandNames>[] = state.isEditableToggleable ? [ {+ title: t("link_context_menu.editable"),+ uiIcon: "bx bx-edit-alt",+ trailingIcon: state.isEditable ? CHECK_ICON : undefined,+ handler: () => runEmbedCommand(embed, "toggleContentEmbedEditable")+ } ] : [];return [+ ...editableItems,submenuItem({title: t("link_context_menu.include_size"),uiIcon: "bx bx-expand-vertical"diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 42138e5a0c..57786d779a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3064,7 +3064,8 @@"convert_embed_to_link": "Convert to link","include_size": "Size","show_title": "Show title",- "show_caption": "Show caption"+ "show_caption": "Show caption",+ "editable": "Editable"},"electron_integration": {"desktop-application": "Desktop Application",@@ -4416,7 +4417,8 @@"tiny": "Tiny","show-title": "Show title","more-actions": "More actions",- "insert-drawing-canvas": "Insert drawing canvas"+ "insert-drawing-canvas": "Insert drawing canvas",+ "editable": "Editable"},"task-state-dropped-title": "Invalid task states","task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts b/apps/client/src/widgets/type_widgets/text/content_embed_tools.tsindex d7a69f281c..ac4b36e82e 100644--- a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts@@ -31,6 +31,11 @@ export interface ContentEmbedToolProvider {subscribe(callback: () => void): () => void;/** The items of the embed toolbar to hide. The menu of the embed still offers them. */hiddenToolbarItems?: readonly ContentEmbedToolbarItem[];+ /**+ * Whether the content has an editable mode, which the toolbar and the menu of the embed then+ * turn on and off. The embed carries `data-editable="true"` while it is on.+ */+ hasEditableFlag?: boolean;}const providers = new Map<HTMLElement, ContentEmbedToolProvider>();diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 02084411bc..426ce0d723 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -63,6 +63,11 @@ declare global {subscribe(callback: () => void): () => void;/** The items of the embed toolbar to hide. The menu of the embed still offers them. */hiddenToolbarItems?: readonly ContentEmbedToolbarItem[];+ /**+ * Whether the content has an editable mode, which the toolbar and the menu of the embed+ * then turn on and off. The embed carries `data-editable="true"` while it is on.+ */+ hasEditableFlag?: boolean;}interface EditorComponent extends Component {diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.tsindex 8b324e7dd1..42b0a4cdfd 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts@@ -15,6 +15,7 @@ import {Widget,type ModelElement} from "ckeditor5";+import bxEditAlt from "boxicons/svg/regular/bx-edit-alt.svg?raw";import bxWindowAlt from "boxicons/svg/regular/bx-window-alt.svg?raw";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -29,6 +30,7 @@ import ContentEmbed, {CONVERT_LINK_TO_EMBED_COMMAND,CONTENT_EMBED_MENU,TOGGLE_CAPTION_COMMAND_NAME,+ TOGGLE_EDITABLE_COMMAND_NAME,TOGGLE_TITLE_COMMAND_NAME} from "./content_embed.js";@@ -618,7 +620,7 @@ describe("ContentEmbed", () => {const realGet = editor.commands.get.bind(editor.commands);const absent: string[] = [COMMAND_NAME, CONVERT_EMBED_TO_LINK_COMMAND, TOGGLE_CAPTION_COMMAND_NAME,- TOGGLE_TITLE_COMMAND_NAME+ TOGGLE_TITLE_COMMAND_NAME, TOGGLE_EDITABLE_COMMAND_NAME];const getSpy = vi.spyOn(editor.commands, "get")@@ -633,6 +635,8 @@ describe("ContentEmbed", () => {expect((caption as unknown as { label: string }).label).toBe("Toggle caption on");const title = editor.ui.componentFactory.create(TOGGLE_TITLE_COMMAND_NAME);expect((title as unknown as { label: string }).label).toBe("Show title");+ const editable = editor.ui.componentFactory.create(TOGGLE_EDITABLE_COMMAND_NAME);+ expect((editable as unknown as { label: string }).label).toBe("Editable");const menu = editor.ui.componentFactory.create(CONTENT_EMBED_MENU);expect((menu as unknown as { label: string }).label).toBe("More actions");} finally {@@ -870,17 +874,18 @@ describe("ContentEmbed with attachments", () => {const states = [ embed, note, tiny, unsized ].map((wrapper) => plugin.getEmbedStateAt(wrapper));+ const notEditable = { isEditable: false, isEditableToggleable: false };expect(states).toEqual([ {- boxSize: "small", isTitleShown: true, isTitleToggleable: true,+ ...notEditable, boxSize: "small", isTitleShown: true, isTitleToggleable: true,hasCaption: false, isCaptionToggleable: true, isConvertibleToLink: true}, {- boxSize: "medium", isTitleShown: false, isTitleToggleable: true,+ ...notEditable, boxSize: "medium", isTitleShown: false, isTitleToggleable: true,hasCaption: true, isCaptionToggleable: true, isConvertibleToLink: true}, {- boxSize: "tiny", isTitleShown: true, isTitleToggleable: false,+ ...notEditable, boxSize: "tiny", isTitleShown: true, isTitleToggleable: false,hasCaption: false, isCaptionToggleable: false, isConvertibleToLink: true}, {- boxSize: null, isTitleShown: true, isTitleToggleable: true,+ ...notEditable, boxSize: null, isTitleShown: true, isTitleToggleable: true,hasCaption: false, isCaptionToggleable: true, isConvertibleToLink: true} ]);const paragraph = editor.editing.view.getDomRoot()?.querySelector("p") ?? embed;@@ -1284,6 +1289,161 @@ describe("ContentEmbed title", () => {});});+describe("ContentEmbed editable flag", () => {+ const EDITABLE = "<figure class=\"include-note\" data-note-id=\"n1\" data-box-size=\"medium\""+ + " data-hide-title=\"true\" data-editable=\"true\"> </figure>";+ let editor: ClassicEditor;+ let loadEmbeddedNote: ReturnType<typeof vi.fn>;+ let getContentEmbedTools: ReturnType<typeof vi.fn>;++ beforeEach(async () => {+ loadEmbeddedNote = vi.fn();+ getContentEmbedTools = vi.fn(() => ({ hasEditableFlag: true }));+ installGlobMock({+ getComponentByEl: () => ({ loadEmbeddedNote, getContentEmbedTools })+ });++ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ]);+ });++ function getCommand() {+ const command = editor.commands.get(TOGGLE_EDITABLE_COMMAND_NAME);+ if (!command) {+ throw new Error("Expected the editable command.");+ }+ return command;+ }++ function getRenderedEmbed() {+ const embed = editor.editing.view.getDomRoot()?.querySelector("figure.include-note");+ if (!embed) {+ throw new Error("Expected a rendered embed.");+ }+ return embed;+ }++ it("loads and saves the flag, and marks the embed it renders", () => {+ editor.setData(EDITABLE);++ expect(getModelData(editor.model, { withoutSelection: true })).toBe(+ "<contentEmbed boxSize=\"medium\" editable=\"true\" hideTitle=\"true\" noteId=\"n1\">"+ + "</contentEmbed>"+ );+ expect(editor.getData()).toBe(EDITABLE);+ expect(getRenderedEmbed().getAttribute("data-editable")).toBe("true");++ for (const data of [+ EDITABLE.replace(" data-editable=\"true\"", ""),+ EDITABLE.replace("data-editable=\"true\"", "data-editable=\"false\"")+ ]) {+ editor.setData(data);+ expect(getModelData(editor.model, { withoutSelection: true }))+ .not.toContain("editable");+ expect(editor.getData()).not.toContain("data-editable");+ expect(getRenderedEmbed().hasAttribute("data-editable")).toBe(false);+ }+ });++ it("turns editing on and off as one undo step, keeping the rendered content", () => {+ insertContentEmbed(editor, "n1", "medium");+ const wrapper = getRenderedEmbed().querySelector(".include-note-wrapper");+ const command = getCommand();+ expect([ command.isEnabled, command.value ]).toEqual([ true, false ]);++ editor.execute(TOGGLE_EDITABLE_COMMAND_NAME);+ expect(command.value).toBe(true);+ expect(getRenderedEmbed().getAttribute("data-editable")).toBe("true");+ expect(editor.getData()).toContain("data-editable=\"true\"");+ expect(editor.model.document.selection.getSelectedElement()?.name).toBe("contentEmbed");++ editor.execute(TOGGLE_EDITABLE_COMMAND_NAME);+ expect(command.value).toBe(false);+ expect(getRenderedEmbed().hasAttribute("data-editable")).toBe(false);+ expect(editor.getData()).not.toContain("data-editable");++ editor.execute("undo");+ expect(command.value).toBe(true);+ expect(getRenderedEmbed().querySelector(".include-note-wrapper")).toBe(wrapper);+ expect(loadEmbeddedNote).toHaveBeenCalledTimes(1);+ });++ it("is offered only for content that opts in, once its content declares it", () => {+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");+ expect(getCommand().isEnabled).toBe(false);++ // The content of an embed renders after the embed, and declares its tools then.+ getContentEmbedTools.mockReturnValue(null);+ insertContentEmbed(editor, "n1", "medium");+ expect(getCommand().isEnabled).toBe(false);+ getContentEmbedTools.mockReturnValue({ hasEditableFlag: true });+ editor.ui.update();+ expect(getCommand().isEnabled).toBe(true);+ expect(getContentEmbedTools).toHaveBeenLastCalledWith(getRenderedEmbed());++ getContentEmbedTools.mockReturnValue({ hasEditableFlag: false });+ editor.ui.update();+ expect(getCommand().isEnabled).toBe(false);++ installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote }) });+ editor.ui.update();+ expect(getCommand().isEnabled).toBe(false);+ });++ it("offers an Editable button that shows only while the command is enabled", () => {+ const button = editor.ui.componentFactory.create(TOGGLE_EDITABLE_COMMAND_NAME);+ if (!(button instanceof ButtonView) || button instanceof SwitchButtonView) {+ throw new Error("Expected a button.");+ }+ const focus = vi.spyOn(editor.editing.view, "focus");+ insertContentEmbed(editor, "n1", "medium");+ expect([ button.icon, button.withText, button.tooltip, button.isToggleable ])+ .toEqual([ bxEditAlt, false, true, true ]);+ expect([ button.label, button.isOn, button.isEnabled, button.isVisible ])+ .toEqual([ "Editable", false, true, true ]);++ button.fire("execute");+ expect([ button.isOn, getCommand().value ]).toEqual([ true, true ]);+ expect(focus).toHaveBeenCalled();++ getContentEmbedTools.mockReturnValue(null);+ editor.ui.update();+ expect([ button.isEnabled, button.isVisible ]).toEqual([ false, false ]);+ });++ it("describes the flag of the embed an element is part of", () => {+ editor.setData(EDITABLE + "<figure class=\"include-note\" data-note-id=\"n2\"></figure>");+ const [ editable, readOnly ] =+ editor.editing.view.getDomRoot()?.querySelectorAll("div.include-note-wrapper") ?? [];+ const plugin = editor.plugins.get(ContentEmbed);+ if (!editable || !readOnly) {+ throw new Error("Expected two rendered embeds.");+ }++ expect(plugin.getEmbedStateAt(editable))+ .toMatchObject({ isEditable: true, isEditableToggleable: true });+ expect(plugin.getEmbedStateAt(readOnly))+ .toMatchObject({ isEditable: false, isEditableToggleable: true });++ getContentEmbedTools.mockReturnValue(null);+ expect(plugin.getEmbedStateAt(editable))+ .toMatchObject({ isEditable: true, isEditableToggleable: false });+ });++ it("changes nothing when no embed is selected", () => {+ editor.setData(EDITABLE + "<p>after</p>");+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");+ const before = editor.getData();++ // The decorated `Command#execute()` skips a disabled command, so the command is forced+ // enabled to run `execute()` with no embed selected.+ const command = getCommand();+ command.isEnabled = true;+ command.execute();++ expect(editor.getData()).toBe(before);+ });+});+describe("ContentEmbed resizing", () => {const RESIZED = "<figure class=\"include-note\""+ " style=\"--include-note-height:12.5em;--include-note-width:30em;\""diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex 4315403733..b8f16b79cd 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -21,6 +21,7 @@ import {Widget,type Observable} from 'ckeditor5';+import editIcon from 'boxicons/svg/regular/bx-edit-alt.svg?raw';import windowIcon from 'boxicons/svg/regular/bx-window-alt.svg?raw';import noteIcon from '../../icons/note.svg?raw';import { getAttachmentId, getNoteId } from '../referencelink.js';@@ -32,6 +33,7 @@ export const CONVERT_LINK_TO_EMBED_COMMAND = 'convertLinkToEmbed';export const CONVERT_EMBED_TO_LINK_COMMAND = 'convertEmbedToLink';export const TOGGLE_CAPTION_COMMAND_NAME = 'toggleContentEmbedCaption';export const TOGGLE_TITLE_COMMAND_NAME = 'toggleContentEmbedTitle';+export const TOGGLE_EDITABLE_COMMAND_NAME = 'toggleContentEmbedEditable';/** The toolbar button that opens the context menu of an embed whose title is hidden. */export const CONTENT_EMBED_MENU = 'contentEmbedMenu';@@ -42,8 +44,20 @@ export type BoxSizeValue = typeof BOX_SIZES[number];/** The box sizes that can be resized. Tiny and Full fit their content. */const RESIZABLE_BOX_SIZES: unknown[] = [ 'small', 'medium', 'expandable' ];+/** The flags of an embed, each saved as `"true"` in a `data-*` attribute while it is on. */+const FLAG_ATTRIBUTES = [+ [ 'hideTitle', 'data-hide-title' ],+ [ 'editable', 'data-editable' ]+] as const;++type EmbedFlag = typeof FLAG_ATTRIBUTES[number][0];+/** What the toolbar of an embed shows of it, for a menu offering the same commands. */export interface ContentEmbedState {+ /** Whether the content can be edited in place. */+ isEditable: boolean;+ /** Whether the content has an editable mode, which its content type opts in to. */+ isEditableToggleable: boolean;boxSize: BoxSizeValue | null;/** Whether the title shows, which a Tiny or an Expandable embed always does. */isTitleShown: boolean;@@ -135,6 +149,8 @@ export default class ContentEmbed extends Plugin {const isTitleToggleable = isEmbedTitleToggleable( embed );return {+ isEditable: !!embed.getAttribute( 'editable' ),+ isEditableToggleable: isEmbedEditableToggleable( editor, embed ),boxSize: embed.getAttribute( 'boxSize' ) as BoxSizeValue | undefined ?? null,isTitleShown: !isTitleToggleable || !embed.getAttribute( 'hideTitle' ),isTitleToggleable,@@ -238,6 +254,31 @@ class ContentEmbedUI extends Plugin {return buttonView;} );+ editor.ui.componentFactory.add( TOGGLE_EDITABLE_COMMAND_NAME, locale => {+ const command = editor.commands.get( TOGGLE_EDITABLE_COMMAND_NAME );+ const buttonView = new ButtonView( locale );++ buttonView.set( {+ label: t( 'Editable' ),+ icon: editIcon,+ tooltip: true,+ isToggleable: true+ } );++ // Shown only for content that has an editable mode.+ if ( command ) {+ buttonView.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );+ buttonView.bind( 'isVisible' ).to( command, 'isEnabled' );+ }++ this.listenTo( buttonView, 'execute', () => {+ editor.execute( TOGGLE_EDITABLE_COMMAND_NAME );+ editor.editing.view.focus();+ } );++ return buttonView;+ } );+editor.ui.componentFactory.add( TOGGLE_TITLE_COMMAND_NAME, locale => {const command = editor.commands.get( TOGGLE_TITLE_COMMAND_NAME );const buttonView = new ButtonView( locale );@@ -326,6 +367,8 @@ class ContentEmbedEditing extends Plugin {commands.add( CONVERT_EMBED_TO_LINK_COMMAND, new ConvertEmbedToLinkCommand( editor ) );commands.add( TOGGLE_CAPTION_COMMAND_NAME, new ToggleContentEmbedCaptionCommand( editor ) );commands.add( TOGGLE_TITLE_COMMAND_NAME, new ToggleContentEmbedTitleCommand( editor ) );+ commands.add(+ TOGGLE_EDITABLE_COMMAND_NAME, new ToggleContentEmbedEditableCommand( editor ) );editor.model.document.registerPostFixer( writer => this.removeTinyCaptions( writer ) );}@@ -357,8 +400,8 @@ class ContentEmbedEditing extends Plugin {// An embed shows either a note or an attachment. An embed that// `FileUploadEditing` is uploading carries the upload attributes instead of its id.allowAttributes: [- 'noteId', 'attachmentId', 'boxSize', 'hideTitle', 'uploadId', 'uploadStatus',- 'uploadFileName'+ 'noteId', 'attachmentId', 'boxSize', 'hideTitle', 'editable', 'uploadId',+ 'uploadStatus', 'uploadFileName'],// Allow in places where other blocks are allowed (e.g. directly in the root).@@ -393,9 +436,7 @@ class ContentEmbedEditing extends Plugin {return modelWriter.createElement( 'contentEmbed', {...embedded,boxSize: viewElement.getAttribute( 'data-box-size' ),- ...( viewElement.getAttribute( 'data-hide-title' ) === 'true'- ? { hideTitle: true }- : {} )+ ...getFlagsOfView( viewElement )} );},// Embeds saved before captions existed are `<section>` elements.@@ -411,7 +452,7 @@ class ContentEmbedEditing extends Plugin {class: 'include-note',...getEmbeddedEntityAttributes( modelElement ),'data-box-size': modelElement.getAttribute( 'boxSize' ),- ...getTitleAttributes( modelElement )+ ...getFlagAttributes( modelElement )} );}} );@@ -425,7 +466,7 @@ class ContentEmbedEditing extends Plugin {class: 'include-note box-size-' + boxSize,...getEmbeddedEntityAttributes( modelElement ),'data-box-size': boxSize,- ...getTitleAttributes( modelElement )+ ...getFlagAttributes( modelElement )} );const embedWrapper = viewWriter.createUIElement( 'div', {@@ -482,20 +523,23 @@ class ContentEmbedEditing extends Plugin {}} );- // Shows or hides the title without drawing the content again.- dispatcher.on( 'attribute:hideTitle:contentEmbed', ( _evt, data, conversionApi ) => {- const viewElement = conversionApi.mapper.toViewElement( data.item as ModelElement );- /* v8 ignore next 3 -- converted after the embed itself, so always mapped */- if ( !viewElement ) {- return;- }+ // Marks the view of the embed without drawing the content again. Content with an+ // editable mode reads `data-editable` from the embed.+ for ( const [ flag, dataAttribute ] of FLAG_ATTRIBUTES ) {+ dispatcher.on( `attribute:${ flag }:contentEmbed`, ( _evt, data, api ) => {+ const viewElement = api.mapper.toViewElement( data.item as ModelElement );+ /* v8 ignore next 3 -- converted after the embed itself, so always mapped */+ if ( !viewElement ) {+ return;+ }- if ( data.attributeNewValue ) {- conversionApi.writer.setAttribute( 'data-hide-title', 'true', viewElement );- } else {- conversionApi.writer.removeAttribute( 'data-hide-title', viewElement );- }- } );+ if ( data.attributeNewValue ) {+ api.writer.setAttribute( dataAttribute, 'true', viewElement );+ } else {+ api.writer.removeAttribute( dataAttribute, viewElement );+ }+ } );+ }// Redraws the content in place when an upload ends. A converter that lists// `attributes` also reconverts the embed on every change of its children, such as@@ -707,19 +751,50 @@ export class ToggleContentEmbedTitleCommand extends Command {}override execute() {+ toggleSelectedEmbedFlag( this.editor, 'hideTitle' );+ }+}++/**+ * Turns the editing of the selected embed's content on and off, for content whose type has an+ * editable mode.+ */+export class ToggleContentEmbedEditableCommand extends Command {+ /** Whether the content can be edited. */+ declare value: boolean;++ constructor( editor: Editor ) {+ super( editor );+ // Content declares its editable mode once it renders, which changes nothing in the model.+ this.listenTo( editor.ui, 'update', () => this.refresh(), { priority: 'high' } );+ }++ override refresh() {const embed = getSelectedContentEmbed( this.editor );- if ( !embed ) {- return;- }- this.editor.model.change( writer => {- if ( embed.getAttribute( 'hideTitle' ) ) {- writer.removeAttribute( 'hideTitle', embed );- } else {- writer.setAttribute( 'hideTitle', true, embed );- }- } );+ this.isEnabled = !!embed && isEmbedEditableToggleable( this.editor, embed );+ this.value = !!embed?.getAttribute( 'editable' );+ }++ override execute() {+ toggleSelectedEmbedFlag( this.editor, 'editable' );+ }+}++/** Sets the flag of the selected embed when it is off, and removes it when it is on. */+function toggleSelectedEmbedFlag( editor: Editor, flag: EmbedFlag ) {+ const embed = getSelectedContentEmbed( editor );+ if ( !embed ) {+ return;}++ editor.model.change( writer => {+ if ( embed.getAttribute( flag ) ) {+ writer.removeAttribute( flag, embed );+ } else {+ writer.setAttribute( flag, true, embed );+ }+ } );}/** Replaces a reference link with an embed of the note or attachment it points to, in its place. */@@ -845,6 +920,11 @@ function isEmbedTitleToggleable( embed: ModelElement ) {return boxSize !== 'tiny' && boxSize !== 'expandable';}+/** Whether the content of `embed` has an editable mode, which its content type opts in to. */+function isEmbedEditableToggleable( editor: Editor, embed: ModelElement ) {+ return !!getEmbedTools( editor, embed )?.hasEditableFlag;+}+/** Whether `embed` can have a caption. A Tiny embed has none. */function isEmbedCaptionToggleable( editor: Editor, embed: ModelElement ) {return embed.getAttribute( 'boxSize' ) !== 'tiny'@@ -905,9 +985,18 @@ function getEmbeddedEntityAttributes( element: ModelElement ): Record<string, streturn noteId ? { 'data-note-id': noteId } : {};}-/** The `data-hide-title` attribute of an embed whose title is hidden. */-function getTitleAttributes( element: ModelElement ): Record<string, string> {- return element.getAttribute( 'hideTitle' ) ? { 'data-hide-title': 'true' } : {};+/** The `data-*` attributes of the flags that are on in `element`. */+function getFlagAttributes( element: ModelElement ): Record<string, string> {+ return Object.fromEntries( FLAG_ATTRIBUTES+ .filter( ( [ flag ] ) => element.getAttribute( flag ) )+ .map( ( [ , dataAttribute ] ) => [ dataAttribute, 'true' ] ) );+}++/** The flags that the `data-*` attributes of a saved embed turn on. */+function getFlagsOfView( viewElement: ViewElement ): Partial<Record<EmbedFlag, true>> {+ return Object.fromEntries( FLAG_ATTRIBUTES+ .filter( ( [ , dataAttribute ] ) => viewElement.getAttribute( dataAttribute ) === 'true' )+ .map( ( [ flag ] ) => [ flag, true ] ) );}/** Whether the content of the selected embed, whose buttons are `tools`, hides `name`. */@@ -934,19 +1023,27 @@ function bindToolbarItemVisibility(/** The buttons that the content of the selected embed adds to its toolbar, or `null`. */function getSelectedEmbedTools( editor: Editor ): ContentEmbedToolProvider | null {- const embed = getSelectedContentEmbedDom( editor );- if ( !embed ) {+ return getEmbedTools( editor, getSelectedContentEmbed( editor ) );+}++/** The buttons that the content of `embed` adds to its toolbar, or `null`. */+function getEmbedTools(+ editor: Editor,+ embed: ModelElement | null+): ContentEmbedToolProvider | null {+ const domElement = getContentEmbedDom( editor, embed );+ if ( !domElement ) {return null;}const component: EditorComponent | undefined =glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );- return component?.getContentEmbedTools?.( embed ) ?? null;+ return component?.getContentEmbedTools?.( domElement ) ?? null;}/** Has the host open the context menu of the selected embed, below `anchor`. */function openContentEmbedMenu( editor: Editor, anchor: HTMLElement | null ) {- const domElement = getSelectedContentEmbedDom( editor );+ const domElement = getContentEmbedDom( editor, getSelectedContentEmbed( editor ) );if ( !anchor || !domElement ) {return;}@@ -955,9 +1052,8 @@ function openContentEmbedMenu( editor: Editor, anchor: HTMLElement | null ) {component.openContentEmbedMenu?.( domElement, anchor );}-/** The rendered `<figure>` of the selected embed, or `null`. */-function getSelectedContentEmbedDom( editor: Editor ): HTMLElement | null {- const embed = getSelectedContentEmbed( editor );+/** The rendered `<figure>` of `embed`, or `null`. */+function getContentEmbedDom( editor: Editor, embed: ModelElement | null ): HTMLElement | null {const viewElement = embed && editor.editing.mapper.toViewElement( embed );const domElement = viewElement && editor.editing.view.domConverter.mapViewToDom( viewElement );return domElement instanceof HTMLElement ? domElement : null;@@ -1185,5 +1281,6 @@ declare module 'ckeditor5' {interface CommandsMap {toggleContentEmbedCaption: ToggleContentEmbedCaptionCommand;toggleContentEmbedTitle: ToggleContentEmbedTitleCommand;+ toggleContentEmbedEditable: ToggleContentEmbedEditableCommand;}}diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.tsindex 1a4ac4a159..71dbd8ced4 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts@@ -8,6 +8,7 @@ import ContentEmbed, {CONVERT_EMBED_TO_LINK_COMMAND,CONTENT_EMBED_MENU,TOGGLE_CAPTION_COMMAND_NAME,+ TOGGLE_EDITABLE_COMMAND_NAME,TOGGLE_TITLE_COMMAND_NAME} from "./content_embed.js";import ContentEmbedBoxSizeDropdown from "./content_embed_box_size_dropdown.js";@@ -101,12 +102,13 @@ describe("ContentEmbedToolbar", () => {expect(requires).toContain(ContentEmbedTools);});- it("offers the content's tools, the box size, the title, the caption, the link conversion and the menu", () => {+ it("offers the Editable toggle, the content's tools, then the embed's own items", () => {const repository = editor.plugins.get(WidgetToolbarRepository) as unknown as {_toolbarDefinitions: Map<string, { itemsConfig: string[] }>;};expect(repository._toolbarDefinitions.get("contentEmbed")?.itemsConfig).toEqual([+ TOGGLE_EDITABLE_COMMAND_NAME,CONTENT_EMBED_TOOLS,"contentEmbedBoxSizeDropdown",TOGGLE_TITLE_COMMAND_NAME,diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.tsindex 500c558897..0e5000459d 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts@@ -3,6 +3,7 @@ import ContentEmbed, {CONVERT_EMBED_TO_LINK_COMMAND,CONTENT_EMBED_MENU,TOGGLE_CAPTION_COMMAND_NAME,+ TOGGLE_EDITABLE_COMMAND_NAME,TOGGLE_TITLE_COMMAND_NAME} from "./content_embed.js";import ContentEmbedBoxSizeDropdown, {@@ -24,6 +25,7 @@ export default class ContentEmbedToolbar extends Plugin {widgetToolbarRepository.register("contentEmbed", {items: [+ TOGGLE_EDITABLE_COMMAND_NAME,CONTENT_EMBED_TOOLS,CONTENT_EMBED_BOX_SIZE_DROPDOWN,TOGGLE_TITLE_COMMAND_NAME,