Merge branch 'feature/extension-bubble-menu'

This commit is contained in:
Philipp Kühn
2021-03-31 13:45:46 +02:00
29 changed files with 620 additions and 33 deletions

View File

@@ -24,7 +24,10 @@
</div>
</div>
<div class="demo__meta">
<div class="demo__name">
<g-link class="demo__name" :to="`/demos/${name}`" v-if="isDevelopment">
Demo/{{ name }}
</g-link>
<div class="demo__name" v-else>
Demo/{{ name }}
</div>
<a class="demo__link" :href="githubUrl" target="_blank">
@@ -67,8 +70,12 @@ export default {
return this.files[this.currentIndex]
},
isDevelopment() {
return process.env.NODE_ENV === 'development'
},
githubUrl() {
if (process.env.NODE_ENV === 'development') {
if (this.isDevelopment) {
return `vscode://file${this.cwd}/src/demos/${this.name}/${this.files[0].name}`
}

View File

@@ -0,0 +1,43 @@
import React from 'react'
import { useEditor, EditorContent, BubbleMenu } from '@tiptap/react'
import { defaultExtensions } from '@tiptap/starter-kit'
import './styles.scss'
export default () => {
const editor = useEditor({
extensions: [
...defaultExtensions(),
],
content: `
<p>
Hey, try to select some text here. There will popup a menu for selecting some inline styles. Remember: you have full control about content and styling of this menu.
</p>
`,
})
return (
<div style={{ position: 'relative' }}>
{editor && <BubbleMenu editor={editor}>
<button
onClick={() => editor.chain().focus().toggleBold().run()}
className={editor.isActive('bold') ? 'is-active' : ''}
>
bold
</button>
<button
onClick={() => editor.chain().focus().toggleItalic().run()}
className={editor.isActive('italic') ? 'is-active' : ''}
>
italic
</button>
<button
onClick={() => editor.chain().focus().toggleCode().run()}
className={editor.isActive('code') ? 'is-active' : ''}
>
code
</button>
</BubbleMenu>}
<EditorContent editor={editor} />
</div>
)
}

View File

@@ -0,0 +1,5 @@
.ProseMirror {
> * + * {
margin-top: 0.75em;
}
}

View File

@@ -0,0 +1,60 @@
<template>
<div style="position: relative">
<bubble-menu :editor="editor" v-if="editor">
<button @click="editor.chain().focus().toggleBold().run()" :class="{ 'is-active': editor.isActive('bold') }">
bold
</button>
<button @click="editor.chain().focus().toggleItalic().run()" :class="{ 'is-active': editor.isActive('italic') }">
italic
</button>
<button @click="editor.chain().focus().toggleCode().run()" :class="{ 'is-active': editor.isActive('code') }">
code
</button>
</bubble-menu>
<editor-content :editor="editor" />
</div>
</template>
<script>
import { Editor, EditorContent, BubbleMenu } from '@tiptap/vue-2'
import { defaultExtensions } from '@tiptap/starter-kit'
export default {
components: {
EditorContent,
BubbleMenu,
},
data() {
return {
editor: null,
}
},
mounted() {
this.editor = new Editor({
extensions: [
...defaultExtensions(),
],
content: `
<p>
Hey, try to select some text here. There will popup a menu for selecting some inline styles. Remember: you have full control about content and styling of this menu.
</p>
`,
})
},
beforeDestroy() {
this.editor.destroy()
},
}
</script>
<style lang="scss">
/* Basic editor styles */
.ProseMirror {
> * + * {
margin-top: 0.75em;
}
}
</style>

View File

@@ -0,0 +1,42 @@
# Bubble Menu
[![Version](https://img.shields.io/npm/v/@tiptap/extension-bubble-menu.svg?label=version)](https://www.npmjs.com/package/@tiptap/extension-bubble-menu)
[![Downloads](https://img.shields.io/npm/dm/@tiptap/extension-bubble-menu.svg)](https://npmcharts.com/compare/@tiptap/extension-bubble-menu?minimal=true)
This extension will make a contextual menu appear near a selection of text.
## Installation
```bash
# with npm
npm install @tiptap/extension-bubble-menu
# with Yarn
yarn add @tiptap/extension-bubble-menu
```
## Settings
| Option | Type | Default | Description |
| ------------ | ------------- | --------- | ----------- |
| element | `HTMLElement` | `null` | |
| keepInBounds | `Boolean` | `true` | |
## Source code
[packages/extension-bubble-menu/](https://github.com/ueberdosis/tiptap-next/blob/main/packages/extension-bubble-menu/)
## Vanilla JavaScript
```js
import { Editor } from '@tiptap/core'
import BubbleMenu from '@tiptap/extension-bubble-menu'
new Editor({
extensions: [
BubbleMenu.configure({
element: document.querySelector('.menu'),
}),
],
})
```
## Using a framework
<demos :items="{
Vue: 'Extensions/BubbleMenu/Vue',
React: 'Extensions/BubbleMenu/React',
}" />

View File

@@ -195,6 +195,8 @@
# - title: Annotation
# link: /api/extensions/annotation
# type: draft
- title: BubbleMenu
link: /api/extensions/bubble-menu
- title: CharacterCount
link: /api/extensions/character-count
- title: Collaboration

View File

@@ -1,4 +1,6 @@
import { EditorState, Plugin, Transaction } from 'prosemirror-state'
import {
EditorState, Plugin, PluginKey, Transaction,
} from 'prosemirror-state'
import { EditorView } from 'prosemirror-view'
import { Schema, DOMParser, Node } from 'prosemirror-model'
import elementFromString from './utilities/elementFromString'
@@ -172,10 +174,19 @@ export class Editor extends EventEmitter {
*
* @param name The plugins name
*/
public unregisterPlugin(name: string): void {
public unregisterPlugin(nameOrPluginKey: string | PluginKey): void {
if (this.isDestroyed) {
return
}
const name = typeof nameOrPluginKey === 'string'
? `${nameOrPluginKey}$`
// @ts-ignore
: nameOrPluginKey.key
const state = this.state.reconfigure({
// @ts-ignore
plugins: this.state.plugins.filter(plugin => !plugin.key.startsWith(`${name}$`)),
plugins: this.state.plugins.filter(plugin => !plugin.key.startsWith(name)),
})
this.view.updateState(state)

View File

@@ -4,7 +4,8 @@ import { InputRule } from 'prosemirror-inputrules'
import { Editor } from './Editor'
import { Node } from './Node'
import mergeDeep from './utilities/mergeDeep'
import { GlobalAttributes, RawCommands, ExtensionConfig } from './types'
import { GlobalAttributes, RawCommands } from './types'
import { ExtensionConfig } from '.'
declare module '@tiptap/core' {
interface ExtensionConfig<Options = any> {

View File

@@ -8,12 +8,8 @@ import { Plugin, Transaction } from 'prosemirror-state'
import { Command as ProseMirrorCommand } from 'prosemirror-commands'
import { InputRule } from 'prosemirror-inputrules'
import mergeDeep from './utilities/mergeDeep'
import {
Attributes,
RawCommands,
GlobalAttributes,
MarkConfig,
} from './types'
import { Attributes, RawCommands, GlobalAttributes } from './types'
import { MarkConfig } from '.'
import { Editor } from './Editor'
declare module '@tiptap/core' {

View File

@@ -13,8 +13,8 @@ import {
NodeViewRenderer,
GlobalAttributes,
RawCommands,
NodeConfig,
} from './types'
import { NodeConfig } from '.'
import { Editor } from './Editor'
declare module '@tiptap/core' {

View File

@@ -1,10 +1,6 @@
import { NodeSpec, MarkSpec, Schema } from 'prosemirror-model'
import {
Extensions,
ExtensionConfig,
NodeConfig,
MarkConfig,
} from '../types'
import { Extensions } from '../types'
import { ExtensionConfig, NodeConfig, MarkConfig } from '..'
import splitExtensions from './splitExtensions'
import getAttributesFromExtensions from './getAttributesFromExtensions'
import getRenderedAttributes from './getRenderedAttributes'

View File

@@ -11,6 +11,7 @@ export { default as markPasteRule } from './pasteRules/markPasteRule'
export { default as callOrReturn } from './utilities/callOrReturn'
export { default as mergeAttributes } from './utilities/mergeAttributes'
export { default as generateHTML } from './helpers/generateHTML'
export { default as getSchema } from './helpers/getSchema'
export { default as getHTMLFromFragment } from './helpers/getHTMLFromFragment'

View File

@@ -14,19 +14,7 @@ import { Extension } from './Extension'
import { Node } from './Node'
import { Mark } from './Mark'
import { Editor } from './Editor'
import {
Commands,
ExtensionConfig,
NodeConfig,
MarkConfig,
} from '.'
export {
Commands,
ExtensionConfig,
NodeConfig,
MarkConfig,
}
import { Commands } from '.'
export type Extensions = (Extension | Node | Mark)[]

View File

@@ -0,0 +1,14 @@
# @tiptap/extension-underline
[![Version](https://img.shields.io/npm/v/@tiptap/extension-underline.svg?label=version)](https://www.npmjs.com/package/@tiptap/extension-underline)
[![Downloads](https://img.shields.io/npm/dm/@tiptap/extension-underline.svg)](https://npmcharts.com/compare/tiptap?minimal=true)
[![License](https://img.shields.io/npm/l/@tiptap/extension-underline.svg)](https://www.npmjs.com/package/@tiptap/extension-underline)
[![Sponsor](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub)](https://github.com/sponsors/ueberdosis)
## Introduction
tiptap is a headless wrapper around [ProseMirror](https://ProseMirror.net) a toolkit for building rich text WYSIWYG editors, which is already in use at many well-known companies such as *New York Times*, *The Guardian* or *Atlassian*.
## Offical Documentation
Documentation can be found on the [tiptap website](https://tiptap.dev).
## License
tiptap is open-sourced software licensed under the [MIT license](https://github.com/ueberdosis/tiptap-next/blob/main/LICENSE.md).

View File

@@ -0,0 +1,31 @@
{
"name": "@tiptap/extension-bubble-menu",
"description": "bubble-menu extension for tiptap",
"version": "2.0.0-beta.0",
"homepage": "https://tiptap.dev",
"keywords": [
"tiptap",
"tiptap extension"
],
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"main": "dist/tiptap-extension-bubble-menu.cjs.js",
"umd": "dist/tiptap-extension-bubble-menu.umd.js",
"module": "dist/tiptap-extension-bubble-menu.esm.js",
"unpkg": "dist/tiptap-extension-bubble-menu.bundle.umd.min.js",
"types": "dist/packages/extension-bubble-menu/src/index.d.ts",
"files": [
"src",
"dist"
],
"peerDependencies": {
"@tiptap/core": "^2.0.0-beta.1"
},
"dependencies": {
"prosemirror-state": "^1.3.4",
"prosemirror-view": "^1.18.2"
}
}

View File

@@ -0,0 +1,145 @@
import { Editor } from '@tiptap/core'
import { EditorState, Plugin, PluginKey } from 'prosemirror-state'
import { EditorView } from 'prosemirror-view'
import { coordsAtPos } from './helpers'
export interface BubbleMenuPluginProps {
editor: Editor,
element: HTMLElement,
keepInBounds: boolean,
}
export type BubbleMenuViewProps = BubbleMenuPluginProps & {
view: EditorView,
}
export class BubbleMenuView {
public editor: Editor
public element: HTMLElement
public keepInBounds = true
public view: EditorView
public isActive = false
public top = 0
public bottom = 0
public left = 0
public preventHide = false
constructor({
editor,
element,
keepInBounds,
view,
}: BubbleMenuViewProps) {
this.editor = editor
this.element = element
this.keepInBounds = keepInBounds
this.view = view
this.element.addEventListener('mousedown', this.mousedownHandler, { capture: true })
this.editor.on('focus', this.focusHandler)
this.editor.on('blur', this.blurHandler)
this.render()
}
mousedownHandler = () => {
this.preventHide = true
}
focusHandler = () => {
// we use `setTimeout` to make sure `selection` is already updated
setTimeout(() => this.update(this.editor.view))
}
blurHandler = ({ event }: { event: FocusEvent }) => {
if (this.preventHide) {
this.preventHide = false
return
}
if (
event?.relatedTarget
&& this.element.parentNode?.contains(event.relatedTarget as Node)
) {
return
}
this.hide()
}
update(view: EditorView, oldState?: EditorState) {
const { state, composing } = view
const { doc, selection } = state
const isSame = oldState && oldState.doc.eq(doc) && oldState.selection.eq(selection)
if (composing || isSame) {
return
}
const { from, to, empty } = selection
const parent = this.element.offsetParent
if (empty || !parent) {
this.hide()
return
}
const start = coordsAtPos(view, from)
const end = coordsAtPos(view, to, true)
const parentBox = parent.getBoundingClientRect()
const box = this.element.getBoundingClientRect()
const left = (start.left + end.left) / 2 - parentBox.left
this.isActive = true
this.top = Math.round(end.bottom - parentBox.top)
this.bottom = Math.round(parentBox.bottom - start.top)
this.left = Math.round(
this.keepInBounds
? Math.min(parentBox.width - box.width / 2, Math.max(left, box.width / 2))
: left,
)
this.render()
}
render() {
Object.assign(this.element.style, {
position: 'absolute',
zIndex: 1,
visibility: this.isActive ? 'visible' : 'hidden',
opacity: this.isActive ? 1 : 0,
left: `${this.left}px`,
// top: `${this.top}px`,
bottom: `${this.bottom}px`,
transform: 'translateX(-50%)',
})
}
hide() {
this.isActive = false
this.render()
}
destroy() {
this.element.removeEventListener('mousedown', this.mousedownHandler)
this.editor.off('focus', this.focusHandler)
this.editor.off('blur', this.blurHandler)
}
}
export const BubbleMenuPluginKey = new PluginKey('menuBubble')
export const BubbleMenuPlugin = (options: BubbleMenuPluginProps) => {
return new Plugin({
key: BubbleMenuPluginKey,
view: view => new BubbleMenuView({ view, ...options }),
})
}

View File

@@ -0,0 +1,23 @@
import { Extension } from '@tiptap/core'
import { BubbleMenuPlugin, BubbleMenuPluginProps } from './bubble-menu-plugin'
export type BubbleMenuOptions = Omit<BubbleMenuPluginProps, 'editor'>
export const BubbleMenu = Extension.create<BubbleMenuOptions>({
name: 'bubbleMenu',
defaultOptions: {
element: document.createElement('div'),
keepInBounds: true,
},
addProseMirrorPlugins() {
return [
BubbleMenuPlugin({
editor: this.editor,
element: this.options.element,
keepInBounds: this.options.keepInBounds,
}),
]
},
})

View File

@@ -0,0 +1,72 @@
import { EditorView } from 'prosemirror-view'
type DOMRectSide = 'bottom' | 'left' | 'right' | 'top';
function textRange(node: Node, from?: number, to?: number) {
const range = document.createRange()
range.setEnd(node, typeof to === 'number' ? to : (node.nodeValue || '').length)
range.setStart(node, Math.max(from || 0, 0))
return range
}
function singleRect(object: Range | Element, bias: number) {
const rects = object.getClientRects()
return !rects.length
? object.getBoundingClientRect()
: rects[bias < 0 ? 0 : rects.length - 1]
}
export function coordsAtPos(view: EditorView, pos: number, end = false) {
const { node, offset } = view.domAtPos(pos) // view.docView.domFromPos(pos);
let side: DOMRectSide | null = null
let rect: DOMRect | null = null
if (node.nodeType === 3) {
const nodeValue = node.nodeValue || ''
if (end && offset < nodeValue.length) {
rect = singleRect(textRange(node, offset - 1, offset), -1)
side = 'right'
} else if (offset < nodeValue.length) {
rect = singleRect(textRange(node, offset, offset + 1), -1)
side = 'left'
}
} else if (node.firstChild) {
if (offset < node.childNodes.length) {
const child = node.childNodes[offset]
rect = singleRect(
child.nodeType === 3 ? textRange(child) : (child as Element),
-1,
)
side = 'left'
}
if ((!rect || rect.top === rect.bottom) && offset) {
const child = node.childNodes[offset - 1]
rect = singleRect(
child.nodeType === 3 ? textRange(child) : (child as Element),
1,
)
side = 'right'
}
} else {
const element = node as Element
rect = element.getBoundingClientRect()
side = 'left'
}
if (rect && side) {
const x = rect[side]
return {
top: rect.top,
bottom: rect.bottom,
left: x,
right: x,
}
}
return {
top: 0,
bottom: 0,
left: 0,
right: 0,
}
}

View File

@@ -0,0 +1,6 @@
import { BubbleMenu } from './bubble-menu'
export * from './bubble-menu'
export * from './bubble-menu-plugin'
export default BubbleMenu

View File

@@ -27,6 +27,7 @@
"react-dom": "^17.0.1"
},
"dependencies": {
"@tiptap/extension-bubble-menu": "^2.0.0-beta.0",
"prosemirror-view": "^1.18.2"
},
"devDependencies": {

View File

@@ -0,0 +1,30 @@
import React, { useEffect, useRef } from 'react'
import { BubbleMenuPlugin, BubbleMenuPluginKey, BubbleMenuPluginProps } from '@tiptap/extension-bubble-menu'
export type BubbleMenuProps = Omit<BubbleMenuPluginProps, 'element'> & {
className?: string,
}
export const BubbleMenu: React.FC<BubbleMenuProps> = props => {
const element = useRef<HTMLDivElement>(null)
useEffect(() => {
const { editor, keepInBounds = true } = props
editor.registerPlugin(BubbleMenuPlugin({
editor,
element: element.current as HTMLElement,
keepInBounds,
}))
return () => {
editor.unregisterPlugin(BubbleMenuPluginKey)
}
}, [])
return (
<div ref={element} className={props.className}>
{props.children}
</div>
)
}

View File

@@ -1,4 +1,5 @@
export * from '@tiptap/core'
export * from './BubbleMenu'
export { Editor } from './Editor'
export * from './useEditor'
export * from './ReactRenderer'

View File

@@ -26,6 +26,7 @@
"vue": "^2.6.12"
},
"dependencies": {
"@tiptap/extension-bubble-menu": "^2.0.0-beta.0",
"prosemirror-view": "^1.18.2"
}
}

View File

@@ -0,0 +1,45 @@
import Vue, { PropType } from 'vue'
import { BubbleMenuPlugin, BubbleMenuPluginKey, BubbleMenuPluginProps } from '@tiptap/extension-bubble-menu'
export const BubbleMenu = Vue.extend({
name: 'BubbleMenu',
props: {
editor: {
type: Object as PropType<BubbleMenuPluginProps['editor']>,
required: true,
},
keepInBounds: {
type: Boolean as PropType<BubbleMenuPluginProps['keepInBounds']>,
default: true,
},
},
watch: {
editor: {
immediate: true,
handler(editor: BubbleMenuPluginProps['editor']) {
if (!editor) {
return
}
this.$nextTick(() => {
editor.registerPlugin(BubbleMenuPlugin({
editor,
element: this.$el as HTMLElement,
keepInBounds: this.keepInBounds,
}))
})
},
},
},
render(createElement) {
return createElement('div', {}, this.$slots.default)
},
beforeDestroy() {
this.editor.unregisterPlugin(BubbleMenuPluginKey)
},
})

View File

@@ -1,4 +1,5 @@
export * from '@tiptap/core'
export * from './BubbleMenu'
export { Editor } from './Editor'
export * from './EditorContent'
export * from './VueRenderer'

View File

@@ -25,6 +25,7 @@
"@tiptap/core": "^2.0.0-beta.1"
},
"dependencies": {
"prosemirror-state": "^1.3.4",
"prosemirror-view": "^1.18.2",
"vue": "^3.0.0"
}

View File

@@ -0,0 +1,47 @@
import {
h,
ref,
PropType,
onMounted,
onBeforeUnmount,
defineComponent,
} from 'vue'
import {
BubbleMenuPlugin,
BubbleMenuPluginKey,
BubbleMenuPluginProps,
} from '@tiptap/extension-bubble-menu'
export const BubbleMenu = defineComponent({
name: 'BubbleMenu',
props: {
editor: {
type: Object as PropType<BubbleMenuPluginProps['editor']>,
required: true,
},
keepInBounds: {
type: Boolean as PropType<BubbleMenuPluginProps['keepInBounds']>,
default: true,
},
},
setup({ editor, keepInBounds }, { slots }) {
const root = ref<HTMLElement | null>(null)
onMounted(() => {
editor.registerPlugin(BubbleMenuPlugin({
editor,
element: root.value as HTMLElement,
keepInBounds,
}))
})
onBeforeUnmount(() => {
editor.unregisterPlugin(BubbleMenuPluginKey)
})
return () => h('div', { ref: root }, slots.default?.())
},
})

View File

@@ -1,3 +1,4 @@
import { EditorState, Plugin, PluginKey } from 'prosemirror-state'
import { Editor as CoreEditor, EditorOptions } from '@tiptap/core'
import {
markRaw,
@@ -7,7 +8,6 @@ import {
ComponentPublicInstance,
reactive,
} from 'vue'
import { EditorState } from 'prosemirror-state'
import { VueRenderer } from './VueRenderer'
function useDebouncedRef<T>(value: T) {
@@ -60,4 +60,20 @@ export class Editor extends CoreEditor {
? this.reactiveState.value
: this.view.state
}
/**
* Register a ProseMirror plugin.
*/
public registerPlugin(plugin: Plugin, handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[]): void {
super.registerPlugin(plugin, handlePlugins)
this.reactiveState.value = this.view.state
}
/**
* Unregister a ProseMirror plugin.
*/
public unregisterPlugin(nameOrPluginKey: string | PluginKey): void {
super.unregisterPlugin(nameOrPluginKey)
this.reactiveState.value = this.view.state
}
}

View File

@@ -1,4 +1,5 @@
export * from '@tiptap/core'
export * from './BubbleMenu'
export { Editor } from './Editor'
export * from './EditorContent'
export * from './useEditor'