How do I get toolbar available items in CKEDITOR 5? - ckeditor5

I wanted to configure the toolbar in CKEDITOR 5. I took a look at the documentation.
https://ckeditor5.github.io/docs/nightly/ckeditor5/latest/builds/guides/integration/configuration.html
Yet, the only script related to my question is:
Array.from( editor.ui.componentFactory.names );
It is way too difficult for a frontend programmer to understand. Where do I put this script? How do I output the results? Is there a detailed tutorial?
Matter fact, it would be nice if CKEDITOR simply put the available items in the documentation. That will save a hell lot of troubles.
Thanks!

You can put this code right in the body of code samples which you can find e.g. in CKEditor 5 Build's Basic API guide. For example:
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
console.log( Array.from( editor.ui.componentFactory.names() ) );
} )
.catch( error => {
console.error( error );
} );
As #Szymon Cofalik mentioned in his answer – there's no single list of buttons which are available in all builds. CKEditor 5 builds may differ not only visually – they may also contain different plugins and hence different buttons. So, using that code snippet is the safest and future-proof solution.

you can use console.log( Array.from( editor.ui.componentFactory.names() ) ); which will give you:
["undo", "redo", "bold", "italic", "blockQuote", "ckfinder", "imageTextAlternative", "imageUpload", "heading", "imageStyle:full", "imageStyle:side", "link", "numberedList", "bulletedList", "mediaEmbed", "insertTable", "tableColumn", "tableRow", "mergeTableCells"]

Example code you can use to list available toolbar
var editor = ClassicEditor
.create(document.querySelector('#editor'), {
toolbar: ['headings', 'bold', 'italic', 'link', 'bulletedList', 'numberedList'],
heading: {
options: [
{modelElement: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph'},
{modelElement: 'heading1', viewElement: 'h1', title: 'Heading 1', class: 'ck-heading_heading1'},
{modelElement: 'heading2', viewElement: 'h2', title: 'Heading 2', class: 'ck-heading_heading2'},
{modelElement: 'heading', viewElement: 'h3', title: 'Heading 3', class: 'ck-heading_heading3'}
]
}
})
.then(function (editor) {
console.log(Array.from(editor.ui.componentFactory.names()));
});

For anyone coming here wondering how to make use of the Array.from(editor.ui.componentFactory.names()) solution (as described in the other answers) in Angular (e.g. Angular 8), here is a description. If you try to do it in ngOnInit or ngAfterViewInit, it is too early and you will get something like Cannot read property 'ui' of null. You need to listen for the ready event from the ckeditor and query the names at that point as follows.
In your component template code, give the editor an id and listen for the ready event:
<ckeditor
#editor
[editor]="Editor"
[config]="config"
(ready)="onEditorReady($event)">
</ckeditor>
Then in your component typescript code, add a #ViewChild annotation and implement onEditorReady as follows:
#ViewChild('editor', {static: false})
editorComponent: CKEditorComponent;
onEditorReady(event: any): void {
const toolbarItems = Array.from(this.editorComponent.editorInstance.ui.componentFactory.names());
console.log('Available toolbar items: ' + toolbarItems.join(', '));
}
You will then see something like this in the console:
Available toolbar items: undo, redo, bold, italic, blockQuote,
ckfinder, imageTextAlternative, imageUpload, heading, imageStyle:full,
imageStyle:side, indent, outdent, link, numberedList, bulletedList,
mediaEmbed, insertTable, tableColumn, tableRow, mergeTableCells

It is difficult to keep plugin names in one place in documentation because:
There are multiple builds which differs,
New plugins are developed and added.
If you want to check what toolbar items are available in the build you are currently using, open developer's console in the browser you are using and execute the quoted line of code
Array.from( editor.ui.componentFactory.names );
Of course, editor has to be the editor instance.
I hope this answers your question.
EDIT: Creating editor is described in the documentation too. But you have to assign editor instance to editor variable.
For example:
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
window.editor = editor;
// Or alternatively you could paste that line here and look at console.
} );

Adding to #DestinyB answer - perhaps a simpler solution for Vue - just listen for #ready="onReady" on the ckeditor component, and in the onReady method:
onReady(event) {
console.log(Array.from(event.ui.componentFactory.names()));
},

Adding to #user2846469 Response, It can be achieved in vue.js simply by the sample below;
import ClassicEditorfrom '#ckeditor/ckeditor5-build-classic';
export default {
data() {
return {
editor: ClassicEditor,
editorData: '',
editorConfig: {}
},
mounted() {
console.log(this.editor.builtinPlugins.map( plugin => plugin.pluginName ));
}
}
}

In React
import { CKEditor } from '#ckeditor/ckeditor5-react';
import ClassicEditor from '#ckeditor/ckeditor5-build-classic';
export default class AddArticle extends Component {
render() {
return <CKEditor config={EditorConfig} editor={ClassicEditor} onReady={(event) => {
console.log(Array.from(event.ui.componentFactory.names()))}} />
}
}

