webapp/src/components/Editor/store/ctrl.ts

543 lines
14 KiB
TypeScript
Raw Normal View History

2022-09-09 11:53:35 +00:00
import { Store, createStore, unwrap } from 'solid-js/store'
import { v4 as uuidv4 } from 'uuid'
2022-10-09 08:33:28 +00:00
import type { Command, EditorState } from 'prosemirror-state'
2022-09-09 11:53:35 +00:00
import { undo, redo } from 'prosemirror-history'
import { selectAll, deleteSelection } from 'prosemirror-commands'
2022-10-09 00:00:13 +00:00
import * as Y from 'yjs'
2022-09-09 11:53:35 +00:00
import { undo as yUndo, redo as yRedo } from 'y-prosemirror'
2022-10-09 00:00:13 +00:00
import { WebrtcProvider } from 'y-webrtc'
import { uniqueNamesGenerator, adjectives, animals } from 'unique-names-generator'
2022-10-08 05:24:09 +00:00
import debounce from 'lodash/debounce'
2022-10-09 00:00:13 +00:00
import { createSchema, createExtensions, createEmptyText } from '../prosemirror/setup'
import { State, Draft, Config, ServiceError, newState } from '.'
2022-09-09 11:53:35 +00:00
import { serialize, createMarkdownParser } from '../prosemirror/markdown'
2022-10-09 00:00:13 +00:00
import db from '../db'
import { isEmpty, isInitialized } from '../prosemirror/helpers'
import { Awareness } from 'y-protocols/awareness'
import { drafts as draftsatom } from '../../../stores/editor'
import { useStore } from '@nanostores/solid'
import { createMemo } from 'solid-js'
2022-09-09 11:53:35 +00:00
2022-10-09 00:00:13 +00:00
const isText = (x) => x && x.doc && x.selection
const isState = (x) => typeof x.lastModified !== 'string' && Array.isArray(x.drafts)
const isDraft = (x): boolean => x && (x.text || x.path)
const mod = 'Ctrl'
2022-09-09 11:53:35 +00:00
2022-10-09 08:33:28 +00:00
export const createCtrl = (initial): [Store<State>, { [key: string]: any }] => {
2022-10-09 00:00:13 +00:00
const [store, setState] = createStore(initial)
2022-09-09 11:53:35 +00:00
2022-10-09 00:00:13 +00:00
const onNew = () => {
newDraft()
2022-10-08 05:24:09 +00:00
return true
2022-09-09 11:53:35 +00:00
}
const onDiscard = () => {
discard()
return true
}
2022-10-09 00:00:13 +00:00
const onToggleMarkdown = () => toggleMarkdown()
2022-09-09 11:53:35 +00:00
const onUndo = () => {
2022-10-09 00:00:13 +00:00
if (!isInitialized(store.text as EditorState)) return
2022-09-09 11:53:35 +00:00
const text = store.text as EditorState
2022-10-09 00:00:13 +00:00
store.collab?.started ? yUndo(text) : undo(text, store.editorView.dispatch)
2022-09-09 11:53:35 +00:00
return true
}
const onRedo = () => {
2022-10-09 00:00:13 +00:00
if (!isInitialized(store.text as EditorState)) return
2022-09-09 11:53:35 +00:00
const text = store.text as EditorState
2022-10-09 00:00:13 +00:00
if (store.collab?.started) {
yRedo(text)
} else {
redo(text, store.editorView.dispatch)
}
2022-09-09 11:53:35 +00:00
return true
}
2022-10-09 00:00:13 +00:00
const keymap = {
[`${mod}-n`]: onNew,
[`${mod}-w`]: onDiscard,
[`${mod}-z`]: onUndo,
[`Shift-${mod}-z`]: onRedo,
[`${mod}-y`]: onRedo,
[`${mod}-m`]: onToggleMarkdown
2022-10-09 08:33:28 +00:00
} as { [key: string]: Command }
2022-10-09 00:00:13 +00:00
const createTextFromDraft = async (d: Draft): Promise<Draft> => {
let draft = d
2022-09-09 11:53:35 +00:00
const state = unwrap(store)
2022-10-09 00:00:13 +00:00
if (draft.path) {
draft = await loadDraft(state.config, draft.path)
2022-10-08 05:24:09 +00:00
}
2022-09-09 11:53:35 +00:00
const extensions = createExtensions({
config: state.config,
2022-10-09 00:00:13 +00:00
markdown: draft.markdown,
path: draft.path,
keymap
2022-09-09 11:53:35 +00:00
})
2022-10-09 00:00:13 +00:00
return {
text: draft.text,
2022-09-09 11:53:35 +00:00
extensions,
2022-10-09 08:33:28 +00:00
lastModified: draft.lastModified ? new Date(draft.lastModified) : undefined,
2022-10-09 00:00:13 +00:00
path: draft.path,
markdown: draft.markdown
}
2022-09-09 11:53:35 +00:00
}
2022-10-09 00:00:13 +00:00
// eslint-disable-next-line unicorn/consistent-function-scoping
const addToDrafts = (drafts: Draft[], prev: Draft) => {
const text = prev.path ? undefined : JSON.stringify(prev.text)
return [
...drafts,
{
body: text,
2022-10-09 08:33:28 +00:00
lastModified: prev.lastModified as Date,
2022-10-09 00:00:13 +00:00
path: prev.path,
markdown: prev.markdown
} as Draft
]
}
const discardText = async () => {
const state = unwrap(store)
const index = state.drafts.length - 1
const draft = index !== -1 ? state.drafts[index] : undefined
let next
if (draft) {
next = await createTextFromDraft(draft)
} else {
const extensions = createExtensions({
config: state.config ?? store.config,
markdown: state.markdown ?? store.markdown,
keymap
})
next = {
text: createEmptyText(),
extensions,
2022-10-09 08:33:28 +00:00
lastModified: new Date(),
2022-10-09 00:00:13 +00:00
path: undefined,
markdown: state.markdown
}
}
const drafts = state.drafts.filter((f: Draft) => f !== draft)
setState({
drafts,
...next,
collab: state.collab,
error: undefined
})
}
2022-10-08 05:24:09 +00:00
2022-09-09 11:53:35 +00:00
const fetchData = async (): Promise<State> => {
2022-10-08 05:24:09 +00:00
const state: State = unwrap(store)
2022-10-09 00:00:13 +00:00
const room = window.location.pathname?.slice(1).trim()
const args = { room, draft: room }
const data = await db.get('state')
let parsed
2022-10-07 19:35:53 +00:00
if (data !== undefined) {
try {
2022-10-09 00:00:13 +00:00
parsed = JSON.parse(data)
} catch (error) {
console.error(error)
2022-10-07 19:35:53 +00:00
throw new ServiceError('invalid_state', data)
2022-09-09 11:53:35 +00:00
}
2022-10-07 19:35:53 +00:00
}
2022-10-09 00:00:13 +00:00
if (!parsed) {
return { ...state, args }
}
let text = state.text
if (parsed.text) {
if (!isText(parsed.text)) {
throw new ServiceError('invalid_state', parsed.text)
}
text = parsed.text
}
const extensions = createExtensions({
path: parsed.path,
markdown: parsed.markdown,
keymap,
config: undefined
})
const newst = {
...parsed,
text,
extensions,
// config,
args,
lastModified: new Date(parsed.lastModified)
}
for (const draft of parsed.drafts) {
if (!isDraft(draft)) {
throw new ServiceError('invalid_draft', draft)
}
}
if (!isState(newst)) {
throw new ServiceError('invalid_state', newst)
}
return newst
2022-09-09 11:53:35 +00:00
}
2022-10-09 00:00:13 +00:00
const getTheme = (state: State) => ({ theme: state.config.theme })
2022-09-09 11:53:35 +00:00
const clean = () => {
2022-10-09 00:00:13 +00:00
setState({
2022-09-09 11:53:35 +00:00
...newState(),
loading: 'initialized',
2022-10-09 00:00:13 +00:00
drafts: [],
fullscreen: store.fullscreen,
2022-09-09 11:53:35 +00:00
lastModified: new Date(),
error: undefined,
2022-10-09 00:00:13 +00:00
text: undefined
})
}
const discard = async () => {
if (store.path) {
await discardText()
} else if (store.drafts.length > 0 && isEmpty(store.text as EditorState)) {
await discardText()
} else {
selectAll(store.editorView.state, store.editorView.dispatch)
deleteSelection(store.editorView.state, store.editorView.dispatch)
2022-10-08 16:40:58 +00:00
}
2022-09-09 11:53:35 +00:00
}
const init = async () => {
2022-10-09 00:00:13 +00:00
let data = await fetchData()
try {
if (data.args.room) {
data = doStartCollab(data)
} else if (data.args.text) {
data = await doOpenDraft(data, {
text: { ...JSON.parse(data.args.text) },
2022-10-09 08:33:28 +00:00
lastModified: new Date()
2022-10-09 00:00:13 +00:00
})
} else if (data.args.draft) {
const draft = await loadDraft(data.config, data.args.draft)
data = await doOpenDraft(data, draft)
} else if (data.path) {
const draft = await loadDraft(data.config, data.path)
data = await doOpenDraft(data, draft)
} else if (!data.text) {
const text = createEmptyText()
const extensions = createExtensions({
config: data.config ?? store.config,
markdown: data.markdown ?? store.markdown,
keymap: keymap
})
data = { ...data, text, extensions }
2022-09-09 11:53:35 +00:00
}
2022-10-09 00:00:13 +00:00
} catch (error) {
data = { ...data, error: error.errorObject }
}
setState({
...data,
config: { ...data.config, ...getTheme(data) },
loading: 'initialized'
})
}
const loadDraft = async (config: Config, path: string): Promise<Draft> => {
const draftstore = useStore(draftsatom)
const draft = createMemo(() => draftstore()[path])
const schema = createSchema({
config,
markdown: false,
path,
keymap
})
const parser = createMarkdownParser(schema)
return {
...draft(),
2022-10-09 08:41:33 +00:00
text: {
doc: parser.parse(draft().body).toJSON(),
selection: {
type: 'text',
anchor: 1,
head: 1
}
},
2022-10-09 00:00:13 +00:00
path
}
}
const newDraft = () => {
if (isEmpty(store.text as EditorState) && !store.path) return
const state = unwrap(store)
let drafts = state.drafts
if (!state.error) {
drafts = addToDrafts(drafts, state)
}
const extensions = createExtensions({
config: state.config ?? store.config,
markdown: state.markdown ?? store.markdown,
keymap
})
setState({
text: createEmptyText(),
extensions,
drafts,
lastModified: undefined,
path: undefined,
error: undefined,
collab: undefined
})
}
const openDraft = async (draft: Draft) => {
const state: State = unwrap(store)
const update = await doOpenDraft(state, draft)
setState(update)
}
const doOpenDraft = async (state: State, draft: Draft): Promise<State> => {
const findIndexOfDraft = (f: Draft) => {
for (let i = 0; i < state.drafts.length; i++) {
if (state.drafts[i] === f || (f.path && state.drafts[i].path === f.path)) return i
}
return -1
}
const index = findIndexOfDraft(draft)
const item = index === -1 ? draft : state.drafts[index]
let drafts = state.drafts.filter((f) => f !== item)
if (!isEmpty(state.text as EditorState) && state.lastModified) {
2022-10-09 08:33:28 +00:00
drafts = addToDrafts(drafts, { lastModified: new Date(), text: state.text } as Draft)
2022-10-09 00:00:13 +00:00
}
2022-10-09 08:33:28 +00:00
draft.lastModified = item.lastModified
2022-10-09 00:00:13 +00:00
const next = await createTextFromDraft(draft)
return {
...state,
...next,
drafts,
collab: undefined,
error: undefined
2022-09-09 11:53:35 +00:00
}
}
2022-10-08 16:40:58 +00:00
const saveState = () =>
debounce(async (state: State) => {
2022-10-09 08:33:28 +00:00
const data: State = {
loading: 'initialized',
2022-10-08 16:40:58 +00:00
lastModified: state.lastModified,
2022-10-09 00:00:13 +00:00
drafts: state.drafts,
2022-10-08 16:40:58 +00:00
config: state.config,
path: state.path,
markdown: state.markdown,
collab: {
room: state.collab?.room
2022-10-09 00:00:13 +00:00
}
2022-10-08 16:40:58 +00:00
}
2022-10-09 00:00:13 +00:00
2022-10-08 16:40:58 +00:00
if (isInitialized(state.text as EditorState)) {
2022-10-09 00:00:13 +00:00
if (state.path) {
2022-10-09 08:41:33 +00:00
// const text = serialize(store.editorView.state)
2022-10-09 08:33:28 +00:00
// await remote.writeDraft(state.path, text)
2022-10-09 08:41:33 +00:00
draftsatom.setKey(state.path, store.editorView.state)
2022-10-09 00:00:13 +00:00
} else {
data.text = store.editorView.state.toJSON()
}
2022-10-08 16:40:58 +00:00
} else if (state.text) {
2022-10-09 00:00:13 +00:00
data.text = state.text
2022-10-08 16:40:58 +00:00
}
2022-10-09 00:00:13 +00:00
db.set('state', JSON.stringify(data))
2022-10-08 16:40:58 +00:00
}, 200)
2022-09-09 11:53:35 +00:00
const startCollab = () => {
const state: State = unwrap(store)
const update = doStartCollab(state)
setState(update)
}
const doStartCollab = (state: State): State => {
const backup = state.args?.room && state.collab?.room !== state.args.room
const room = state.args?.room ?? uuidv4()
2022-10-09 00:00:13 +00:00
window.history.replaceState(null, '', `/${room}`)
const ydoc = new Y.Doc()
const type = ydoc.getXmlFragment('prosemirror')
const webrtcOptions = {
awareness: new Awareness(ydoc),
filterBcConns: true,
maxConns: 33,
signaling: [
// 'wss://signaling.discours.io',
// 'wss://stun.l.google.com:19302',
'wss://y-webrtc-signaling-eu.herokuapp.com',
'wss://signaling.yjs.dev'
],
peerOpts: {},
password: ''
}
const provider = new WebrtcProvider(room, ydoc, webrtcOptions)
const username = uniqueNamesGenerator({
dictionaries: [adjectives, animals],
style: 'capital',
separator: ' ',
length: 2
})
provider.awareness.setLocalStateField('user', {
name: username
})
const extensions = createExtensions({
2022-09-09 11:53:35 +00:00
config: state.config,
markdown: state.markdown,
path: state.path,
keymap,
2022-10-09 00:00:13 +00:00
y: { type, provider }
})
let newst = state
2022-10-08 16:40:58 +00:00
if ((backup && !isEmpty(state.text as EditorState)) || state.path) {
2022-10-09 00:00:13 +00:00
let drafts = state.drafts
if (!state.error) {
2022-10-09 08:33:28 +00:00
drafts = addToDrafts(drafts, { lastModified: new Date(), text: state.text } as Draft)
2022-10-09 00:00:13 +00:00
}
newst = {
2022-09-09 11:53:35 +00:00
...state,
2022-10-09 00:00:13 +00:00
drafts,
2022-09-09 11:53:35 +00:00
lastModified: undefined,
path: undefined,
error: undefined
}
}
2022-10-09 00:00:13 +00:00
2022-09-09 11:53:35 +00:00
return {
2022-10-09 00:00:13 +00:00
...newst,
2022-09-09 11:53:35 +00:00
extensions,
2022-10-09 00:00:13 +00:00
collab: { started: true, room, y: { type, provider } }
2022-09-09 11:53:35 +00:00
}
}
const stopCollab = (state: State) => {
2022-10-09 00:00:13 +00:00
state.collab.y?.provider.destroy()
2022-09-09 11:53:35 +00:00
const extensions = createExtensions({
config: state.config,
markdown: state.markdown,
path: state.path,
keymap
})
2022-10-09 00:00:13 +00:00
2022-09-09 11:53:35 +00:00
setState({ collab: undefined, extensions })
window.history.replaceState(null, '', '/')
}
2022-10-09 00:00:13 +00:00
const toggleMarkdown = () => {
const state = unwrap(store)
const editorState = store.text as EditorState
const markdown = !state.markdown
const selection = { type: 'text', anchor: 1, head: 1 }
2022-10-09 08:33:28 +00:00
let doc
2022-10-09 00:00:13 +00:00
if (markdown) {
const lines = serialize(editorState).split('\n')
const nodes = lines.map((text) => {
return text ? { type: 'paragraph', content: [{ type: 'text', text }] } : { type: 'paragraph' }
})
doc = { type: 'doc', content: nodes }
} else {
const schema = createSchema({
config: state.config,
path: state.path,
y: state.collab?.y,
markdown,
keymap
})
const parser = createMarkdownParser(schema)
let textContent = ''
editorState.doc.forEach((node) => {
textContent += `${node.textContent}\n`
})
const text = parser.parse(textContent)
doc = text.toJSON()
}
const extensions = createExtensions({
config: state.config,
markdown,
path: state.path,
keymap: keymap,
y: state.collab?.y
})
setState({
text: { selection, doc },
extensions,
markdown
})
2022-10-09 08:33:28 +00:00
return true
2022-10-09 00:00:13 +00:00
}
2022-09-09 11:53:35 +00:00
const updateConfig = (config: Partial<Config>) => {
const state = unwrap(store)
const extensions = createExtensions({
config: { ...state.config, ...config },
markdown: state.markdown,
path: state.path,
keymap,
y: state.collab?.y
})
setState({
config: { ...state.config, ...config },
extensions,
lastModified: new Date()
})
}
const updatePath = (path: string) => {
setState({ path, lastModified: new Date() })
}
const updateTheme = () => {
const { theme } = getTheme(unwrap(store))
setState('config', { theme })
}
const ctrl = {
clean,
discard,
getTheme,
init,
2022-10-09 00:00:13 +00:00
loadDraft,
newDraft,
openDraft,
2022-09-09 11:53:35 +00:00
saveState,
setState,
startCollab,
stopCollab,
toggleMarkdown,
updateConfig,
updatePath,
updateTheme
}
return [store, ctrl]
}