Related

Docusaurus: How can I have multiple versions of different docs in the docs directory?

I'm working with Docusaurus to create a documentation site for 3 different education courses - all within the docs folder.
So I'm looking for a way to have the version be different across folders in there, or figure out what the best strategy for this is.
Right now, in my docusaurus.config.js I have:
module.exports = {
presets: [
'#docusaurus/preset-classic',
docs: {
lastVersion: 'current',
versions: {
current: {
label: '1.0.0',
path: '1.0.0',
},
},
},
],
};
But I'm not sure how to keep track of 3 different versions across 3 different docs all within the same site.
Swizzle the navbar via wrapping
yarn run swizzle #docusaurus/theme-classic NavbarItem/DocsVersionDropdownNavbarItem -- --wrap
Modify the swizzled component like so:
src/theme/NavbarItem/DocsVersionDropdownNavbarItem.js:
import React from "react";
import DocsVersionDropdownNavbarItem from '#theme-original/NavbarItem/DocsVersionDropdownNavbarItem';
import { useLocation } from '#docusaurus/router';
export default function DocsVersionDropdownNavbarItemWrapper(props) {
const { docsPluginId, className, type } = props
const { pathname } = useLocation()
/* (Custom) check if docsPluginId contains pathname
Given that the docsPluginId is 'charge-controller' and the routeBasePath is 'charge-controller', we can check against the current URI (pathname).
If the pathname contains the docsPluginId, we want to show the version dropdown. Otherwise, we don't want to show it.
This gives us one, global, context-aware version dropdown that works with multi-instance setups.
You want to declare a version dropdown for each plugin in your navbarItems config property for this to work well.
const doesPathnameContainDocsPluginId = pathname.includes(docsPluginId)
if (!doesPathnameContainDocsPluginId) {
return null
}
return <DocsVersionDropdownNavbarItem {...props} />;
}
For this to work, you need to have your documentation (based on products) split up using multi-instances: (https://docusaurus.io/docs/docs-multi-instance#docs-navbar-items)
Note that the preset docsPlugin ID always is "default".
You can try to use
import {
useActivePluginAndVersion,
} from '#docusaurus/plugin-content-docs/client';
const version = activePluginAndVersion.activeVersion.name; // use label instead of name if issues arise.
instead to get the current docsPluginId, name or label.
This would be the more "robust" solution I think. That said, we do use the solution I provided above as-is and it works fine for now.

How to use Google search on a docusaruas blog

I'm wondering how i might go about adding this search box snippet to a docusarus blog.
<script async src="https://cse.google.com/cse.js?cx=e2e7646659949450a">
</script>
<div class="gcse-search"></div>
I've googled lot but can't find any examples or anything close that I could hack on.
I've also tried swizzling the local search and also navbar items but could not figure it out.
I also tried to add it as a html item into the navbar but didn't notice any change.
I'm new to docusarus and not a front end developer, just trying to help get our blog off WordPress :)
Any help/pointers/references would be greatly appreciated.
Update
I seem to have one approach working by just using custom html item in the navbar.
Adding below script from Google:
scripts: [
{src:'https://cse.google.com/cse.js?cx=e2e7646659949450a', async: false, defer: false}
]
And then this item in the navbar:
items: [
...
{
type: "html",
position: "left",
value: '<div class="gcse-search"></div>',
},
...
],
This seems like the most simple to me as avoids having to swizzle anything. However i am having an issue in that i need to now f5 refresh the page for the search box to load for some reason. So i need to try figure that out before saying the html item in navbar approach 100% can work.
I am working in thie PR if ends up being useful to anyone: https://github.com/netdata/blog/pull/106/files
Probably looking at something like this:
export default function NavbarContent(): JSX.Element {
const mobileSidebar = useNavbarMobileSidebar();
const items = useNavbarItems();
const [leftItems, rightItems] = splitNavbarItems(items);
const searchBarItem = items.find((item) => item.type === 'search');
return (
<NavbarContentLayout
left={
// TODO stop hardcoding items?
<>
{!mobileSidebar.disabled && <NavbarMobileSidebarToggle />}
<NavbarLogo />
<NavbarItems items={leftItems} />
</>
}
right={
// TODO stop hardcoding items?
// Ask the user to add the respective navbar items => more flexible
<>
<NavbarItems items={rightItems} />
<NavbarColorModeToggle className={styles.colorModeToggle} />
<div className="gcse-search"></div>
</>
}
/>
);
}
In a swizzled Navbar/Content.
Then:
scripts: [
{
src: 'https://cse.google.com/cse.js?cx=<ID>',
async: true,
},
],
in your docusaurus.config.js. This is untested.

How to Fetch data to dynamically build out a custom Menu for a Layout?

What I would like to do is, call an endpoint to get the list of categories to display in the Sidebar's Menu. I'm not seeing anything in the Layout that would handle this. Am I missing something? What would be the correct way to do this?
Thanks #François, good to know I don't need to look any further in the Layout or Menu files.
Looking at the Demo source code, I see this approach in action using Reacts useState and useEffect.
Posted for others, this is in my Admin component:
const [categories, setCategories] = useState({categories: []});
useEffect(
() => {
dataProvider.getList('tools', {
sort: '',
pagination: {
page: 1,
perPage: 10
}
}).then(data =>
setCategories({categories: data['data']}))
},
[]
);

ckeditor5 - custom container element - recursion error on paste

I'm trying to create a CKEditor5 custom element plugin - mainly for custom format/styles -- nested divs etc. Managed to be able to inject/format the elements, and I can type in them. But if I try to copy and paste text into a custom element I get a too much recursion error.
MyWidget plugin:
export default class MyWidgetPlugin extends Plugin {
init() {
const editor = this.editor;
editor.model.schema.register('my-widget', {
inheritAllFrom: '$root',
isLimit: true,
});
editor.conversion.elementToElement({ model: 'my-widget', view: 'my-widget' });
editor.commands.add('myWidget', new MyWidgetCommand(editor));
}
}
MyWidget command:
class MyWidgetCommand extends Command {
execute() {
const editor = this.editor;
const block = first(this.editor.model.document.selection.getSelectedBlocks());
this.editor.model.change(writer => {
const myWidget = writer.createElement('my-widget')
writer.insert ( myWidget, block, 'after');
writer.appendElement( 'paragraph', myWidget );
});
}
}
Inserting a widget injects this into the editor:
<my-widget>
<p></p>
</my-widget>
And I can type fine, but I can't paste. I'm guessing I got the schema wrong... have played around with quite a few different options.. but to no avail.
I didn't check it but I think that the issue is here:
editor.model.schema.register('my-widget', {
inheritAllFrom: '$root',
isLimit: true,
});
This schema rule says that <my-widget> will allow e.g. a <paragraph> inside it. But it doesn't say anything about where <my-widget> may be used. That's because $root is not allowed in any other element (cause it's a root :)).
I think that the following should work fine:
editor.model.schema.register('my-widget', {
inheritAllFrom: '$root',
allowIn: '$root',
isLimit: true,
});
Alternatively, a more generic solution should work too:
editor.model.schema.register('my-widget', {
inheritAllFrom: '$root',
allowWhere: '$block',
isLimit: true,
});
Still, the editor should not crash with an infinite loop, so I reported https://github.com/ckeditor/ckeditor5-engine/issues/1441.

Twitter typeahead.js not working in Vue component

I'm trying to use Twitter's typeahead.js in a Vue component, but although I have it set up correctly as tested out outside any Vue component, when used within a component, no suggestions appear, and no errors are written to the console. It is simply as if it is not there. This is my typeahead setup code:
var codes = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('code'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: contextPath + "/product/codes"
});
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'codes',
display: 'code',
source: codes,
templates: {
suggestion: (data)=> {
return '<div><strong>' + data.code + '</strong> - ' + data.name + '</div>';
}
}
});
I use it with this form input:
<form>
<input id="item" ref="ttinput" autocomplete="off" placeholder="Enter code" name="item" type="text" class="typeahead"/>
</form>
As mentioned, if I move this to a div outside Vue.js control, and put the Javascript in a document ready block, it works just fine, a properly formatted set of suggestions appears as soon as 3 characters are input in the field. If, however, I put the Javascript in the mounted() for the component (or alternatively in a watch, I've tried both), no typeahead functionality kicks in (i.e., nothing happens after typing in 3 characters), although the Bloodhound prefetch call is made. For the life of me I can't see what the difference is.
Any suggestions as to where to look would be appreciated.
LATER: I've managed to get it to appear by putting the typeahead initialization code in the updated event (instead of mounted or watch). It must have been some problem with the DOM not being in the right state. I have some formatting issues but at least I can move on now.
The correct place to initialize Twitter Typeahead/Bloodhound is in the mounted() hook since thats when the DOM is completely built. (Ref)
Find below the relevant snippet: (Source: https://digitalfortress.tech/js/using-twitter-typeahead-with-vuejs/)
mounted() {
// configure datasource for the suggestions (i.e. Bloodhound)
this.suggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: item => item.id,
remote: {
url: http://example.com/search + '/%QUERY',
wildcard: '%QUERY'
}
});
// get the input element and init typeahead on it
let inputEl = $('.globalSearchInput input');
inputEl.typeahead(
{
minLength: 1,
highlight: true,
},
{
name: 'suggestions',
source: this.suggestions,
limit: 5,
display: item => item.title,
templates: {
suggestion: data => `${data.title}`;
}
}
);
}
You can also find a working example: https://gospelmusic.io/
and a Reference Tutorial to integrate twitter typeahead with your VueJS app.