@dxos/react-ui-editor 0.8.3 → 0.8.4-main.84f28bd
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/browser/chunk-22UMM3QJ.mjs +22 -0
- package/dist/lib/browser/chunk-22UMM3QJ.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +566 -525
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +1 -1
- package/dist/lib/browser/types/index.mjs +13 -0
- package/dist/lib/browser/types/index.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-YXYQPV6R.mjs +24 -0
- package/dist/lib/node-esm/chunk-YXYQPV6R.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +566 -526
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +1 -1
- package/dist/lib/node-esm/types/index.mjs +14 -0
- package/dist/lib/node-esm/types/index.mjs.map +7 -0
- package/dist/types/src/components/Editor/Editor.d.ts +19 -0
- package/dist/types/src/components/Editor/Editor.d.ts.map +1 -0
- package/dist/types/src/components/Editor/index.d.ts +2 -0
- package/dist/types/src/components/Editor/index.d.ts.map +1 -0
- package/dist/types/src/components/EditorToolbar/util.d.ts +4 -3
- package/dist/types/src/components/EditorToolbar/util.d.ts.map +1 -1
- package/dist/types/src/components/EditorToolbar/view-mode.d.ts +1 -1
- package/dist/types/src/components/EditorToolbar/view-mode.d.ts.map +1 -1
- package/dist/types/src/components/Popover/RefDropdownMenu.d.ts.map +1 -1
- package/dist/types/src/components/index.d.ts +1 -0
- package/dist/types/src/components/index.d.ts.map +1 -1
- package/dist/types/src/extensions/automerge/automerge.stories.d.ts +28 -28
- package/dist/types/src/extensions/automerge/automerge.stories.d.ts.map +1 -1
- package/dist/types/src/extensions/blast.d.ts.map +1 -1
- package/dist/types/src/extensions/command/index.d.ts +1 -1
- package/dist/types/src/extensions/command/index.d.ts.map +1 -1
- package/dist/types/src/extensions/command/typeahead.d.ts +7 -2
- package/dist/types/src/extensions/command/typeahead.d.ts.map +1 -1
- package/dist/types/src/extensions/factories.d.ts +18 -0
- package/dist/types/src/extensions/factories.d.ts.map +1 -1
- package/dist/types/src/extensions/markdown/formatting.d.ts.map +1 -1
- package/dist/types/src/extensions/modes.d.ts +0 -7
- package/dist/types/src/extensions/modes.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/stories/CommandMenu.stories.d.ts +1 -1
- package/dist/types/src/stories/CommandMenu.stories.d.ts.map +1 -1
- package/dist/types/src/stories/EditorToolbar.stories.d.ts +1 -1
- package/dist/types/src/stories/EditorToolbar.stories.d.ts.map +1 -1
- package/dist/types/src/stories/components/EditorStory.d.ts +2 -2
- package/dist/types/src/translations.d.ts +28 -29
- package/dist/types/src/translations.d.ts.map +1 -1
- package/dist/types/src/types/index.d.ts +2 -0
- package/dist/types/src/types/index.d.ts.map +1 -0
- package/dist/types/src/types/types.d.ts +21 -0
- package/dist/types/src/types/types.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +44 -41
- package/src/components/Editor/Editor.tsx +39 -0
- package/src/components/Editor/index.ts +5 -0
- package/src/components/EditorToolbar/util.ts +5 -4
- package/src/components/EditorToolbar/view-mode.ts +1 -1
- package/src/components/Popover/RefDropdownMenu.tsx +9 -3
- package/src/components/index.ts +1 -0
- package/src/extensions/automerge/automerge.stories.tsx +4 -2
- package/src/extensions/blast.ts +3 -16
- package/src/extensions/command/index.ts +1 -1
- package/src/extensions/command/typeahead.ts +26 -13
- package/src/extensions/factories.ts +24 -5
- package/src/extensions/markdown/formatting.test.ts +1 -1
- package/src/extensions/markdown/formatting.ts +14 -12
- package/src/extensions/modes.ts +0 -9
- package/src/index.ts +1 -1
- package/src/stories/CommandMenu.stories.tsx +1 -1
- package/src/stories/EditorToolbar.stories.tsx +3 -4
- package/src/stories/Preview.stories.tsx +4 -4
- package/src/stories/TextEditor.stories.tsx +1 -1
- package/src/styles/theme.ts +1 -1
- package/src/translations.ts +4 -2
- package/src/types/index.ts +5 -0
- package/src/types/types.ts +32 -0
- package/dist/lib/node/index.cjs +0 -7754
- package/dist/lib/node/index.cjs.map +0 -7
- package/dist/lib/node/meta.json +0 -1
- package/dist/lib/node/testing/index.cjs +0 -29
- package/dist/lib/node/testing/index.cjs.map +0 -7
- package/dist/types/src/types.d.ts +0 -14
- package/dist/types/src/types.d.ts.map +0 -1
- package/src/types.ts +0 -23
@@ -1,7 +0,0 @@
|
|
1
|
-
{
|
2
|
-
"version": 3,
|
3
|
-
"sources": ["../../../src/translations.ts", "../../../src/index.ts", "../../../src/components/EditorToolbar/EditorToolbar.tsx", "../../../src/components/EditorToolbar/util.ts", "../../../src/extensions/annotations.ts", "../../../src/extensions/autocomplete.ts", "../../../src/extensions/automerge/automerge.ts", "../../../src/extensions/automerge/cursor.ts", "../../../src/extensions/automerge/defs.ts", "../../../src/extensions/automerge/sync.ts", "../../../src/extensions/automerge/update-automerge.ts", "../../../src/extensions/automerge/update-codemirror.ts", "../../../src/util/facet.ts", "../../../src/util/cursor.ts", "../../../src/util/debug.ts", "../../../src/util/dom.ts", "../../../src/util/react.tsx", "../../../src/extensions/awareness/awareness.ts", "../../../src/extensions/awareness/awareness-provider.ts", "../../../src/extensions/blast.ts", "../../../src/extensions/command/action.ts", "../../../src/extensions/command/state.ts", "../../../src/extensions/command/command.ts", "../../../src/extensions/command/hint.ts", "../../../src/extensions/command/command-menu.ts", "../../../src/extensions/command/placeholder.ts", "../../../src/extensions/command/floating-menu.ts", "../../../src/extensions/command/useCommandMenu.ts", "../../../src/extensions/command/typeahead.ts", "../../../src/extensions/comments.ts", "../../../src/extensions/selection.ts", "../../../src/extensions/debug.ts", "../../../src/extensions/dnd.ts", "../../../src/extensions/factories.ts", "../../../src/extensions/focus.ts", "../../../src/defaults.ts", "../../../src/styles/markdown.ts", "../../../src/styles/tokens.ts", "../../../src/styles/theme.ts", "../../../src/extensions/folding.tsx", "../../../src/extensions/hashtag.tsx", "../../../src/extensions/json.ts", "../../../src/extensions/listener.ts", "../../../src/extensions/markdown/formatting.ts", "../../../src/extensions/markdown/action.ts", "../../../src/extensions/markdown/bundle.ts", "../../../src/extensions/markdown/highlight.ts", "../../../src/extensions/markdown/debug.ts", "../../../src/extensions/markdown/decorate.ts", "../../../src/extensions/markdown/changes.ts", "../../../src/extensions/markdown/image.ts", "../../../src/extensions/markdown/styles.ts", "../../../src/extensions/markdown/table.ts", "../../../src/extensions/markdown/link.ts", "../../../src/extensions/mention.ts", "../../../src/extensions/modes.ts", "../../../src/extensions/outliner/commands.ts", "../../../src/extensions/outliner/selection.ts", "../../../src/extensions/outliner/tree.ts", "../../../src/extensions/outliner/outliner.ts", "../../../src/extensions/outliner/editor.ts", "../../../src/extensions/preview/preview.ts", "../../../src/extensions/typewriter.ts", "../../../src/components/EditorToolbar/blocks.ts", "../../../src/components/EditorToolbar/formatting.ts", "../../../src/components/EditorToolbar/headings.ts", "../../../src/components/EditorToolbar/image.ts", "../../../src/components/EditorToolbar/lists.ts", "../../../src/components/EditorToolbar/search.ts", "../../../src/components/EditorToolbar/view-mode.ts", "../../../src/components/Popover/CommandMenu.tsx", "../../../src/components/Popover/RefPopover.tsx", "../../../src/components/Popover/RefDropdownMenu.tsx", "../../../src/hooks/useTextEditor.ts"],
|
4
|
-
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nexport const translationKey = 'react-ui-editor';\n\nexport default [\n {\n 'en-US': {\n [translationKey]: {\n 'strong label': 'Bold',\n 'emphasis label': 'Italics',\n 'strikethrough label': 'Strikethrough',\n 'code label': 'Code',\n 'link label': 'Link',\n 'list-bullet label': 'Bullet list',\n 'list-ordered label': 'Numbered list',\n 'list-task label': 'Task list',\n 'blockquote label': 'Block quote',\n 'codeblock label': 'Code block',\n 'comment label': 'Create comment',\n 'selection overlaps existing comment label': 'Selection overlaps existing comment',\n 'select text to comment label': 'Select text to comment',\n 'image label': 'Insert image',\n 'heading label': 'Heading level',\n 'table label': 'Create table',\n 'heading level label_zero': 'Paragraph',\n 'heading level label_one': 'Heading level {{count}}',\n 'heading level label_other': 'Heading level {{count}}',\n 'view mode label': 'Editor view',\n 'preview mode label': 'Live preview',\n 'readonly mode label': 'Read only',\n 'search label': 'Search',\n 'source mode label': 'Source',\n },\n },\n },\n];\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport translations from './translations';\n\nexport { type Extension, EditorState } from '@codemirror/state';\nexport { EditorView, keymap } from '@codemirror/view';\nexport { tags } from '@lezer/highlight';\n\nexport { TextKind } from '@dxos/protocols/proto/dxos/echo/model/text';\n\nexport * from './components';\nexport * from './defaults';\nexport * from './extensions';\nexport * from './hooks';\nexport * from './types';\nexport * from './util';\n\nexport { translations };\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Rx } from '@effect-rx/rx-react';\nimport React, { memo, useMemo } from 'react';\n\nimport { rxFromSignal, type NodeArg } from '@dxos/app-graph';\nimport { ElevationProvider } from '@dxos/react-ui';\nimport { MenuProvider, ToolbarMenu, createGapSeparator, useMenuActions } from '@dxos/react-ui-menu';\n\nimport { createBlocks } from './blocks';\nimport { createFormatting } from './formatting';\nimport { createHeadings } from './headings';\nimport { createImageUpload } from './image';\nimport { createLists } from './lists';\nimport { createSearch } from './search';\nimport { type EditorToolbarActionGraphProps, type EditorToolbarFeatureFlags, type EditorToolbarProps } from './util';\nimport { createViewMode } from './view-mode';\n\nconst createToolbar = ({\n getView,\n state,\n customActions,\n ...features\n}: EditorToolbarFeatureFlags & Pick<EditorToolbarActionGraphProps, 'getView' | 'state' | 'customActions'>): Rx.Rx<{\n nodes: NodeArg<any>[];\n edges: { source: string; target: string }[];\n}> => {\n return Rx.make((get) => {\n const nodes = [];\n const edges = [];\n if (features.headings ?? true) {\n const headings = get(rxFromSignal(() => createHeadings(state, getView)));\n nodes.push(...headings.nodes);\n edges.push(...headings.edges);\n }\n if (features.formatting ?? true) {\n const formatting = get(rxFromSignal(() => createFormatting(state, getView)));\n nodes.push(...formatting.nodes);\n edges.push(...formatting.edges);\n }\n if (features.lists ?? true) {\n const lists = get(rxFromSignal(() => createLists(state, getView)));\n nodes.push(...lists.nodes);\n edges.push(...lists.edges);\n }\n if (features.blocks ?? true) {\n const blocks = get(rxFromSignal(() => createBlocks(state, getView)));\n nodes.push(...blocks.nodes);\n edges.push(...blocks.edges);\n }\n if (features.image) {\n const image = get(rxFromSignal(() => createImageUpload(features.image!)));\n nodes.push(...image.nodes);\n edges.push(...image.edges);\n }\n const editorToolbarGap = createGapSeparator();\n nodes.push(...editorToolbarGap.nodes);\n edges.push(...editorToolbarGap.edges);\n if (customActions) {\n const custom = get(customActions);\n nodes.push(...custom.nodes);\n edges.push(...custom.edges);\n }\n if (features.search ?? true) {\n const search = get(rxFromSignal(() => createSearch(getView)));\n nodes.push(...search.nodes);\n edges.push(...search.edges);\n }\n if (features.viewMode) {\n const viewMode = get(rxFromSignal(() => createViewMode(state, features.viewMode!)));\n nodes.push(...viewMode.nodes);\n edges.push(...viewMode.edges);\n }\n return { nodes, edges };\n });\n};\n\n// TODO(wittjosiah): Toolbar re-rendering is causing this graph to be recreated and breaking reactivity in some cases.\n// E.g. for toolbar dropdowns which use active icon, the icon is not updated when the active item changes.\n// This is currently only happening in the markdown plugin usage and should be reproduced in an editor story.\nconst useEditorToolbarActionGraph = (props: EditorToolbarProps) => {\n const menuCreator = useMemo(\n () =>\n createToolbar({\n getView: props.getView,\n state: props.state,\n customActions: props.customActions,\n headings: props.headings,\n formatting: props.formatting,\n lists: props.lists,\n blocks: props.blocks,\n image: props.image,\n search: props.search,\n viewMode: props.viewMode,\n }),\n [\n props.getView,\n props.state,\n props.customActions,\n props.headings,\n props.formatting,\n props.lists,\n props.blocks,\n props.image,\n props.search,\n props.viewMode,\n ],\n );\n\n return useMenuActions(menuCreator);\n};\n\nexport const EditorToolbar = memo(({ classNames, attendableId, role, ...props }: EditorToolbarProps) => {\n const menuProps = useEditorToolbarActionGraph(props);\n return (\n <ElevationProvider elevation={role === 'section' ? 'positioned' : 'base'}>\n <MenuProvider {...menuProps} attendableId={attendableId}>\n <ToolbarMenu classNames={classNames} textBlockWidth />\n </MenuProvider>\n </ElevationProvider>\n );\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type EditorView } from '@codemirror/view';\nimport { type Rx } from '@effect-rx/rx-react';\nimport { useMemo } from 'react';\n\nimport { type Action } from '@dxos/app-graph';\nimport { live, type Live } from '@dxos/live-object';\nimport { type ThemedClassName } from '@dxos/react-ui';\nimport {\n type MenuSeparator,\n type MenuItemGroup,\n type ToolbarMenuActionGroupProperties,\n createMenuAction,\n createMenuItemGroup,\n type ActionGraphProps,\n type MenuActionProperties,\n} from '@dxos/react-ui-menu';\n\nimport type { EditorAction, EditorViewMode, Formatting } from '../../extensions';\nimport { translationKey } from '../../translations';\n\nexport type EditorToolbarState = Formatting & Partial<{ viewMode: EditorViewMode }>;\n\nexport const useEditorToolbarState = (initialState: Partial<EditorToolbarState> = {}) => {\n return useMemo(() => live<EditorToolbarState>(initialState), []);\n};\n\nexport type EditorToolbarFeatureFlags = Partial<{\n headings: boolean;\n formatting: boolean;\n lists: boolean;\n blocks: boolean;\n search: boolean;\n // TODO(wittjosiah): Factor out. Depend on plugin-level capabilities.\n image: () => void;\n viewMode: (mode: EditorViewMode) => void;\n}>;\n\nexport type EditorToolbarActionGraphProps = {\n state: Live<EditorToolbarState>;\n getView: () => EditorView;\n // TODO(wittjosiah): Control positioning.\n customActions?: Rx.Rx<ActionGraphProps>;\n};\n\nexport type EditorToolbarProps = ThemedClassName<\n EditorToolbarActionGraphProps & EditorToolbarFeatureFlags & { attendableId?: string; role?: string }\n>;\n\nexport type EditorToolbarItem = EditorAction | MenuItemGroup | MenuSeparator;\n\nexport const createEditorAction = (id: string, invoke: () => void, properties: Partial<MenuActionProperties>) => {\n const { label = [`${id} label`, { ns: translationKey }], ...rest } = properties;\n return createMenuAction(id, invoke, { label, ...rest }) as Action<MenuActionProperties>;\n};\n\nexport const createEditorActionGroup = (\n id: string,\n props: Omit<ToolbarMenuActionGroupProperties, 'icon'>,\n icon?: string,\n) => createMenuItemGroup(id, { icon, iconOnly: true, ...props });\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Extension, RangeSetBuilder } from '@codemirror/state';\nimport { Decoration, type DecorationSet, EditorView, ViewPlugin, type ViewUpdate } from '@codemirror/view';\n\nconst annotationMark = Decoration.mark({ class: 'cm-annotation' });\n\nexport type AnnotationOptions = {\n match?: RegExp; // TODO(burdon): Update via hook (e.g., for search).\n};\n\n/**\n *\n */\nexport const annotations = ({ match }: AnnotationOptions = {}): Extension => {\n return [\n ViewPlugin.fromClass(\n class {\n decorations: DecorationSet = Decoration.none;\n update(update: ViewUpdate) {\n const builder = new RangeSetBuilder<Decoration>();\n if (match) {\n // Only process visible lines.\n const { from, to } = update.view.viewport;\n const text = update.state.doc.sliceString(from, to);\n const matches = text.matchAll(match);\n for (const m of matches) {\n if (m.index !== undefined) {\n // Adjust match position relative to viewport.\n const start = from + m.index;\n const end = start + m[0].length;\n builder.add(start, end, annotationMark);\n }\n }\n }\n\n this.decorations = builder.finish();\n }\n },\n {\n decorations: (v) => v.decorations,\n },\n ),\n\n EditorView.theme({\n '.cm-annotation': {\n textDecoration: 'underline',\n textDecorationStyle: 'wavy',\n textDecorationColor: 'var(--dx-errorText)',\n },\n }),\n ];\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport {\n autocompletion,\n completionKeymap,\n type CompletionSource,\n type Completion,\n type CompletionContext,\n type CompletionResult,\n} from '@codemirror/autocomplete';\nimport { markdownLanguage } from '@codemirror/lang-markdown';\nimport { type Extension } from '@codemirror/state';\nimport { keymap } from '@codemirror/view';\n\nexport type AutocompleteResult = Completion;\n\nexport type AutocompleteOptions = {\n activateOnTyping?: boolean;\n override?: CompletionSource[];\n onSearch?: (text: string) => Completion[];\n};\n\n// https://codemirror.net/examples/autocompletion\n// https://codemirror.net/docs/ref/#autocomplete.autocompletion\n// https://codemirror.net/docs/ref/#autocomplete.Completion\n\n/**\n * Autocomplete extension.\n */\nexport const autocomplete = ({ activateOnTyping, override, onSearch }: AutocompleteOptions = {}): Extension => {\n const extensions: Extension[] = [\n // https://codemirror.net/docs/ref/#view.keymap\n // https://discuss.codemirror.net/t/how-can-i-replace-the-default-autocompletion-keymap-v6/3322\n // TODO(burdon): Set custom keymap.\n keymap.of(completionKeymap),\n\n // https://codemirror.net/examples/autocompletion\n // https://codemirror.net/docs/ref/#autocomplete.autocompletion\n autocompletion({\n override,\n activateOnTyping,\n // closeOnBlur: false,\n // tooltipClass: () => 'rounded-be pbe-1 border-separator',\n }),\n ];\n\n if (onSearch) {\n extensions.push(\n // TODO(burdon): Optional decoration via addToOptions.\n markdownLanguage.data.of({\n autocomplete: (context: CompletionContext): CompletionResult | null => {\n const match = context.matchBefore(/\\w*/);\n if (!match || (match.from === match.to && !context.explicit)) {\n return null;\n }\n\n return {\n from: match.from,\n options: onSearch(match.text.toLowerCase()),\n };\n },\n }),\n );\n }\n\n return extensions;\n};\n", "//\n// Copyright 2024 DXOS.org\n// Copyright 2024 Automerge\n// Ref: https://github.com/automerge/automerge-codemirror\n//\n\nimport { next as A } from '@automerge/automerge';\nimport { StateField, type Extension } from '@codemirror/state';\nimport { EditorView, ViewPlugin } from '@codemirror/view';\n\nimport { type DocAccessor } from '@dxos/react-client/echo';\n\nimport { cursorConverter } from './cursor';\nimport { updateHeadsEffect, isReconcile, type State } from './defs';\nimport { Syncer } from './sync';\nimport { Cursor } from '../../util';\n\nexport const automerge = (accessor: DocAccessor): Extension => {\n const syncState = StateField.define<State>({\n create: () => ({\n path: accessor.path.slice(),\n lastHeads: A.getHeads(accessor.handle.doc()!),\n unreconciledTransactions: [],\n }),\n\n update: (value, tr) => {\n const result: State = {\n path: accessor.path.slice(),\n lastHeads: value.lastHeads,\n unreconciledTransactions: value.unreconciledTransactions.slice(),\n };\n\n let clearUnreconciled = false;\n for (const effect of tr.effects) {\n if (effect.is(updateHeadsEffect)) {\n result.lastHeads = effect.value.newHeads;\n clearUnreconciled = true;\n }\n }\n\n if (clearUnreconciled) {\n result.unreconciledTransactions = [];\n } else {\n if (!isReconcile(tr)) {\n result.unreconciledTransactions.push(tr);\n }\n }\n\n return result;\n },\n });\n\n const syncer = new Syncer(accessor.handle, syncState);\n\n return [\n Cursor.converter.of(cursorConverter(accessor)),\n\n // Track heads.\n syncState,\n\n // Reconcile external updates.\n ViewPlugin.fromClass(\n class {\n constructor(private readonly _view: EditorView) {\n accessor.handle.addListener('change', this._handleChange);\n }\n\n destroy() {\n accessor.handle.removeListener('change', this._handleChange);\n }\n\n readonly _handleChange = () => {\n syncer.reconcile(this._view, false);\n };\n },\n ),\n\n // Reconcile local updates.\n EditorView.updateListener.of(({ view, changes }) => {\n if (!changes.empty) {\n syncer.reconcile(view, true);\n }\n }),\n ];\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { log } from '@dxos/log';\nimport { type DocAccessor, fromCursor, toCursor } from '@dxos/react-client/echo';\n\nimport { type CursorConverter } from '../../util';\n\nexport const cursorConverter = (accessor: DocAccessor): CursorConverter => ({\n toCursor: (pos, assoc) => {\n try {\n return toCursor(accessor, pos, assoc);\n } catch (err) {\n log.catch(err);\n return ''; // In case of invalid request (e.g., wrong document).\n }\n },\n\n fromCursor: (cursor) => {\n try {\n return fromCursor(accessor, cursor);\n } catch (err) {\n log.catch(err);\n return 0; // In case of invalid request (e.g., wrong document).\n }\n },\n});\n", "//\n// Copyright 2023 DXOS.org\n// Copyright 2024 Automerge\n// Ref: https://github.com/automerge/automerge-codemirror\n//\n\nimport { type Heads, type Prop } from '@automerge/automerge';\nimport { Annotation, StateEffect, type StateField, type EditorState, type Transaction } from '@codemirror/state';\n\nexport type State = {\n path: Prop[];\n lastHeads: Heads;\n unreconciledTransactions: Transaction[];\n};\n\nexport const getPath = (state: EditorState, field: StateField<State>): Prop[] => state.field(field).path;\nexport const getLastHeads = (state: EditorState, field: StateField<State>): Heads => state.field(field).lastHeads;\n\nexport type UpdateHeads = {\n newHeads: Heads;\n};\n\nexport const updateHeadsEffect = StateEffect.define<UpdateHeads>({});\n\nexport const updateHeads = (newHeads: Heads): StateEffect<UpdateHeads> => updateHeadsEffect.of({ newHeads });\n\nexport const reconcileAnnotation = Annotation.define<boolean>();\n\nexport const isReconcile = (tr: Transaction): boolean => {\n return !!tr.annotation(reconcileAnnotation);\n};\n", "//\n// Copyright 2023 DXOS.org\n// Copyright 2024 Automerge\n// Ref: https://github.com/automerge/automerge-codemirror\n//\n\nimport { next as A } from '@automerge/automerge';\nimport { type StateField } from '@codemirror/state';\nimport { type EditorView } from '@codemirror/view';\n\nimport { type IDocHandle } from '@dxos/react-client/echo';\n\nimport { getLastHeads, getPath, isReconcile, reconcileAnnotation, type State, updateHeads } from './defs';\nimport { updateAutomerge } from './update-automerge';\nimport { updateCodeMirror } from './update-codemirror';\n\n/**\n * Implements three-way merge (on each mutation).\n */\nexport class Syncer {\n private _pending = false;\n\n // prettier-ignore\n constructor(\n private readonly _handle: IDocHandle,\n private readonly _state: StateField<State>\n ) {}\n\n reconcile(view: EditorView, editor: boolean): void {\n // TODO(burdon): Better way to do mutex?\n if (this._pending) {\n return;\n }\n\n this._pending = true;\n if (editor) {\n this.onEditorChange(view);\n } else {\n this.onAutomergeChange(view);\n }\n this._pending = false;\n }\n\n onEditorChange(view: EditorView): void {\n // Apply the unreconciled transactions to the document.\n const transactions = view.state.field(this._state).unreconciledTransactions.filter((tx) => !isReconcile(tx));\n const newHeads = updateAutomerge(this._state, this._handle, transactions, view.state);\n\n if (newHeads) {\n view.dispatch({\n effects: updateHeads(newHeads),\n annotations: reconcileAnnotation.of(false),\n });\n }\n }\n\n onAutomergeChange(view: EditorView): void {\n // Get the diff between the updated state of the document and the heads and apply that to the codemirror doc.\n const oldHeads = getLastHeads(view.state, this._state);\n const newHeads = A.getHeads(this._handle.doc()!);\n const diff = A.equals(oldHeads, newHeads) ? [] : A.diff(this._handle.doc()!, oldHeads, newHeads);\n\n const selection = view.state.selection;\n const path = getPath(view.state, this._state);\n updateCodeMirror(view, selection, path, diff);\n\n // TODO(burdon): Test conflicts?\n // A.getConflicts(this._handle.doc()!, path[0]);\n\n view.dispatch({\n effects: updateHeads(newHeads),\n annotations: reconcileAnnotation.of(false),\n });\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n// Copyright 2024 Automerge\n// Ref: https://github.com/automerge/automerge-codemirror\n//\n\nimport { next as A, type Heads } from '@automerge/automerge';\nimport { type EditorState, type StateField, type Transaction, type Text } from '@codemirror/state';\n\nimport { type IDocHandle } from '@dxos/react-client/echo';\n\nimport { type State } from './defs';\n\nexport const updateAutomerge = (\n field: StateField<State>,\n handle: IDocHandle,\n transactions: Transaction[],\n state: EditorState, // TODO(burdon): Just pass in the state field value?\n): Heads | undefined => {\n const { lastHeads, path } = state.field(field);\n\n // We don't want to call `automerge.updateAt` if there are no changes.\n // Otherwise, later on `automerge.diff` will return empty patches that result in a no-op but still mess up the selection.\n let hasChanges = false;\n for (const tr of transactions) {\n tr.changes.iterChanges(() => {\n hasChanges = true;\n });\n }\n\n if (!hasChanges) {\n return undefined;\n }\n\n const newHeads = handle.changeAt(lastHeads, (doc: A.Doc<unknown>) => {\n const invertedTransactions: { from: number; del: number; insert: Text }[] = [];\n for (const tr of transactions) {\n tr.changes.iterChanges((fromA, toA, _fromB, _toB, insert) => {\n invertedTransactions.push({ from: fromA, del: toA - fromA, insert });\n });\n }\n\n // TODO(burdon): Hack to apply in reverse order to properly apply range.\n invertedTransactions.reverse().forEach(({ from, del, insert }) => {\n A.splice(doc, path.slice(), from, del, insert.toString());\n });\n });\n\n return newHeads ?? undefined;\n};\n", "//\n// Copyright 2023 DXOS.org\n// Copyright 2024 Automerge\n// Ref: https://github.com/automerge/automerge-codemirror\n//\n\nimport {\n type DelPatch,\n type InsertPatch,\n type Patch,\n type Prop,\n type PutPatch,\n type SpliceTextPatch,\n} from '@automerge/automerge';\nimport { ChangeSet, type ChangeSpec, type EditorSelection, type EditorState } from '@codemirror/state';\nimport { type EditorView } from '@codemirror/view';\n\nimport { reconcileAnnotation } from './defs';\n\nexport const updateCodeMirror = (view: EditorView, selection: EditorSelection, target: Prop[], patches: Patch[]) => {\n for (const patch of patches) {\n const changeSpec = handlePatch(patch, target, view.state);\n if (changeSpec != null) {\n const changeSet = ChangeSet.of(changeSpec, view.state.doc.length, '\\n');\n selection = selection.map(changeSet, 1);\n view.dispatch({\n changes: changeSet,\n annotations: reconcileAnnotation.of(false),\n });\n }\n }\n\n view.dispatch({\n selection,\n annotations: reconcileAnnotation.of(false),\n });\n};\n\nconst handlePatch = (patch: Patch, target: Prop[], state: EditorState): ChangeSpec | null => {\n if (patch.action === 'insert') {\n return handleInsert(target, patch);\n } else if (patch.action === 'splice') {\n return handleSplice(target, patch);\n } else if (patch.action === 'del') {\n return handleDel(target, patch);\n } else if (patch.action === 'put') {\n return handlePut(target, patch, state);\n } else {\n return null;\n }\n};\n\nconst handleInsert = (target: Prop[], patch: InsertPatch): Array<ChangeSpec> => {\n const index = charPath(target, patch.path);\n if (index == null) {\n return [];\n }\n\n const text = patch.values.map((value) => (value ? value.toString() : '')).join('');\n return [{ from: index, to: index, insert: text }];\n};\n\nconst handleSplice = (target: Prop[], patch: SpliceTextPatch): Array<ChangeSpec> => {\n const index = charPath(target, patch.path);\n if (index == null) {\n return [];\n }\n\n return [{ from: index, insert: patch.value }];\n};\n\nconst handleDel = (target: Prop[], patch: DelPatch): Array<ChangeSpec> => {\n const index = charPath(target, patch.path);\n if (index == null) {\n return [];\n }\n\n const length = patch.length || 1;\n return [{ from: index, to: index + length }];\n};\n\nconst handlePut = (target: Prop[], patch: PutPatch, state: EditorState): Array<ChangeSpec> => {\n const index = charPath(target, [...patch.path, 0]);\n if (index == null) {\n return [];\n }\n\n const length = state.doc.length;\n if (typeof patch.value !== 'string') {\n return []; // TODO(dmaretskyi): How to handle non-string values?\n }\n\n return [{ from: 0, to: length, insert: patch.value as any }];\n};\n\n// If the path of the patch is of the form [path, <index>] then we know this is a path to a character\n// within the sequence given by path.\nconst charPath = (textPath: Prop[], candidatePath: Prop[]): number | null => {\n if (candidatePath.length !== textPath.length + 1) {\n return null;\n }\n\n for (let i = 0; i < textPath.length; i++) {\n if (textPath[i] !== candidatePath[i]) {\n return null;\n }\n }\n\n const index = candidatePath[candidatePath.length - 1];\n if (typeof index === 'number') {\n return index;\n }\n\n return null;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Facet } from '@codemirror/state';\n\nexport const singleValueFacet = <I, O = I>(defaultValue?: O) =>\n Facet.define<I, O>({\n // Called immediately.\n combine: (providers) => {\n return (providers[0] ?? defaultValue) as O;\n },\n });\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type EditorState } from '@codemirror/state';\n\nimport { singleValueFacet } from './facet';\nimport { type Range } from '../types';\n\n/**\n * Determines if two ranges overlap.\n * A range is considered to overlap if there is any intersection\n * between the two ranges, inclusive of their boundaries.\n */\nexport const overlap = (a: Range, b: Range): boolean => a.from <= b.to && a.to >= b.from;\n\n/**\n * Converts indexes into the text document into stable peer-independent cursors.\n *\n * See:\n * - https://automerge.org/automerge/api-docs/js/functions/next.getCursor.html\n * - https://github.com/yjs/yjs?tab=readme-ov-file#relative-positions\n *\n * @param {assoc} number Negative values will associate the cursor with the previous character\n * while positive - with the next one.\n */\nexport interface CursorConverter {\n toCursor(position: number, assoc?: -1 | 1 | undefined): string;\n fromCursor(cursor: string): number;\n}\n\nconst defaultCursorConverter: CursorConverter = {\n toCursor: (position) => position.toString(),\n fromCursor: (cursor) => parseInt(cursor),\n};\n\nexport class Cursor {\n static readonly converter = singleValueFacet(defaultCursorConverter);\n\n static readonly getCursorFromRange = (state: EditorState, range: Range) => {\n const cursorConverter = state.facet(Cursor.converter);\n const from = cursorConverter.toCursor(range.from);\n const to = cursorConverter.toCursor(range.to, -1);\n return [from, to].join(':');\n };\n\n static readonly getRangeFromCursor = (state: EditorState, cursor: string) => {\n const cursorConverter = state.facet(Cursor.converter);\n\n const parts = cursor.split(':');\n const from = cursorConverter.fromCursor(parts[0]);\n const to = cursorConverter.fromCursor(parts[1]);\n return from !== undefined && to !== undefined ? { from, to } : undefined;\n };\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Transaction } from '@codemirror/state';\nimport { type EditorView } from '@codemirror/view';\n\nimport { log } from '@dxos/log';\n\nexport const wrapWithCatch = (fn: (...args: any[]) => any) => {\n return (...args: any[]) => {\n try {\n return fn(...args);\n } catch (err) {\n log.catch(err);\n }\n };\n};\n\n/**\n * CodeMirror callbacks swallow errors so wrap handlers.\n */\n// TODO(burdon): Reconcile with wrapWithCatch.\nexport const callbackWrapper = <T extends Function>(fn: T): T =>\n ((...args: any[]) => {\n try {\n return fn(...args);\n } catch (err) {\n log.catch(err);\n }\n }) as unknown as T;\n\n/**\n * Log all changes before dispatching them to the view.\n * https://codemirror.net/docs/ref/#view.EditorView.dispatch\n */\nexport const debugDispatcher = (trs: readonly Transaction[], view: EditorView) => {\n logChanges(trs);\n view.update(trs);\n};\n\n/**\n * Util to log transactions in update listener.\n */\nexport const logChanges = (trs: readonly Transaction[]) => {\n const changes = trs\n .flatMap((tr) => {\n if (tr.changes.empty) {\n return undefined;\n }\n\n const changes: any[] = [];\n tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) =>\n changes.push(JSON.stringify({ fromA, toA, fromB, toB, inserted: inserted.toString() })),\n );\n\n return changes;\n })\n .filter(Boolean);\n\n if (changes.length) {\n log('changes', { changes });\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// Copied from @codemirror/view\n\nexport interface Rect {\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly bottom: number;\n}\n\nexport const flattenRect = (rect: Rect, left: boolean) => {\n const x = left ? rect.left : rect.right;\n return { left: x, right: x, top: rect.top, bottom: rect.bottom };\n};\n\nlet scratchRange: Range | null;\n\nexport const textRange = (node: Text, from: number, to = from) => {\n const range = scratchRange || (scratchRange = document.createRange());\n range.setEnd(node, to);\n range.setStart(node, from);\n return range;\n};\n\nexport const clientRectsFor = (dom: Node) => {\n if (dom.nodeType === 3) {\n return textRange(dom as Text, 0, dom.nodeValue!.length).getClientRects();\n } else if (dom.nodeType === 1) {\n return (dom as HTMLElement).getClientRects();\n } else {\n return [] as any as DOMRectList;\n }\n};\n\nexport type ElementOptions = {\n className?: string;\n text?: string;\n};\n\nexport const createElement = (tag: string, options?: ElementOptions, children?: HTMLElement[]): HTMLElement => {\n const el = document.createElement(tag);\n if (options?.className) {\n el.className = options.className;\n }\n if (options?.text) {\n el.textContent = options.text;\n }\n if (children) {\n el.append(...(Array.isArray(children) ? children : [children]));\n }\n\n return el;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport React, { type FC, type ReactNode } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nimport { ThemeProvider, Tooltip } from '@dxos/react-ui';\nimport { defaultTx } from '@dxos/react-ui-theme';\n\nimport { type RenderCallback } from '../types';\n\n/** @deprecated */\n// TODO(wittjosiah): Replace with portals which are lighter weight and inherit context from the main react tree.\nexport const renderRoot = <T extends Element>(root: T, node: ReactNode): T => {\n createRoot(root).render(<ThemeProvider tx={defaultTx}>{node}</ThemeProvider>);\n return root;\n};\n\n/**\n * Utility to create a renderer for a React component.\n * @deprecated\n */\nexport const createRenderer =\n <Props extends object>(Component: FC<Props>): RenderCallback<Props> =>\n (el, props) => {\n renderRoot(\n el,\n <ThemeProvider tx={defaultTx}>\n <Tooltip.Provider>\n <Component {...props} />\n </Tooltip.Provider>\n </ThemeProvider>,\n );\n };\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Annotation, type Extension, RangeSet, type Range } from '@codemirror/state';\nimport {\n Decoration,\n type DecorationSet,\n EditorView,\n type PluginValue,\n ViewPlugin,\n type ViewUpdate,\n WidgetType,\n} from '@codemirror/view';\n\nimport { Event } from '@dxos/async';\nimport { Context } from '@dxos/context';\n\nimport { singleValueFacet, Cursor, type CursorConverter } from '../../util';\n\nexport interface AwarenessProvider {\n remoteStateChange: Event<void>;\n\n open(): void;\n close(): void;\n\n getRemoteStates(): AwarenessState[];\n update(position: AwarenessPosition | undefined): void;\n}\n\nconst dummyProvider: AwarenessProvider = {\n remoteStateChange: new Event(),\n\n open: () => {},\n close: () => {},\n\n getRemoteStates: () => [],\n update: () => {},\n};\n\nexport const awarenessProvider = singleValueFacet<AwarenessProvider>(dummyProvider);\n\n// TODO(dmaretskyi): Specify the users that actually changed. Currently, we recalculate positions for every user.\nconst RemoteSelectionChangedAnnotation = Annotation.define();\n\nexport type AwarenessPosition = {\n anchor?: string;\n head?: string;\n};\n\nexport type AwarenessInfo = {\n displayName: string;\n darkColor: string;\n lightColor: string;\n};\n\nexport type AwarenessState = {\n position?: AwarenessPosition;\n peerId: string;\n info: AwarenessInfo;\n};\n\n/**\n * Extension provides presence information about other peers.\n */\nexport const awareness = (provider = dummyProvider): Extension => {\n return [\n awarenessProvider.of(provider),\n ViewPlugin.fromClass(RemoteSelectionsDecorator, {\n decorations: (value) => value.decorations,\n }),\n styles,\n ];\n};\n\n/**\n * Generates selection decorations from remote peers.\n */\nexport class RemoteSelectionsDecorator implements PluginValue {\n private readonly _ctx = new Context();\n private readonly _cursorConverter: CursorConverter;\n private readonly _provider: AwarenessProvider;\n\n private _lastAnchor?: number;\n private _lastHead?: number;\n\n public decorations: DecorationSet = RangeSet.of([]);\n\n constructor(view: EditorView) {\n this._cursorConverter = view.state.facet(Cursor.converter);\n this._provider = view.state.facet(awarenessProvider);\n this._provider.open();\n this._provider.remoteStateChange.on(this._ctx, () => {\n view.dispatch({ annotations: [RemoteSelectionChangedAnnotation.of([])] });\n });\n }\n\n destroy(): void {\n void this._ctx.dispose();\n this._provider.close();\n }\n\n update(update: ViewUpdate): void {\n this._updateLocalSelection(update.view);\n this._updateRemoteSelections(update.view);\n }\n\n private _updateLocalSelection(view: EditorView): void {\n const hasFocus = view.hasFocus && view.dom.ownerDocument.hasFocus();\n const { anchor = undefined, head = undefined } = hasFocus ? view.state.selection.main : {};\n if (this._lastAnchor === anchor && this._lastHead === head) {\n return;\n }\n\n this._lastAnchor = anchor;\n this._lastHead = head;\n\n this._provider.update(\n anchor !== undefined && head !== undefined\n ? {\n anchor: this._cursorConverter.toCursor(anchor),\n head: this._cursorConverter.toCursor(head, -1),\n }\n : undefined,\n );\n }\n\n private _updateRemoteSelections(view: EditorView): void {\n const decorations: Range<Decoration>[] = [\n // TODO(burdon): Factor out for testing.\n // {\n // from: 0,\n // to: 0,\n // value: Decoration.widget({ side: 0, block: false, widget: new RemoteCaretWidget('Test', 'red') }),\n // },\n ];\n\n const awarenessStates = this._provider.getRemoteStates();\n for (const state of awarenessStates) {\n const anchor = state.position?.anchor ? this._cursorConverter.fromCursor(state.position.anchor) : null;\n const head = state.position?.head ? this._cursorConverter.fromCursor(state.position.head) : null;\n if (anchor == null || head == null) {\n continue;\n }\n\n const start = Math.min(Math.min(anchor, head), view.state.doc.length);\n const end = Math.min(Math.max(anchor, head), view.state.doc.length);\n\n const startLine = view.state.doc.lineAt(start);\n const endLine = view.state.doc.lineAt(end);\n\n const darkColor = state.info.darkColor;\n const lightColor = state.info.lightColor;\n\n if (startLine.number === endLine.number) {\n // Selected content in a single line.\n decorations.push({\n from: start,\n to: end,\n value: Decoration.mark({\n attributes: { style: `background-color: ${lightColor}` },\n class: 'cm-collab-selection',\n }),\n });\n } else {\n // Selected content in multiple lines; first, render text-selection in the first line.\n decorations.push({\n from: start,\n to: startLine.from + startLine.length,\n value: Decoration.mark({\n attributes: { style: `background-color: ${lightColor}` },\n class: 'cm-collab-selection',\n }),\n });\n\n // Render text-selection in the last line.\n decorations.push({\n from: endLine.from,\n to: end,\n value: Decoration.mark({\n attributes: { style: `background-color: ${lightColor}` },\n class: 'cm-collab-selection',\n }),\n });\n\n for (let i = startLine.number + 1; i < endLine.number; i++) {\n const linePos = view.state.doc.line(i).from;\n decorations.push({\n from: linePos,\n to: linePos,\n value: Decoration.line({\n attributes: { style: `background-color: ${lightColor}`, class: 'cm-collab-selectionLine' },\n }),\n });\n }\n }\n\n decorations.push({\n from: head,\n to: head,\n value: Decoration.widget({\n side: head - anchor > 0 ? -1 : 1, // The local cursor should be rendered outside the remote selection.\n block: false,\n widget: new RemoteCaretWidget(state.info.displayName ?? 'Anonymous', darkColor),\n }),\n });\n }\n\n this.decorations = Decoration.set(decorations, true);\n }\n}\n\nclass RemoteCaretWidget extends WidgetType {\n constructor(\n private readonly _name: string,\n private readonly _color: string,\n ) {\n super();\n }\n\n override toDOM(): HTMLElement {\n const span = document.createElement('span');\n span.className = 'cm-collab-selectionCaret';\n span.style.backgroundColor = this._color;\n span.style.borderColor = this._color;\n\n const dot = document.createElement('div');\n dot.className = 'cm-collab-selectionCaretDot';\n\n const info = document.createElement('div');\n info.className = 'cm-collab-selectionInfo';\n info.innerText = this._name;\n\n span.appendChild(document.createTextNode('\\u2060'));\n span.appendChild(dot);\n span.appendChild(document.createTextNode('\\u2060'));\n span.appendChild(info);\n span.appendChild(document.createTextNode('\\u2060'));\n return span;\n }\n\n override updateDOM(): boolean {\n return false;\n }\n\n override eq(widget: this): boolean {\n return widget._color === this._color;\n }\n\n override get estimatedHeight() {\n return -1;\n }\n\n override ignoreEvent(): boolean {\n return true;\n }\n}\n\nconst styles = EditorView.theme({\n '.cm-collab-selection': {},\n '.cm-collab-selectionLine': {\n padding: 0,\n margin: '0px 2px 0px 4px',\n },\n '.cm-collab-selectionCaret': {\n position: 'relative',\n borderLeft: '1px solid black',\n borderRight: '1px solid black',\n marginLeft: '-1px',\n marginRight: '-1px',\n boxSizing: 'border-box',\n display: 'inline',\n cursor: 'pointer',\n },\n '.cm-collab-selectionCaretDot': {\n borderRadius: '50%',\n position: 'absolute',\n width: '.5em',\n height: '.5em',\n top: '-.25em',\n left: '-.25em',\n backgroundColor: 'inherit',\n transition: 'transform .3s ease-in-out',\n boxSizing: 'border-box',\n },\n '.cm-collab-selectionCaret:hover > .cm-collab-selectionCaretDot': {\n transform: 'scale(0)',\n transformOrigin: 'center',\n },\n '.cm-collab-selectionInfo': {\n position: 'absolute',\n transform: 'translate(-50%, 0)',\n top: '-20px',\n left: 0,\n fontSize: '.75em',\n fontFamily: 'sans-serif',\n fontStyle: 'normal',\n fontWeight: 'normal',\n lineHeight: 'normal',\n userSelect: 'none',\n color: 'white',\n padding: '2px 6px',\n zIndex: 101,\n transition: 'opacity .3s ease-in-out',\n backgroundColor: 'inherit',\n borderRadius: '2px',\n opacity: 0,\n transitionDelay: '0s',\n whiteSpace: 'nowrap',\n },\n '.cm-collab-selectionCaret:hover > .cm-collab-selectionInfo': {\n opacity: 1,\n transitionDelay: '0s',\n },\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { DeferredTask, Event, sleep } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { type Space } from '@dxos/react-client/echo';\nimport { type GossipMessage } from '@dxos/react-client/mesh';\n\nimport { type AwarenessInfo, type AwarenessPosition, type AwarenessProvider, type AwarenessState } from './awareness';\n\ntype ProtocolMessage =\n | {\n kind: 'query';\n }\n | {\n kind: 'post';\n state: AwarenessState;\n };\n\nconst DEBOUNCE_INTERVAL = 100; // ms\n\nexport type AwarenessProviderParams = {\n space: Space;\n channel: string;\n peerId: string;\n info: AwarenessInfo;\n};\n\n/**\n * Receives and broadcasts profile and cursor position.\n */\nexport class SpaceAwarenessProvider implements AwarenessProvider {\n private readonly _remoteStates = new Map<string, AwarenessState>();\n\n private readonly _space: Space;\n private readonly _channel: string;\n private readonly _peerId: string;\n private readonly _info: AwarenessInfo;\n\n private _ctx?: Context;\n private _postTask?: DeferredTask;\n private _localState?: AwarenessState;\n\n public readonly remoteStateChange = new Event<void>();\n\n constructor(params: AwarenessProviderParams) {\n this._space = params.space;\n this._channel = params.channel;\n this._peerId = params.peerId;\n this._info = params.info;\n }\n\n open(): void {\n this._ctx = new Context();\n this._postTask = new DeferredTask(this._ctx, async () => {\n if (this._localState) {\n await this._space.postMessage(this._channel, {\n kind: 'post',\n state: this._localState,\n } satisfies ProtocolMessage);\n\n // TODO(burdon): Replace with throttle.\n // TODO(burdon): Send heads?\n await sleep(DEBOUNCE_INTERVAL);\n }\n });\n\n this._ctx.onDispose(\n this._space.listen(this._channel, (message: GossipMessage) => {\n switch (message.payload.kind) {\n case 'query': {\n this._handleQueryMessage();\n break;\n }\n case 'post': {\n this._handlePostMessage(message.payload);\n break;\n }\n }\n }),\n );\n\n void this._space\n .postMessage(this._channel, {\n kind: 'query',\n } satisfies ProtocolMessage)\n .catch((err) => {\n log.debug('failed to query awareness', { err });\n });\n }\n\n close(): void {\n void this._ctx?.dispose();\n this._ctx = undefined;\n this._postTask = undefined;\n }\n\n getRemoteStates(): AwarenessState[] {\n return Array.from(this._remoteStates.values());\n }\n\n update(position: AwarenessPosition | undefined): void {\n invariant(this._postTask);\n this._localState = {\n peerId: this._peerId,\n position,\n info: this._info,\n };\n\n this._postTask.schedule();\n }\n\n private _handleQueryMessage(): void {\n invariant(this._postTask);\n this._postTask.schedule();\n }\n\n private _handlePostMessage(message: ProtocolMessage): void {\n invariant(message.kind === 'post');\n // TODO(wittjosiah): Is it helpful or confusing to show cursors for self on other devices?\n this._remoteStates.set(message.state.peerId, message.state);\n this.remoteStateChange.emit();\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n// Based on a demo by Joel Besada and Kushagra Gour.\n// https://twitter.com/JoelBesada/status/670343885655293952\n// https://github.com/chinchang/code-blast-codemirror/blob/master/code-blast.js\n//\n\nimport { type Extension } from '@codemirror/state';\nimport { EditorView, keymap } from '@codemirror/view';\nimport defaultsDeep from 'lodash.defaultsdeep';\n\nimport { invariant } from '@dxos/invariant';\n\nexport type BlastOptions = {\n effect?: number;\n maxParticles: number;\n particleGravity: number;\n particleAlphaFadeout: number;\n particleSize: { min: number; max: number };\n particleNumRange: { min: number; max: number };\n particleVelocityRange: { x: [number, number]; y: [number, number] };\n particleShrinkRate: number;\n shakeIntensity: number;\n color?: () => number[];\n};\n\nexport const defaultOptions: BlastOptions = {\n effect: 2,\n maxParticles: 200,\n particleGravity: 0.08,\n particleAlphaFadeout: 0.996,\n particleSize: { min: 2, max: 8 },\n particleNumRange: { min: 5, max: 10 },\n particleVelocityRange: { x: [-1, 1], y: [-3.5, -1.5] },\n particleShrinkRate: 0.95,\n shakeIntensity: 5,\n};\n\nexport const blast = (options: Partial<BlastOptions> = defaultOptions): Extension => {\n let blaster: Blaster | undefined;\n let last = 0;\n\n const getPoint = (view: EditorView, pos: number) => {\n const { left: x = 0, top: y = 0 } = view.coordsForChar(pos) ?? {};\n const element = document.elementFromPoint(x, y);\n\n const { offsetLeft: left = 0, offsetTop: top = 0 } = view.scrollDOM.parentElement ?? {};\n const point = { x: x - left, y: y - top };\n\n return { element, point };\n };\n\n return [\n // Cursor moved.\n EditorView.updateListener.of((update) => {\n // NOTE: The MarkdownEditor may recreated the EditorView.\n if (blaster?.node !== update.view.scrollDOM) {\n if (blaster) {\n blaster.destroy();\n }\n\n blaster = new Blaster(\n update.view.scrollDOM,\n defaultsDeep(\n {\n particleGravity: 0.2,\n particleShrinkRate: 0.995,\n color: () => [100 + Math.random() * 100, 0, 0],\n },\n options,\n defaultOptions,\n ),\n );\n blaster.initialize();\n blaster.start(); // TODO(burdon): Stop/clean-up.\n } else {\n blaster.resize();\n }\n\n const current = update.state.selection.main.head;\n if (current !== last) {\n last = current;\n // TODO(burdon): Null if end of line.\n const { element, point } = getPoint(update.view, current - 1);\n if (element && point) {\n blaster.spawn({ element, point });\n }\n }\n }),\n\n keymap.of([\n {\n any: (_, event) => {\n if (blaster) {\n if (event.key === 'Enter' && event.shiftKey) {\n blaster.shake({ time: 0.8 });\n return true;\n }\n }\n\n return false;\n },\n },\n ]),\n ];\n};\n\n//\n// Blaster (no CM deps).\n//\n\nclass Blaster {\n private readonly _effect: Effect;\n\n _canvas: HTMLCanvasElement | undefined;\n _ctx: CanvasRenderingContext2D | undefined | null;\n\n _running = false;\n _lastTime: number | undefined;\n _shakeTime = 0;\n _shakeTimeMax = 0;\n\n _particles: Particle[] = [];\n _particlePointer = 0;\n\n _lastPoint = { x: 0, y: 0 };\n\n constructor(\n private readonly _node: HTMLElement,\n private readonly _options: BlastOptions,\n ) {\n this._effect = this._options.effect === 1 ? new Effect1(_options) : new Effect2(_options);\n }\n\n get node() {\n return this._node;\n }\n\n initialize(): void {\n // console.log('initialize');\n invariant(!this._canvas && !this._ctx);\n\n this._canvas = document.createElement('canvas');\n this._canvas.id = 'code-blast-canvas';\n this._canvas.style.position = 'absolute';\n this._canvas.style.zIndex = '0';\n this._canvas.style.pointerEvents = 'none';\n // this._canvas.style.border = '2px dashed red';\n\n this._ctx = this._canvas.getContext('2d');\n\n const parent = this._node.parentElement?.parentElement;\n parent?.appendChild(this._canvas);\n\n this.resize();\n }\n\n destroy(): void {\n this.stop();\n // console.log('destroy');\n if (this._canvas) {\n this._canvas.remove();\n this._canvas = undefined;\n this._ctx = undefined;\n }\n }\n\n resize(): void {\n if (this._node.parentElement && this._canvas) {\n const { offsetLeft: x, offsetTop: y, offsetWidth: width, offsetHeight: height } = this._node.parentElement;\n this._canvas.style.top = `${y}px`;\n this._canvas.style.left = `${x}px`;\n this._canvas.width = width;\n this._canvas.height = height;\n }\n }\n\n start(): void {\n // console.log('start');\n invariant(this._canvas && this._ctx);\n this._running = true;\n this.loop();\n }\n\n stop(): void {\n // console.log('stop');\n this._running = false;\n this._node.style.transform = 'translate(0px, 0px)';\n }\n\n loop(): void {\n if (!this._running || !this._canvas || !this._ctx) {\n return;\n }\n\n this._ctx.clearRect(0, 0, this._canvas.width ?? 0, this._canvas.height ?? 0);\n\n // Calculate the delta from the previous frame.\n const now = new Date().getTime();\n this._lastTime ??= now;\n const dt = (now - this._lastTime) / 1000;\n this._lastTime = now;\n\n if (this._shakeTime > 0) {\n this._shakeTime -= dt;\n const magnitude = (this._shakeTime / this._shakeTimeMax) * this._options.shakeIntensity;\n const shakeX = random(-magnitude, magnitude);\n const shakeY = random(-magnitude, magnitude);\n this._node!.style.transform = `translate(${shakeX}px,${shakeY}px)`;\n }\n\n this.drawParticles();\n\n requestAnimationFrame(this.loop.bind(this));\n }\n\n shake = throttle<{ time: number }>(({ time }) => {\n this._shakeTime = this._shakeTimeMax || time;\n this._shakeTimeMax = time;\n }, 100);\n\n spawn = throttle<{ element: Element; point: { x: number; y: number } }>(({ element, point }) => {\n const color = getRGBComponents(element, this._options.color);\n const numParticles = random(this._options.particleNumRange.min, this._options.particleNumRange.max);\n const dir = this._lastPoint.x === point.x ? 0 : this._lastPoint.x < point.x ? 1 : -1;\n this._lastPoint = point;\n for (let i = numParticles; i--; i > 0) {\n this._particles[this._particlePointer] = this._effect.create(point.x - dir * 16, point.y, color);\n this._particlePointer = (this._particlePointer + 1) % this._options.maxParticles;\n }\n }, 100);\n\n drawParticles(): void {\n for (let i = this._particles.length; i--; i > 0) {\n const particle = this._particles[i];\n if (!particle) {\n continue;\n }\n\n if (particle.alpha < 0.01 || particle.size <= 0.5) {\n continue;\n }\n\n this._effect.update(this._ctx!, particle);\n }\n }\n}\n\n//\n// Effects\n//\n\ntype Particle = {\n x: number;\n y: number;\n vx: number;\n vy: number;\n size: number;\n color: (string | number)[];\n alpha: number;\n theta?: number;\n drag?: number;\n wander?: number;\n};\n\nabstract class Effect {\n constructor(protected readonly _options: BlastOptions) {}\n abstract create(x: number, y: number, color: Particle['color']): Particle;\n abstract update(ctx: CanvasRenderingContext2D, particle: Particle): void;\n}\n\nclass Effect1 extends Effect {\n create(x: number, y: number, color: Particle['color']) {\n return {\n x,\n y: y + 10,\n vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),\n vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),\n size: random(this._options.particleSize.min, this._options.particleSize.max),\n color,\n alpha: 1,\n };\n }\n\n update(ctx: CanvasRenderingContext2D, particle: Particle): void {\n particle.vy += this._options.particleGravity;\n particle.x += particle.vx;\n particle.y += particle.vy;\n particle.alpha *= this._options.particleAlphaFadeout;\n\n ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;\n ctx.fillRect(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, particle.size);\n }\n}\n\n/**\n * Based on Soulwire's demo.\n * http://codepen.io/soulwire/pen/foktm\n */\nclass Effect2 extends Effect {\n create(x: number, y: number, color: Particle['color']) {\n return {\n x,\n y: y + 10,\n vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),\n vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),\n size: random(this._options.particleSize.min, this._options.particleSize.max),\n color,\n alpha: 1,\n theta: (random(0, 360) * Math.PI) / 180,\n drag: 0.92,\n wander: 0.15,\n };\n }\n\n update(ctx: CanvasRenderingContext2D, particle: Particle): void {\n particle.vy += this._options.particleGravity;\n particle.x += particle.vx;\n particle.y += particle.vy;\n particle.vx *= particle.drag!;\n particle.vy *= particle.drag!;\n particle.theta! += random(-0.5, 0.5);\n particle.vx += Math.sin(particle.theta!) * 0.1;\n particle.vy += Math.cos(particle.theta!) * 0.1;\n particle.size *= this._options.particleShrinkRate;\n particle.alpha *= this._options.particleAlphaFadeout;\n\n ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;\n ctx.beginPath();\n ctx.arc(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, 0, 2 * Math.PI);\n ctx.fill();\n }\n}\n\n//\n// Utils\n//\n\nfunction throttle<T>(callback: (arg: T) => void, limit: number): (arg: T) => void {\n let wait = false;\n return function (...args: any[]) {\n if (!wait) {\n // @ts-ignore\n callback.apply(this, args);\n wait = true;\n setTimeout(() => {\n wait = false;\n }, limit);\n }\n };\n}\n\nconst getRGBComponents = (node: Element, color: BlastOptions['color']): Particle['color'] => {\n if (typeof color === 'function') {\n return color();\n }\n\n const bgColor = getComputedStyle(node).color;\n if (bgColor) {\n const x = bgColor.match(/(\\d+), (\\d+), (\\d+)/)?.slice(1);\n if (x) {\n return x;\n }\n }\n\n return [50, 50, 50];\n};\n\nconst random = (min: number, max: number) => {\n if (!max) {\n max = min;\n min = 0;\n }\n\n return min + ~~(Math.random() * (max - min + 1));\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { StateEffect } from '@codemirror/state';\nimport { type KeyBinding, type Command, type EditorView } from '@codemirror/view';\n\nimport { commandState } from './state';\n\nexport type Action =\n | {\n type: 'insert';\n text: string;\n }\n | {\n type: 'cancel';\n };\n\nexport type ActionHandler = (action: Action) => void;\n\nexport const openEffect = StateEffect.define<{ pos: number; fullWidth?: boolean }>();\nexport const closeEffect = StateEffect.define<null>();\n\nexport const openCommand: Command = (view: EditorView) => {\n if (view.state.field(commandState, false)) {\n const selection = view.state.selection.main;\n const line = view.state.doc.lineAt(selection.from);\n if (line.from === selection.from && line.from === line.to) {\n view.dispatch({ effects: openEffect.of({ pos: selection.anchor, fullWidth: true }) });\n return true;\n }\n }\n\n return false;\n};\n\nexport const closeCommand: Command = (view: EditorView) => {\n if (view.state.field(commandState, false)) {\n view.dispatch({ effects: closeEffect.of(null) });\n return true;\n }\n\n return false;\n};\n\nexport const commandKeyBindings: readonly KeyBinding[] = [\n {\n key: '/',\n preventDefault: true,\n run: openCommand,\n },\n {\n key: 'Escape',\n run: closeCommand,\n },\n];\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { StateField } from '@codemirror/state';\nimport { showTooltip, type EditorView, type Tooltip, type TooltipView } from '@codemirror/view';\n\nimport { closeEffect, type Action, openEffect } from './action';\nimport { type CommandOptions } from './command';\nimport { type RenderCallback } from '../../types';\nimport { singleValueFacet } from '../../util';\n\nexport const commandConfig = singleValueFacet<CommandOptions>();\n\nexport type PopupOptions = {\n renderDialog: RenderCallback<{ onAction: (action?: Action) => void }>;\n};\n\ntype CommandState = {\n tooltip?: Tooltip;\n};\n\nexport const commandState = StateField.define<CommandState>({\n create: () => ({}),\n update: (state, tr) => {\n for (const effect of tr.effects) {\n if (effect.is(closeEffect)) {\n return {};\n }\n\n const { renderDialog } = tr.state.facet(commandConfig);\n if (effect.is(openEffect) && renderDialog) {\n const { pos, fullWidth } = effect.value;\n const tooltip: Tooltip = {\n pos,\n above: false,\n arrow: false,\n strictSide: true,\n create: (view: EditorView) => {\n const root = document.createElement('div');\n const tooltipView: TooltipView = {\n dom: root,\n mount: (view: EditorView) => {\n if (fullWidth) {\n const parent = root.parentElement!;\n const { paddingLeft, paddingRight } = window.getComputedStyle(parent);\n const widthWithoutPadding = parent.clientWidth - parseFloat(paddingLeft) - parseFloat(paddingRight);\n root.style.width = `${widthWithoutPadding}px`;\n }\n\n // Render react component.\n renderDialog(\n root,\n {\n onAction: (action) => {\n view.dispatch({ effects: closeEffect.of(null) });\n switch (action?.type) {\n case 'insert': {\n // Insert into editor.\n const text = action.text + '\\n';\n view.dispatch({\n changes: { from: pos, insert: text },\n selection: { anchor: pos + text.length },\n });\n break;\n }\n }\n\n // NOTE: Truncates text if set focus immediately.\n requestAnimationFrame(() => view.focus());\n },\n },\n view,\n );\n },\n };\n\n return tooltipView;\n },\n };\n\n return { tooltip };\n }\n }\n\n return state;\n },\n provide: (field) => [showTooltip.from(field, (value) => value.tooltip ?? null)],\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Prec, type Extension } from '@codemirror/state';\nimport { EditorView, keymap } from '@codemirror/view';\n\nimport { isNonNullable } from '@dxos/util';\n\nimport { closeEffect, commandKeyBindings } from './action';\nimport { hint, type HintOptions } from './hint';\nimport { commandConfig, commandState, type PopupOptions } from './state';\n\n// TODO(burdon): Create knowledge base for CM notes and ideas.\n// https://discuss.codemirror.net/t/inline-code-hints-like-vscode/5533/4\n// https://github.com/saminzadeh/codemirror-extension-inline-suggestion\n// https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/ui/components/text_editor/config.ts#L370\n\nexport type CommandOptions = Partial<PopupOptions & HintOptions>;\n\nexport const command = (options: CommandOptions = {}): Extension => {\n return [\n Prec.highest(keymap.of(commandKeyBindings)),\n commandConfig.of(options),\n commandState,\n options.onHint && hint(options),\n EditorView.focusChangeEffect.of((_, focusing) => (focusing ? closeEffect.of(null) : null)),\n EditorView.theme({\n '.cm-tooltip': {\n background: 'transparent',\n },\n }),\n ].filter(isNonNullable);\n};\n", "//\n// Copyright 2024 DXOS.org\n// Based on https://github.com/codemirror/view/blob/main/src/placeholder.ts\n//\n\nimport { RangeSetBuilder } from '@codemirror/state';\nimport { Decoration, EditorView, ViewPlugin, type ViewUpdate, WidgetType } from '@codemirror/view';\n\nimport { commandState } from './state';\nimport { clientRectsFor, flattenRect } from '../../util';\n\nexport type HintOptions = {\n delay?: number;\n onHint?: () => string | undefined;\n};\n\nexport const hint = ({ delay = 3_000, onHint }: HintOptions) => {\n return ViewPlugin.fromClass(\n class {\n decorations = Decoration.none;\n timeout: ReturnType<typeof setTimeout> | undefined;\n\n update(update: ViewUpdate) {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n\n const builder = new RangeSetBuilder<Decoration>();\n const cState = update.view.state.field(commandState, false);\n if (!cState?.tooltip) {\n const selection = update.view.state.selection.main;\n const line = update.view.state.doc.lineAt(selection.from);\n // Only show if blank line.\n if (selection.from === selection.to && line.from === line.to) {\n // Set timeout to add decoration after delay.\n this.timeout = setTimeout(() => {\n const hint = onHint?.();\n if (hint) {\n const builder = new RangeSetBuilder<Decoration>();\n builder.add(selection.from, selection.to, Decoration.widget({ widget: new Hint(hint) }));\n this.decorations = builder.finish();\n update.view.update([]);\n }\n }, delay);\n }\n }\n\n this.decorations = builder.finish();\n }\n\n destroy() {\n if (this.timeout) {\n clearTimeout(this.timeout);\n }\n }\n },\n {\n provide: (plugin) => [EditorView.decorations.of((view) => view.plugin(plugin)?.decorations ?? Decoration.none)],\n },\n );\n};\n\nexport class Hint extends WidgetType {\n constructor(readonly content: string | HTMLElement) {\n super();\n }\n\n toDOM(): HTMLSpanElement {\n const wrap = document.createElement('span');\n wrap.className = 'cm-placeholder';\n wrap.style.pointerEvents = 'none';\n wrap.appendChild(typeof this.content === 'string' ? document.createTextNode(this.content) : this.content);\n if (typeof this.content === 'string') {\n wrap.setAttribute('aria-label', 'placeholder ' + this.content);\n } else {\n wrap.setAttribute('aria-hidden', 'true');\n }\n\n return wrap;\n }\n\n override coordsAt(dom: HTMLElement) {\n const rects = dom.firstChild ? clientRectsFor(dom.firstChild) : [];\n if (!rects.length) {\n return null;\n }\n\n const style = window.getComputedStyle(dom.parentNode as HTMLElement);\n const rect = flattenRect(rects[0], style.direction !== 'rtl');\n const lineHeight = parseInt(style.lineHeight);\n if (rect.bottom - rect.top > lineHeight * 1.5) {\n return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight };\n }\n\n return rect;\n }\n\n override ignoreEvent(): boolean {\n return false;\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { RangeSetBuilder, StateField, StateEffect, Prec } from '@codemirror/state';\nimport { EditorView, ViewPlugin, type ViewUpdate, Decoration, keymap, type DecorationSet } from '@codemirror/view';\n\nimport { placeholder, type PlaceholderOptions } from './placeholder';\nimport { type Range } from '../../types';\n\nexport type CommandMenuOptions = {\n trigger: string | string[];\n placeholder?: Partial<PlaceholderOptions>;\n\n // TODO(burdon): Replace with onKey?\n onClose?: () => void;\n onArrowDown?: () => void;\n onArrowUp?: () => void;\n onEnter?: () => void;\n\n onTextChange?: (trigger: string, text: string) => void;\n};\n\nexport const commandMenu = (options: CommandMenuOptions) => {\n const commandMenuPlugin = ViewPlugin.fromClass(\n class {\n decorations: DecorationSet = Decoration.none;\n\n constructor(readonly view: EditorView) {}\n\n // TODO(wittjosiah): The decorations are repainted on every update, this occasionally causes menu to flicker.\n update(update: ViewUpdate) {\n const builder = new RangeSetBuilder<Decoration>();\n const selection = update.view.state.selection.main;\n const { range: activeRange, trigger } = update.view.state.field(commandMenuState) ?? {};\n\n // Check if we should show the widget - only if cursor is within the active command range.\n const shouldShowWidget = activeRange && selection.head >= activeRange.from && selection.head <= activeRange.to;\n if (shouldShowWidget) {\n // Create mark decoration that wraps the entire line content in a dx-ref-tag.\n builder.add(\n activeRange.from,\n activeRange.to,\n Decoration.mark({\n tagName: 'dx-ref-tag',\n class: 'cm-ref-tag',\n attributes: {\n 'data-auto-trigger': 'true',\n 'data-trigger': trigger!,\n },\n }),\n );\n }\n\n const activeRangeChanged = update.transactions.some((tr) =>\n tr.effects.some((effect) => effect.is(commandRangeEffect)),\n );\n if (activeRange && activeRangeChanged && trigger) {\n const content = update.view.state.sliceDoc(\n activeRange.from + 1, // Skip the trigger character.\n activeRange.to,\n );\n options.onTextChange?.(trigger, content);\n }\n\n this.decorations = builder.finish();\n }\n },\n {\n decorations: (v) => v.decorations,\n },\n );\n\n const triggers = Array.isArray(options.trigger) ? options.trigger : [options.trigger];\n\n const commandKeymap = keymap.of([\n ...triggers.map((trigger) => ({\n key: trigger,\n preventDefault: true,\n run: (view: EditorView) => {\n const selection = view.state.selection.main;\n const line = view.state.doc.lineAt(selection.head);\n\n // Check if we should trigger the command menu:\n // 1. Empty lines or at the beginning of a line\n // 2. When there's a preceding space\n if (\n line.text.trim() === '' ||\n selection.head === line.from ||\n (selection.head > line.from && line.text[selection.head - line.from - 1] === ' ')\n ) {\n // Insert and select the trigger.\n view.dispatch({\n changes: { from: selection.head, insert: trigger },\n selection: { anchor: selection.head + 1, head: selection.head + 1 },\n effects: commandRangeEffect.of({ trigger, range: { from: selection.head, to: selection.head + 1 } }),\n });\n\n return true;\n }\n\n return false;\n },\n })),\n {\n key: 'Enter',\n run: (view) => {\n const activeRange = view.state.field(commandMenuState)?.range;\n if (activeRange) {\n view.dispatch({ changes: { from: activeRange.from, to: activeRange.to, insert: '' } });\n options.onEnter?.();\n return true;\n }\n\n return false;\n },\n },\n {\n key: 'ArrowDown',\n run: (view) => {\n const activeRange = view.state.field(commandMenuState)?.range;\n if (activeRange) {\n options.onArrowDown?.();\n return true;\n }\n\n return false;\n },\n },\n {\n key: 'ArrowUp',\n run: (view) => {\n const activeRange = view.state.field(commandMenuState)?.range;\n if (activeRange) {\n options.onArrowUp?.();\n return true;\n }\n\n return false;\n },\n },\n ]);\n\n // Listen for selection and document changes to clean up the command menu.\n const updateListener = EditorView.updateListener.of((update) => {\n const { trigger, range: activeRange } = update.view.state.field(commandMenuState) ?? {};\n if (!activeRange || !trigger) {\n return;\n }\n\n const selection = update.view.state.selection.main;\n const firstChar = update.view.state.doc.sliceString(activeRange.from, activeRange.from + 1);\n const shouldRemove =\n firstChar !== trigger || // Trigger deleted.\n selection.head < activeRange.from || // Cursor moved before the range.\n selection.head > activeRange.to + 1; // Cursor moved after the range (+1 to handle selection changing before doc).\n\n const nextRange = shouldRemove\n ? null\n : update.docChanged\n ? { from: activeRange.from, to: selection.head }\n : activeRange;\n if (nextRange !== activeRange) {\n update.view.dispatch({ effects: commandRangeEffect.of(nextRange ? { trigger, range: nextRange } : null) });\n }\n\n // TODO(burdon): Should delete if user presses escape? How else to insert the trigger character?\n if (shouldRemove) {\n options.onClose?.();\n }\n });\n\n return [\n Prec.highest(commandKeymap),\n placeholder(\n Object.assign(\n {\n content: `Press '${Array.isArray(options.trigger) ? options.trigger[0] : options.trigger}' for commands`,\n },\n options.placeholder,\n ),\n ),\n updateListener,\n commandMenuState,\n commandMenuPlugin,\n ];\n};\n\ntype CommandState = {\n trigger: string;\n range: Range;\n};\n\n// State effects for managing command menu state.\nexport const commandRangeEffect = StateEffect.define<CommandState | null>();\n\n// State field to track the active command menu range.\nconst commandMenuState = StateField.define<CommandState | null>({\n create: () => null,\n update: (value, tr) => {\n let newValue = value;\n for (const effect of tr.effects) {\n if (effect.is(commandRangeEffect)) {\n newValue = effect.value;\n }\n }\n\n return newValue;\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n// Based on https://github.com/codemirror/view/blob/main/src/placeholder.ts\n//\n\nimport { type Extension } from '@codemirror/state';\nimport { Decoration, EditorView, WidgetType, ViewPlugin, type ViewUpdate } from '@codemirror/view';\n\nimport { clientRectsFor, flattenRect } from '../../util';\n\ntype Content = string | HTMLElement | ((view: EditorView) => HTMLElement);\n\nexport type PlaceholderOptions = {\n delay?: number;\n content: Content;\n};\n\nexport const placeholder = ({ delay = 3_000, content }: PlaceholderOptions): Extension => {\n const plugin = ViewPlugin.fromClass(\n class {\n decorations = Decoration.none;\n timeout: ReturnType<typeof setTimeout> | undefined;\n\n update(update: ViewUpdate) {\n if (this.timeout) {\n window.clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n\n // Check if the active line (where cursor is) is empty.\n const activeLine = update.view.state.doc.lineAt(update.view.state.selection.main.head);\n const isEmpty = activeLine.text.trim() === '';\n if (isEmpty) {\n // Create widget decoration at the start of the current line.\n const lineStart = activeLine.from;\n this.timeout = setTimeout(() => {\n this.decorations = Decoration.set([\n Decoration.widget({\n widget: new Placeholder(content),\n side: 1,\n }).range(lineStart),\n ]);\n\n update.view.update([]);\n }, delay);\n }\n\n this.decorations = Decoration.none;\n }\n\n destroy() {\n if (this.timeout) {\n clearTimeout(this.timeout);\n }\n }\n },\n {\n provide: (plugin) => {\n return [EditorView.decorations.of((view) => view.plugin(plugin)?.decorations ?? Decoration.none)];\n },\n },\n );\n\n return typeof content === 'string'\n ? [plugin, EditorView.contentAttributes.of({ 'aria-placeholder': content })]\n : plugin;\n};\n\nclass Placeholder extends WidgetType {\n constructor(readonly content: Content) {\n super();\n }\n\n toDOM(view: EditorView) {\n const wrap = document.createElement('span');\n wrap.className = 'cm-placeholder';\n wrap.style.pointerEvents = 'none';\n wrap.appendChild(\n typeof this.content === 'string'\n ? document.createTextNode(this.content)\n : typeof this.content === 'function'\n ? this.content(view)\n : this.content.cloneNode(true),\n );\n wrap.setAttribute('aria-hidden', 'true');\n return wrap;\n }\n\n override coordsAt(dom: HTMLElement) {\n const rects = dom.firstChild ? clientRectsFor(dom.firstChild) : [];\n if (!rects.length) {\n return null;\n }\n\n const style = window.getComputedStyle(dom.parentNode as HTMLElement);\n const rect = flattenRect(rects[0], style.direction !== 'rtl');\n const lineHeight = parseInt(style.lineHeight);\n if (rect.bottom - rect.top > lineHeight * 1.5) {\n return {\n left: rect.left,\n right: rect.right,\n top: rect.top,\n bottom: rect.top + lineHeight,\n };\n }\n\n return rect;\n }\n\n override ignoreEvent() {\n return false;\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { EditorView, ViewPlugin, type ViewUpdate } from '@codemirror/view';\n\nimport { type CleanupFn, addEventListener } from '@dxos/async';\n\nimport { closeEffect, openEffect } from './action';\n\nexport type FloatingMenuOptions = {\n icon?: string;\n height?: number;\n padding?: number;\n};\n\nexport const floatingMenu = (options: FloatingMenuOptions = {}) => [\n ViewPlugin.fromClass(\n class {\n view: EditorView;\n tag: HTMLElement;\n rafId?: number | null;\n cleanup?: CleanupFn;\n\n constructor(view: EditorView) {\n this.view = view;\n\n // Position context.\n const container = view.scrollDOM;\n if (getComputedStyle(container).position === 'static') {\n container.style.position = 'relative';\n }\n\n {\n const icon = document.createElement('dx-icon');\n icon.setAttribute('icon', options.icon ?? 'ph--dots-three-vertical--regular');\n const button = document.createElement('button');\n button.appendChild(icon);\n\n this.tag = document.createElement('dx-ref-tag');\n this.tag.classList.add('cm-ref-tag');\n this.tag.appendChild(button);\n }\n\n container.appendChild(this.tag);\n\n // Listen for scroll events.\n const handler = () => this.scheduleUpdate();\n this.cleanup = addEventListener(container, 'scroll', handler);\n this.scheduleUpdate();\n }\n\n destroy() {\n this.cleanup?.();\n this.tag.remove();\n if (this.rafId != null) {\n cancelAnimationFrame(this.rafId);\n }\n }\n\n update(update: ViewUpdate) {\n this.tag.dataset.focused = update.view.hasFocus ? 'true' : 'false';\n if (!update.view.hasFocus) {\n return;\n }\n\n // TODO(burdon): Timer to fade in/out.\n if (update.transactions.some((tr) => tr.effects.some((effect) => effect.is(openEffect)))) {\n this.tag.style.display = 'none';\n this.tag.classList.add('opacity-10');\n } else if (update.transactions.some((tr) => tr.effects.some((effect) => effect.is(closeEffect)))) {\n this.tag.style.display = 'block';\n } else if (\n update.docChanged ||\n update.focusChanged ||\n update.geometryChanged ||\n update.selectionSet ||\n update.viewportChanged\n ) {\n this.scheduleUpdate();\n }\n }\n\n updateButtonPosition() {\n const { x, width } = this.view.contentDOM.getBoundingClientRect();\n\n const pos = this.view.state.selection.main.head;\n const line = this.view.lineBlockAt(pos);\n const coords = this.view.coordsAtPos(line.from);\n if (!coords) {\n return;\n }\n\n const lineHeight = coords.bottom - coords.top;\n const dy = (lineHeight - (options.height ?? 32)) / 2;\n\n const offsetTop = coords.top + dy;\n const offsetLeft = x + width + (options.padding ?? 8);\n\n this.tag.style.top = `${offsetTop}px`;\n this.tag.style.left = `${offsetLeft}px`;\n this.tag.style.display = 'block';\n }\n\n scheduleUpdate() {\n if (this.rafId != null) {\n cancelAnimationFrame(this.rafId);\n }\n\n this.rafId = requestAnimationFrame(this.updateButtonPosition.bind(this));\n }\n },\n ),\n\n EditorView.theme({\n '.cm-ref-tag': {\n position: 'fixed',\n padding: '0',\n border: 'none',\n opacity: '0',\n },\n '[data-has-focus] & .cm-ref-tag': {\n opacity: '1',\n },\n '.cm-ref-tag button': {\n display: 'grid',\n alignItems: 'center',\n justifyContent: 'center',\n width: '2rem',\n height: '2rem',\n },\n }),\n];\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type EditorView } from '@codemirror/view';\nimport { type RefObject, useCallback, useMemo, useRef, useState } from 'react';\n\nimport { type DxRefTag, type DxRefTagActivate } from '@dxos/lit-ui';\nimport { type MaybePromise } from '@dxos/util';\n\nimport { commandMenu, commandRangeEffect } from './command-menu';\nimport { type PlaceholderOptions } from './placeholder';\nimport { getItem, getNextItem, getPreviousItem, type CommandMenuGroup, type CommandMenuItem } from '../../components';\n\nexport type UseCommandMenuOptions = {\n viewRef: RefObject<EditorView | undefined>;\n trigger: string | string[];\n placeholder?: Partial<PlaceholderOptions>;\n getMenu: (trigger: string, query?: string) => MaybePromise<CommandMenuGroup[]>;\n};\n\nexport const useCommandMenu = ({ viewRef, trigger, placeholder, getMenu }: UseCommandMenuOptions) => {\n const triggerRef = useRef<DxRefTag | null>(null);\n const currentRef = useRef<CommandMenuItem | null>(null);\n const groupsRef = useRef<CommandMenuGroup[]>([]);\n const [currentItem, setCurrentItem] = useState<string>();\n const [open, setOpen] = useState(false);\n const [_, refresh] = useState({});\n\n const handleOpenChange = useCallback(\n async (open: boolean, trigger?: string) => {\n if (open && trigger) {\n groupsRef.current = await getMenu(trigger);\n }\n setOpen(open);\n if (!open) {\n triggerRef.current = null;\n setCurrentItem(undefined);\n viewRef.current?.dispatch({ effects: [commandRangeEffect.of(null)] });\n }\n },\n [getMenu],\n );\n\n const handleActivate = useCallback(\n async (event: DxRefTagActivate) => {\n const item = getItem(groupsRef.current, currentItem);\n if (item) {\n currentRef.current = item;\n }\n\n triggerRef.current = event.trigger;\n const triggerKey = event.trigger.getAttribute('data-trigger');\n if (!open && triggerKey) {\n await handleOpenChange(true, triggerKey);\n }\n },\n [open, handleOpenChange],\n );\n\n const handleSelect = useCallback((item: CommandMenuItem) => {\n const view = viewRef.current;\n if (!view) {\n return;\n }\n\n const selection = view.state.selection.main;\n void item.onSelect?.(view, selection.head);\n }, []);\n\n const serializedTrigger = Array.isArray(trigger) ? trigger.join(',') : trigger;\n const _commandMenu = useMemo(() => {\n return commandMenu({\n trigger,\n placeholder,\n onClose: () => handleOpenChange(false),\n onArrowDown: () => {\n setCurrentItem((currentItem) => {\n const next = getNextItem(groupsRef.current, currentItem);\n currentRef.current = next;\n return next.id;\n });\n },\n onArrowUp: () => {\n setCurrentItem((currentItem) => {\n const previous = getPreviousItem(groupsRef.current, currentItem);\n currentRef.current = previous;\n return previous.id;\n });\n },\n onEnter: () => {\n if (currentRef.current) {\n handleSelect(currentRef.current);\n }\n },\n onTextChange: async (trigger, text) => {\n groupsRef.current = await getMenu(trigger, text);\n const firstItem = groupsRef.current.filter((group) => group.items.length > 0)[0]?.items[0];\n if (firstItem) {\n setCurrentItem(firstItem.id);\n currentRef.current = firstItem;\n }\n refresh({});\n },\n });\n }, [handleOpenChange, getMenu, serializedTrigger, placeholder]);\n\n return {\n commandMenu: _commandMenu,\n currentItem,\n groupsRef,\n ref: triggerRef,\n open,\n onActivate: handleActivate,\n onOpenChange: setOpen,\n onSelect: handleSelect,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { EditorSelection, Prec, RangeSetBuilder, type Extension } from '@codemirror/state';\nimport {\n type Command,\n Decoration,\n type DecorationSet,\n type EditorView,\n keymap,\n ViewPlugin,\n type ViewUpdate,\n} from '@codemirror/view';\n\nimport { Hint } from './hint';\n\nexport type TypeaheadContext = { line: string };\n\n// TODO(burdon): Option to complete only at end of line?\nexport type TypeaheadOptions = {\n onComplete?: (context: TypeaheadContext) => string | undefined;\n};\n\n/**\n * CodeMirror extension for typeahead completion.\n */\nexport const typeahead = ({ onComplete }: TypeaheadOptions = {}): Extension => {\n let hint: string | undefined;\n\n const complete: Command = (view: EditorView) => {\n if (!hint) {\n return false;\n }\n\n const selection = view.state.selection.main;\n view.dispatch({\n changes: [{ from: selection.from, to: selection.to, insert: hint }],\n selection: EditorSelection.cursor(selection.from + hint.length),\n });\n\n return true;\n };\n\n return [\n ViewPlugin.fromClass(\n class {\n decorations: DecorationSet = Decoration.none;\n update(update: ViewUpdate) {\n const builder = new RangeSetBuilder<Decoration>();\n const selection = update.view.state.selection.main;\n const line = update.view.state.doc.lineAt(selection.from);\n\n // TODO(burdon): Check at end of line and matches start of previous word.\n // TODO(burdon): Context grammar.\n if (selection.from === selection.to && selection.from === line.to) {\n const str = update.state.sliceDoc(line.from, selection.from);\n hint = onComplete?.({ line: str });\n if (hint) {\n builder.add(selection.from, selection.to, Decoration.widget({ widget: new Hint(hint) }));\n }\n }\n\n this.decorations = builder.finish();\n }\n },\n {\n decorations: (v) => v.decorations,\n },\n ),\n\n // Keys.\n Prec.highest(\n keymap.of([\n {\n key: 'Tab',\n preventDefault: true,\n run: complete,\n },\n {\n key: 'ArrowRight',\n preventDefault: true,\n run: complete,\n },\n ]),\n ),\n ];\n};\n\n/**\n * Util to match current line to a static list of completions.\n */\nexport const staticCompletion =\n (completions: string[], defaultCompletion?: string) =>\n ({ line }: TypeaheadContext) => {\n if (line.length === 0 && defaultCompletion) {\n return defaultCompletion;\n }\n\n const words = line.split(/\\s+/).filter(Boolean);\n if (words.length) {\n const word = words.at(-1)!;\n for (const completion of completions) {\n const match = matchCompletion(completion, word);\n if (match) {\n return match;\n }\n }\n }\n };\n\nexport const matchCompletion = (completion: string, word: string): string | undefined => {\n if (completion.length > word.length && completion.startsWith(word)) {\n return completion.slice(word.length);\n }\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { invertedEffects } from '@codemirror/commands';\nimport { type ChangeDesc, type Extension, StateEffect, StateField, type Text } from '@codemirror/state';\nimport {\n hoverTooltip,\n keymap,\n type Command,\n Decoration,\n EditorView,\n type Rect,\n type PluginValue,\n ViewPlugin,\n} from '@codemirror/view';\nimport sortBy from 'lodash.sortby';\nimport { useEffect } from 'react';\n\nimport { debounce, type CleanupFn } from '@dxos/async';\nimport { log } from '@dxos/log';\nimport { isNonNullable } from '@dxos/util';\n\nimport { documentId } from './selection';\nimport { type RenderCallback, type Comment, type Range } from '../types';\nimport { Cursor, singleValueFacet, callbackWrapper } from '../util';\n\n//\n// State management.\n//\n\ntype CommentState = {\n comment: Comment;\n range: Range;\n location?: Rect | null;\n};\n\ntype SelectionState = {\n current?: string;\n closest?: string;\n};\n\nexport type CommentsState = {\n id?: string;\n comments: CommentState[];\n selection: SelectionState;\n};\n\nexport const setComments = StateEffect.define<{ id: string; comments: Comment[] }>();\n\nexport const setSelection = StateEffect.define<SelectionState>();\n\nconst setCommentState = StateEffect.define<CommentsState>();\n\n/**\n * State field (reducer) that tracks comment ranges.\n * The ranges are tracked as Automerge cursors from which the absolute indexed ranges can be computed.\n */\nexport const commentsState = StateField.define<CommentsState>({\n create: (state) => ({ id: state.facet(documentId), comments: [], selection: {} }),\n update: (value, tr) => {\n for (const effect of tr.effects) {\n // Update selection.\n if (effect.is(setSelection)) {\n return { ...value, selection: effect.value };\n }\n\n // Update range from store.\n if (effect.is(setComments)) {\n const { comments } = effect.value;\n const commentStates: CommentState[] = comments\n .map((comment) => {\n // Skip cut/deleted comments.\n if (!comment.cursor) {\n return undefined;\n }\n\n const range = Cursor.getRangeFromCursor(tr.state, comment.cursor);\n return range && { comment, range };\n })\n .filter(isNonNullable);\n\n return { ...value, comments: commentStates };\n }\n\n // Update entire state.\n if (effect.is(setCommentState)) {\n return effect.value;\n }\n }\n\n return value;\n },\n});\n\n/**\n * NOTE: Matches search.\n */\nconst styles = EditorView.theme({\n '.cm-comment, .cm-comment-current': {\n margin: '0 -3px',\n padding: '3px',\n borderRadius: '3px',\n backgroundColor: 'var(--dx-cmCommentSurface)',\n color: 'var(--dx-cmComment)',\n cursor: 'pointer',\n },\n '.cm-comment:hover, .cm-comment-current': {\n textDecoration: 'underline',\n },\n});\n\nconst createCommentMark = (id: string, isCurrent: boolean) =>\n Decoration.mark({\n class: isCurrent ? 'cm-comment-current' : 'cm-comment',\n attributes: {\n 'data-testid': 'cm-comment',\n 'data-comment-id': id,\n },\n });\n\n/**\n * Decorate ranges.\n */\nconst commentsDecorations = EditorView.decorations.compute([commentsState], (state) => {\n const {\n selection: { current },\n comments,\n } = state.field(commentsState);\n\n const decorations = sortBy(comments ?? [], (range) => range.range.from)\n ?.flatMap((comment) => {\n const range = comment.range;\n if (!range) {\n log.warn('Invalid range:', range);\n return undefined;\n } else if (range.from === range.to) {\n // Skip empty ranges. This can happen when a comment is cut or deleted.\n return undefined;\n }\n\n const mark = createCommentMark(comment.comment.id, comment.comment.id === current);\n return mark.range(range.from, range.to);\n })\n .filter(isNonNullable);\n\n return Decoration.set(decorations);\n});\n\nexport const commentClickedEffect = StateEffect.define<string>();\n\nconst handleCommentClick = EditorView.domEventHandlers({\n click: (event, view) => {\n let target = event.target as HTMLElement;\n const editorRoot = view.dom;\n\n // Traverse up the DOM tree looking for an element with data-comment-id\n // Stop if we reach the editor root or find the comment id\n while (target && target !== editorRoot && !target.hasAttribute('data-comment-id')) {\n target = target.parentElement as HTMLElement;\n }\n\n // Check if we found a comment id and are still within the editor\n if (target && target !== editorRoot) {\n const commentId = target.getAttribute('data-comment-id');\n if (commentId) {\n view.dispatch({ effects: commentClickedEffect.of(commentId) });\n return true;\n }\n }\n\n return false;\n },\n});\n\n//\n// Cut-and-paste.\n//\n\ntype TrackedComment = { id: string; from: number; to: number };\n\nconst trackPastedComments = (onUpdate: NonNullable<CommentsOptions['onUpdate']>) => {\n // Tracks indexed selections within text.\n let tracked: { text: Text; comments: TrackedComment[] } | null = null;\n\n // Track cut or copy (enables cut-and-paste and copy-delete-paste to restore comment selection).\n const handleTrack = (event: Event, view: EditorView) => {\n const comments = view.state.field(commentsState);\n const { main } = view.state.selection;\n const selectedRanges = comments.comments.filter(\n ({ range }) => range.from >= main.from && range.to <= main.to && range.from < range.to,\n );\n\n if (!selectedRanges.length) {\n tracked = null;\n } else {\n tracked = {\n text: view.state.doc.slice(main.from, main.to),\n comments: selectedRanges.map(({ comment, range }) => ({\n id: comment.id,\n from: range.from - main.from,\n to: range.to - main.from,\n })),\n };\n }\n };\n\n return [\n EditorView.domEventHandlers({\n cut: handleTrack,\n copy: handleTrack,\n }),\n\n // Track deleted comments.\n invertedEffects.of((tr) => {\n const { comments } = tr.startState.field(commentsState);\n const effects: StateEffect<any>[] = [];\n tr.changes.iterChangedRanges((fromA, toA) => {\n for (const {\n comment: { id },\n range: { from, to },\n } of comments) {\n if (from < to && from >= fromA && to <= toA) {\n effects.push(restoreCommentEffect.of({ id, from, to }));\n }\n }\n });\n\n return effects;\n }),\n\n // Handle paste or the undo of comment deletion.\n EditorView.updateListener.of((update) => {\n const restore: TrackedComment[] = [];\n\n for (let i = 0; i < update.transactions.length; i++) {\n const tr = update.transactions[i];\n for (let j = 0; j < restore.length; j++) {\n restore[j] = mapTrackedComment(restore[j], tr.changes);\n }\n for (const effect of tr.effects) {\n if (effect.is(restoreCommentEffect)) {\n restore.push(effect.value);\n }\n }\n }\n\n if (tracked) {\n const paste = update.transactions.find((tr) => tr.isUserEvent('input.paste'));\n if (paste) {\n let found = -1;\n paste.changes.iterChanges((fromA, toA, fromB, toB, text) => {\n if (text.eq(tracked!.text)) {\n for (let i = update.transactions.indexOf(paste!) + 1; i < update.transactions.length; i++) {\n fromB = update.transactions[i].changes.mapPos(fromB);\n }\n\n found = fromB;\n }\n });\n\n if (found > -1) {\n for (const moved of tracked.comments) {\n restore.push({ id: moved.id, from: found + moved.from, to: found + moved.to });\n }\n }\n\n tracked = null;\n }\n }\n\n for (const comment of restore) {\n const { comments } = update.startState.field(commentsState);\n const exists = comments.some((c) => c.comment.id === comment.id && c.range.from < c.range.to);\n if (!exists) {\n const cursor = Cursor.getCursorFromRange(update.state, comment);\n onUpdate({ id: comment.id, cursor });\n }\n }\n }),\n ];\n};\n\nconst mapTrackedComment = (comment: TrackedComment, changes: ChangeDesc) => ({\n id: comment.id,\n from: changes.mapPos(comment.from, 1),\n to: changes.mapPos(comment.to, 1),\n});\n\n/**\n * These are attached to undone/redone transactions in the editor for the purpose of restoring comments\n * that were deleted by the original changes.\n */\nconst restoreCommentEffect = StateEffect.define<TrackedComment>({ map: mapTrackedComment });\n\n/**\n * Create comment thread action.\n */\nexport const createComment: Command = (view) => {\n const options = view.state.facet(optionsFacet);\n const { from, to } = view.state.selection.main;\n if (from === to) {\n return false;\n }\n\n // Don't allow selection at end of document.\n if (to === view.state.doc.length) {\n view.dispatch({\n changes: {\n from: to,\n insert: '\\n',\n },\n });\n }\n\n const cursor = Cursor.getCursorFromRange(view.state, { from, to });\n if (cursor) {\n // Create thread via callback.\n options.onCreate?.({ cursor, from, location: view.coordsAtPos(from) });\n return true;\n }\n\n return false;\n};\n\n//\n// Options\n//\n\nexport type CommentsOptions = {\n /**\n * Document id.\n */\n id?: string;\n /**\n * Key shortcut to create a new thread.\n */\n key?: string;\n /**\n * Called to render tooltip.\n */\n renderTooltip?: RenderCallback<{ shortcut: string }>;\n /**\n * Called to create a new thread and return the thread id.\n */\n onCreate?: (params: { cursor: string; from: number; location?: Rect | null }) => void;\n /**\n * Selection cut/deleted.\n */\n onDelete?: (params: { id: string }) => void;\n /**\n * Called when a comment is moved.\n */\n onUpdate?: (params: { id: string; cursor: string }) => void;\n /**\n * Called to notify which thread is currently closest to the cursor.\n */\n onSelect?: (state: CommentsState) => void;\n};\n\nconst optionsFacet = singleValueFacet<CommentsOptions>();\n\n/**\n * Comment threads.\n * 1). Updates the EditorModel to store relative selections for a set of comments threads.\n * Since the selections are relative, they do not need to be updated when the document is edited.\n * 2). Implements a StateField to track absolute selections corresponding to the comments (i.e., when the document is edited).\n * 3). Creates decoration marks to apply classes to each selection.\n * 4). Tracks the current cursor position to:\n * a). Update the decoration to show if the cursor is within a current selection.\n * b). Calls a handler to indicate which is the closest selection (e.g., to update the thread sidebar).\n * 5). Optionally, implements a hoverTooltip to show hints when creating a selection range.\n */\nexport const comments = (options: CommentsOptions = {}): Extension => {\n const { key: shortcut = \"meta-'\" } = options;\n\n const handleSelect = debounce((state: CommentsState) => options.onSelect?.(state), 200);\n\n return [\n optionsFacet.of(options),\n options.id ? documentId.of(options.id) : undefined,\n commentsState,\n commentsDecorations,\n handleCommentClick,\n styles,\n\n //\n // Keymap.\n //\n options.onCreate &&\n keymap.of([\n {\n key: shortcut,\n run: callbackWrapper(createComment),\n },\n ]),\n\n //\n // Hover tooltip (for key shortcut hints, etc.)\n // TODO(burdon): Factor out to generic hints extension for current selection/line.\n //\n options.renderTooltip &&\n hoverTooltip(\n (view, pos) => {\n const selection = view.state.selection.main;\n if (selection && pos >= selection.from && pos <= selection.to) {\n return {\n pos: selection.from,\n end: selection.to,\n above: true,\n create: () => {\n const el = document.createElement('div');\n options.renderTooltip!(el, { shortcut }, view);\n return { dom: el, offset: { x: 0, y: 8 } };\n },\n };\n }\n\n return null;\n },\n {\n // TODO(burdon): Hide on change triggered immediately?\n // hideOnChange: true,\n hoverTime: 1_000,\n },\n ),\n\n //\n // Track deleted ranges and update ranges for decorations.\n //\n EditorView.updateListener.of(({ view, state, changes }) => {\n let mod = false;\n const { comments, ...value } = state.field(commentsState);\n changes.iterChanges((from, to, from2, to2) => {\n comments.forEach(({ comment, range }) => {\n // Test if range deleted.\n if (from2 === to2) {\n const newRange = Cursor.getRangeFromCursor(view.state, comment.cursor!);\n if (!newRange || newRange.to - newRange.from === 0) {\n options.onDelete?.({ id: comment.id });\n }\n }\n\n // Update range.\n if (from <= range.to) {\n const newRange = Cursor.getRangeFromCursor(view.state, comment.cursor!);\n Object.assign(range, newRange);\n mod = true;\n }\n });\n });\n\n if (mod) {\n view.dispatch({ effects: setCommentState.of({ comments, ...value }) });\n }\n }),\n\n //\n // Track selection/proximity.\n //\n EditorView.updateListener.of(({ view, state }) => {\n let min = Infinity;\n const {\n selection: { current, closest },\n comments,\n } = state.field(commentsState);\n\n const { head } = state.selection.main;\n const selection: SelectionState = {};\n comments.forEach(({ comment, range }) => {\n if (head >= range.from && head <= range.to) {\n selection.current = comment.id;\n selection.closest = undefined;\n }\n\n if (!selection.current) {\n const d = Math.min(Math.abs(head - range.from), Math.abs(head - range.to));\n if (d < min) {\n selection.closest = comment.id;\n min = d;\n }\n }\n });\n\n if (selection.current !== current || selection.closest !== closest) {\n view.dispatch({ effects: setSelection.of(selection) });\n\n // Update callback.\n handleSelect({\n selection,\n id: state.facet(documentId),\n comments: comments.map(({ comment, range }) => ({\n comment,\n range,\n location: view.coordsAtPos(range.from),\n })),\n });\n }\n }),\n\n options.onUpdate && trackPastedComments(options.onUpdate),\n ].filter(isNonNullable);\n};\n\n//\n// Utils.\n//\n\nexport const scrollThreadIntoView = (view: EditorView, id: string, center = true) => {\n const comment = view.state.field(commentsState).comments.find((range) => range.comment.id === id);\n if (!comment?.comment.cursor) {\n return;\n }\n const range = Cursor.getRangeFromCursor(view.state, comment.comment.cursor);\n if (range) {\n const currentSelection = view.state.selection.main;\n const currentScrollPosition = view.scrollDOM.scrollTop;\n const targetScrollPosition = view.coordsAtPos(range.from)?.top;\n\n const needsScroll =\n targetScrollPosition !== undefined &&\n (targetScrollPosition < currentScrollPosition ||\n targetScrollPosition > currentScrollPosition + view.scrollDOM.clientHeight);\n\n const needsSelectionUpdate = currentSelection.from !== range.from || currentSelection.to !== range.from;\n\n if (needsScroll || needsSelectionUpdate) {\n view.dispatch({\n selection: needsSelectionUpdate ? { anchor: range.from } : undefined,\n effects: [\n needsScroll ? EditorView.scrollIntoView(range.from, center ? { y: 'center' } : undefined) : [],\n needsSelectionUpdate ? setSelection.of({ current: id }) : [],\n ].flat(),\n });\n }\n }\n};\n\n/**\n * Manages external comment synchronization for the editor.\n * This class subscribes to external comment updates and applies them to the editor view.\n */\nclass ExternalCommentSync implements PluginValue {\n private readonly unsubscribe: () => void;\n\n constructor(view: EditorView, id: string, subscribe: (sink: () => void) => CleanupFn, getComments: () => Comment[]) {\n const updateComments = () => {\n const comments = getComments();\n if (id === view.state.facet(documentId)) {\n queueMicrotask(() => view.dispatch({ effects: setComments.of({ id, comments }) }));\n }\n };\n\n this.unsubscribe = subscribe(updateComments);\n }\n\n destroy = () => {\n this.unsubscribe();\n };\n}\n\n// TODO(burdon): Needs comment.\nexport const createExternalCommentSync = (\n id: string,\n subscribe: (sink: () => void) => CleanupFn,\n getComments: () => Comment[],\n): Extension =>\n ViewPlugin.fromClass(\n class {\n constructor(view: EditorView) {\n return new ExternalCommentSync(view, id, subscribe, getComments);\n }\n },\n );\n\n/**\n * @deprecated This hook will be removed in future versions. Use the new comment sync extension instead.\n * Update comments state field.\n */\nexport const useComments = (view: EditorView | null | undefined, id: string, comments?: Comment[]) => {\n useEffect(() => {\n if (view) {\n // Check same document.\n // NOTE: Hook might be called before editor state is updated.\n if (id === view.state.facet(documentId)) {\n view.dispatch({\n effects: setComments.of({ id, comments: comments ?? [] }),\n });\n }\n }\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Extension, Transaction, type TransactionSpec } from '@codemirror/state';\nimport { EditorView, keymap } from '@codemirror/view';\n\nimport { debounce } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { isNotFalsy } from '@dxos/util';\n\nimport { singleValueFacet } from '../util';\n\n/**\n * Currently edited document id as FQ string.\n */\nexport const documentId = singleValueFacet<string>();\n\nexport type EditorSelection = {\n anchor: number;\n head?: number;\n};\n\nexport type EditorSelectionState = {\n scrollTo?: number;\n selection?: EditorSelection;\n};\n\nexport type EditorStateStore = {\n setState: (id: string, state: EditorSelectionState) => void;\n getState: (id: string) => EditorSelectionState | undefined;\n};\n\nconst stateRestoreAnnotation = 'dxos.org/cm/state-restore';\n\nexport const createEditorStateTransaction = ({ scrollTo, selection }: EditorSelectionState): TransactionSpec => {\n return {\n selection,\n scrollIntoView: !scrollTo,\n effects: scrollTo ? EditorView.scrollIntoView(scrollTo, { yMargin: 96 }) : undefined,\n annotations: Transaction.userEvent.of(stateRestoreAnnotation),\n };\n};\n\nexport const createEditorStateStore = (keyPrefix: string): EditorStateStore => ({\n getState: (id) => {\n invariant(id);\n const state = localStorage.getItem(`${keyPrefix}/${id}`);\n return state ? JSON.parse(state) : undefined;\n },\n\n setState: (id, state) => {\n invariant(id);\n localStorage.setItem(`${keyPrefix}/${id}`, JSON.stringify(state));\n },\n});\n\n/**\n * Track scrolling and selection state to be restored when switching to document.\n */\nexport const selectionState = ({ getState, setState }: Partial<EditorStateStore> = {}): Extension => {\n const setStateDebounced = debounce(setState!, 1_000);\n\n return [\n // TODO(burdon): Track scrolling (currently only updates when cursor moves).\n // EditorView.domEventHandlers({\n // scroll: (event) => {\n // setStateDebounced(id, {});\n // },\n // }),\n EditorView.updateListener.of(({ view, transactions }) => {\n const id = view.state.facet(documentId);\n if (!id || transactions.some((tr) => tr.isUserEvent(stateRestoreAnnotation))) {\n return;\n }\n\n if (setState) {\n const { scrollTop } = view.scrollDOM;\n const pos = view.posAtCoords({ x: 0, y: scrollTop });\n if (pos !== null) {\n const { anchor, head } = view.state.selection.main;\n setStateDebounced(id, { scrollTo: pos, selection: { anchor, head } });\n }\n }\n }),\n getState &&\n keymap.of([\n {\n key: 'ctrl-r', // TODO(burdon): Setting to jump back to selection.\n run: (view) => {\n const state = getState(view.state.facet(documentId));\n if (state) {\n view.dispatch(createEditorStateTransaction(state));\n }\n return true;\n },\n },\n ]),\n ].filter(isNotFalsy);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { syntaxTree } from '@codemirror/language';\nimport { type EditorState, type Extension, type RangeSet, StateField, type Transaction } from '@codemirror/state';\n\n// eslint-disable-next-line no-console\nexport const debugNodeLogger = (log: (...args: any[]) => void = console.log): Extension => {\n const logTokens = (state: EditorState) => syntaxTree(state).iterate({ enter: (node) => log(node.type) });\n return StateField.define<any>({\n create: (state) => logTokens(state),\n update: (_: RangeSet<any>, tr: Transaction) => logTokens(tr.state),\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport type { Extension } from '@codemirror/state';\nimport { dropCursor, EditorView } from '@codemirror/view';\n\nexport type DNDOptions = { onDrop?: (view: EditorView, event: { files: FileList }) => void };\n\nconst styles = EditorView.theme({\n '.cm-dropCursor': {\n borderLeft: '2px solid var(--dx-accentText)',\n color: 'var(--dx-accentText)',\n padding: '0 4px',\n },\n '.cm-dropCursor:after': {\n content: '\"←\"',\n },\n});\n\nexport const dropFile = (options: DNDOptions = {}): Extension => {\n return [\n styles,\n dropCursor(),\n EditorView.domEventHandlers({\n drop: (event, view) => {\n event.preventDefault();\n const files = event.dataTransfer?.files;\n const pos = view.posAtCoords(event);\n if (files?.length && pos !== null) {\n view.dispatch({ selection: { anchor: pos } });\n options.onDrop?.(view, { files });\n }\n },\n }),\n ];\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete';\nimport { defaultKeymap, history, historyKeymap, indentWithTab, standardKeymap } from '@codemirror/commands';\nimport { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';\nimport { searchKeymap } from '@codemirror/search';\nimport { EditorState, type Extension } from '@codemirror/state';\nimport { oneDarkHighlightStyle } from '@codemirror/theme-one-dark';\nimport {\n EditorView,\n type KeyBinding,\n ViewPlugin,\n drawSelection,\n dropCursor,\n highlightActiveLine,\n keymap,\n lineNumbers,\n placeholder,\n scrollPastEnd,\n} from '@codemirror/view';\nimport defaultsDeep from 'lodash.defaultsdeep';\nimport merge from 'lodash.merge';\n\nimport { generateName } from '@dxos/display-name';\nimport { log } from '@dxos/log';\nimport { type DocAccessor, type Space } from '@dxos/react-client/echo';\nimport { type Identity } from '@dxos/react-client/halo';\nimport { type ThemeMode } from '@dxos/react-ui';\nimport { type HuePalette } from '@dxos/react-ui-theme';\nimport { hexToHue, isNotFalsy } from '@dxos/util';\n\nimport { automerge } from './automerge';\nimport { SpaceAwarenessProvider, awareness } from './awareness';\nimport { focus } from './focus';\nimport { editorGutter, editorMonospace } from '../defaults';\nimport { type ThemeStyles, defaultTheme } from '../styles';\n\n//\n// Basic\n//\n\nexport const preventNewline = EditorState.transactionFilter.of((tr) => (tr.newDoc.lines > 1 ? [] : tr));\n\n/**\n * https://codemirror.net/docs/extensions\n * https://github.com/codemirror/basic-setup\n * https://github.com/codemirror/basic-setup/blob/main/src/codemirror.ts\n */\nexport type BasicExtensionsOptions = {\n allowMultipleSelections?: boolean;\n bracketMatching?: boolean;\n closeBrackets?: boolean;\n dropCursor?: boolean;\n drawSelection?: boolean;\n editable?: boolean;\n focus?: boolean;\n highlightActiveLine?: boolean;\n history?: boolean;\n indentWithTab?: boolean;\n keymap?: null | 'default' | 'standard';\n lineNumbers?: boolean;\n /** If false then do not set a max-width or side margin on the editor. */\n lineWrapping?: boolean;\n monospace?: boolean;\n placeholder?: string;\n /** If true user cannot edit the text, but they can still select and copy it. */\n readOnly?: boolean;\n search?: boolean;\n scrollPastEnd?: boolean;\n standardKeymap?: boolean;\n tabSize?: number;\n};\n\nconst defaultBasicOptions: BasicExtensionsOptions = {\n allowMultipleSelections: true,\n bracketMatching: true,\n closeBrackets: true,\n drawSelection: true,\n focus: true,\n history: true,\n keymap: 'standard',\n lineWrapping: true,\n search: true,\n};\n\nconst keymaps: { [key: string]: readonly KeyBinding[] } = {\n // https://codemirror.net/docs/ref/#commands.standardKeymap\n standard: standardKeymap,\n // https://codemirror.net/docs/ref/#commands.defaultKeymap\n default: defaultKeymap,\n};\n\nexport const createBasicExtensions = (_props?: BasicExtensionsOptions): Extension => {\n const props: BasicExtensionsOptions = defaultsDeep({}, _props, defaultBasicOptions);\n return [\n // NOTE: Doesn't catch errors in keymap functions.\n EditorView.exceptionSink.of((err) => {\n log.catch(err);\n }),\n\n props.allowMultipleSelections && EditorState.allowMultipleSelections.of(true),\n props.bracketMatching && bracketMatching(),\n props.closeBrackets && closeBrackets(),\n props.dropCursor && dropCursor(),\n props.drawSelection && drawSelection({ cursorBlinkRate: 1_200 }),\n props.editable !== undefined && EditorView.editable.of(props.editable),\n props.focus && focus,\n props.highlightActiveLine && highlightActiveLine(),\n props.history && history(),\n props.lineNumbers && [lineNumbers(), editorGutter],\n props.lineWrapping && EditorView.lineWrapping,\n props.monospace && editorMonospace,\n props.placeholder && placeholder(props.placeholder),\n props.readOnly !== undefined && EditorState.readOnly.of(props.readOnly),\n props.scrollPastEnd && scrollPastEnd(),\n props.tabSize && EditorState.tabSize.of(props.tabSize),\n\n // https://codemirror.net/docs/ref/#view.KeyBinding\n keymap.of(\n [\n ...((props.keymap && keymaps[props.keymap]) ?? []),\n // NOTE: Tabs are also configured by markdown extension.\n // https://codemirror.net/docs/ref/#commands.indentWithTab\n ...(props.indentWithTab ? [indentWithTab] : []),\n // https://codemirror.net/docs/ref/#autocomplete.closeBracketsKeymap\n ...(props.closeBrackets ? closeBracketsKeymap : []),\n // https://codemirror.net/docs/ref/#commands.historyKeymap\n ...(props.history ? historyKeymap : []),\n // https://codemirror.net/docs/ref/#search.searchKeymap\n ...(props.search ? searchKeymap : []),\n // Disable bindings that conflict with system shortcuts.\n // TODO(burdon): Catalog global shortcuts.\n {\n key: 'Mod-Shift-k',\n preventDefault: true,\n run: () => true,\n },\n ].filter(isNotFalsy),\n ),\n ].filter(isNotFalsy);\n};\n\n//\n// Theme\n//\n\nexport type ThemeExtensionsOptions = {\n themeMode?: ThemeMode;\n styles?: ThemeStyles;\n syntaxHighlighting?: boolean;\n slots?: {\n editor?: {\n className?: string;\n };\n scroll?: {\n className?: string;\n };\n content?: {\n className?: string;\n };\n };\n};\n\nconst defaultThemeSlots = {\n editor: {\n className: 'w-full bs-full',\n },\n};\n\n/**\n * https://codemirror.net/examples/styling\n */\nexport const createThemeExtensions = ({\n themeMode,\n styles,\n syntaxHighlighting: _syntaxHighlighting,\n slots: _slots,\n}: ThemeExtensionsOptions = {}): Extension => {\n const slots = defaultsDeep({}, _slots, defaultThemeSlots);\n return [\n EditorView.darkTheme.of(themeMode === 'dark'),\n EditorView.baseTheme(styles ? merge({}, defaultTheme, styles) : defaultTheme),\n // https://github.com/codemirror/theme-one-dark\n _syntaxHighlighting &&\n (themeMode === 'dark' ? syntaxHighlighting(oneDarkHighlightStyle) : syntaxHighlighting(defaultHighlightStyle)),\n slots.editor?.className && EditorView.editorAttributes.of({ class: slots.editor.className }),\n slots.content?.className && EditorView.contentAttributes.of({ class: slots.content.className }),\n slots.scroll?.className &&\n ViewPlugin.fromClass(\n class {\n constructor(view: EditorView) {\n view.scrollDOM.classList.add(slots.scroll.className);\n }\n },\n ),\n ].filter(isNotFalsy);\n};\n\n//\n// Data\n//\n\nexport type DataExtensionsProps<T> = {\n id: string;\n text?: DocAccessor<T>;\n space?: Space;\n identity?: Identity | null;\n};\n\n// TODO(burdon): Move out of react-ui-editor (remove echo deps).\nexport const createDataExtensions = <T>({ id, text, space, identity }: DataExtensionsProps<T>): Extension[] => {\n const extensions: Extension[] = [];\n if (text) {\n extensions.push(automerge(text));\n }\n\n if (space && identity) {\n const peerId = identity?.identityKey.toHex();\n const hue = (identity?.profile?.data?.hue as HuePalette | undefined) ?? hexToHue(peerId ?? '0');\n\n extensions.push(\n awareness(\n new SpaceAwarenessProvider({\n space,\n channel: `awareness.${id}`,\n peerId: identity.identityKey.toHex(),\n info: {\n displayName: identity.profile?.displayName ?? generateName(identity.identityKey.toHex()),\n darkColor: `var(--dx-${hue}Cursor)`,\n lightColor: `var(--dx-${hue}Cursor)`,\n },\n }),\n ),\n );\n }\n\n return extensions;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { StateEffect, StateField } from '@codemirror/state';\nimport { EditorView } from '@codemirror/view';\n\nconst focusEffect = StateEffect.define<boolean>();\n\nexport const focusField = StateField.define<boolean>({\n create: () => false,\n update: (value, tr) => {\n for (const effect of tr.effects) {\n if (effect.is(focusEffect)) {\n return effect.value;\n }\n }\n return value;\n },\n});\n\n/**\n * Manage focus.\n */\nexport const focus = [\n focusField,\n EditorView.domEventHandlers({\n focus: (event, view) => {\n setTimeout(() => view.dispatch({ effects: focusEffect.of(true) }));\n },\n blur: (event, view) => {\n setTimeout(() => view.dispatch({ effects: focusEffect.of(false) }));\n },\n }),\n];\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { EditorView } from '@codemirror/view';\n\nimport { mx } from '@dxos/react-ui-theme';\n\nimport { type ThemeExtensionsOptions } from './extensions';\nimport { fontMono } from './styles';\n\n/**\n * CodeMirror content width.\n * 40rem = 640px. Corresponds to initial plank width (Google docs, Stashpad, etc.)\n * 50rem = 800px. Maximum content width for solo mode.\n * NOTE: Max width - 4rem = 2rem left/right margin (or 2rem gutter plus 1rem left/right margin).\n */\nexport const editorWidth = '!mli-auto is-full max-is-[min(50rem,100%-4rem)]';\n\nexport const editorSlots: ThemeExtensionsOptions['slots'] = {\n scroll: {\n className: 'pbs-2',\n },\n content: {\n className: editorWidth,\n },\n};\n\nexport const editorGutter = EditorView.theme({\n '.cm-gutters': {\n background: 'var(--dx-baseSurface)',\n paddingRight: '1rem',\n },\n});\n\nexport const editorMonospace = EditorView.theme({\n '.cm-content': {\n fontFamily: fontMono,\n },\n});\n\nexport const editorWithToolbarLayout =\n 'grid grid-cols-1 grid-rows-[min-content_1fr] data-[toolbar=disabled]:grid-rows-[1fr] justify-center content-start overflow-hidden';\n\nexport const stackItemContentEditorClassNames = (role?: string) =>\n mx(\n 'attention-surface dx-focus-ring-inset data-[toolbar=disabled]:pbs-2',\n role === 'section' ? '[&_.cm-scroller]:overflow-hidden [&_.cm-scroller]:min-bs-24' : 'min-bs-0',\n );\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { mx } from '@dxos/react-ui-theme';\n\nexport type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;\n\n// https://tailwindcss.com/docs/font-weight\nconst headings: Record<HeadingLevel, string> = {\n 1: 'text-4xl',\n 2: 'text-3xl',\n 3: 'text-2xl',\n 4: 'text-xl',\n 5: 'text-lg',\n 6: '', // TODO(burdon): Should be text-base, but that's a color in our system.\n};\n\nexport const theme = {\n code: 'font-mono !no-underline text-neutral-700 dark:text-neutral-300',\n codeMark: 'font-mono text-primary-500',\n mark: 'opacity-50',\n heading: (level: HeadingLevel) => {\n return mx(headings[level], 'dark:text-primary-400');\n },\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { tokens } from '@dxos/react-ui-theme';\nimport { get } from '@dxos/util';\n\n/**\n * Returns the tailwind token value.\n */\nconst getToken = (path: string, defaultValue?: string | string[]): string => {\n const value = get(tokens, path, defaultValue);\n return value?.toString() ?? '';\n};\n\nexport const fontBody = getToken('fontFamily.body');\nexport const fontMono = getToken('fontFamily.mono');\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type StyleSpec } from 'style-mod';\n\nimport { fontBody } from './tokens';\n\nexport type ThemeStyles = Record<string, StyleSpec>;\n\n/**\n * Minimal styles.\n * https://codemirror.net/examples/styling\n *\n * Examples:\n * - https://github.com/codemirror/view/blob/main/src/theme.ts\n * - https://github.com/codemirror/theme-one-dark/blob/main/src/one-dark.ts\n *\n * Main layout:\n * https://codemirror.net/examples/styling\n * https://codemirror.net/docs/guide (DOM Structure).\n *\n * <div class=\"cm-editor [cm-focused] [generated classes]\">\n * <div class=\"cm-scroller\">\n * <div class=\"cm-gutters\">\n * <div class=\"cm-gutter [...]\">\n * <div class=\"cm-gutterElement\">...</div>\n * </div>\n * </div>\n * <div class=\"cm-content\" role=\"textbox\" contenteditable=\"true\">\n * <div class=\"cm-line\"></div>\n * </div>\n * <div class=\"cm-selectionLayer\">\n * <div class=\"cm-selectionBackground\"></div>\n * </div>\n * <div class=\"cm-cursorLayer\">\n * <div class=\"cm-cursor\"></div>\n * </div>\n * </div>\n * </div>\n *\n * NOTE: `light` and `dark` selectors are preprocessed by CodeMirror and can only be in the base theme.\n * NOTE: Use 'unset' to remove default CM style.\n */\nexport const defaultTheme: ThemeStyles = {\n '&': {},\n '&.cm-focused': {\n outline: 'none',\n },\n\n /**\n * Scroller\n */\n '.cm-scroller': {\n overflowY: 'auto',\n },\n\n /**\n * Content\n * NOTE: Apply margins to content so that scrollbar is at the edge of the container.\n */\n '.cm-content': {\n padding: 'unset',\n fontFamily: fontBody,\n // NOTE: Base font size (otherwise defined by HTML tag, which might be different for storybook).\n fontSize: '16px',\n lineHeight: 1.5,\n color: 'unset',\n },\n\n /**\n * Gutters\n * NOTE: Gutters should have the same top margin as the content.\n */\n '.cm-gutters': {\n borderRight: 'none',\n background: 'transparent',\n },\n '.cm-gutter': {},\n '.cm-gutter.cm-lineNumbers': {\n paddingRight: '4px',\n borderRight: '1px solid var(--dx-separator)',\n },\n '.cm-gutter.cm-lineNumbers .cm-gutterElement': {\n minWidth: '40px',\n alignContent: 'center',\n },\n /**\n * Height is set to match the corresponding line.\n */\n '.cm-gutterElement': {\n alignItems: 'center',\n fontSize: '12px',\n },\n\n /**\n * Line.\n */\n '.cm-line': {\n paddingInline: 0,\n },\n '.cm-activeLine': {\n background: 'var(--dx-cmActiveLine)',\n },\n\n /**\n * Cursor (layer).\n */\n '.cm-cursor, .cm-dropCursor': {\n borderLeft: '2px solid var(--dx-cmCursor)',\n },\n '.cm-placeholder': {\n color: 'var(--dx-subdued)',\n },\n\n /**\n * Selection (layer).\n */\n '.cm-selectionBackground': {\n background: 'var(--dx-cmSelection)',\n },\n '&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {\n background: 'var(--dx-cmFocusedSelection)',\n },\n\n /**\n * Search.\n * NOTE: Matches comment.\n */\n '.cm-searchMatch': {\n margin: '0 -3px',\n padding: '3px',\n borderRadius: '3px',\n background: 'var(--dx-cmHighlightSurface)',\n color: 'var(--dx-cmHighlight)',\n },\n '.cm-searchMatch-selected': {\n textDecoration: 'underline',\n },\n\n /**\n * Link.\n */\n '.cm-link': {\n textDecorationLine: 'underline',\n textDecorationThickness: '1px',\n textDecorationColor: 'var(--dx-separator)',\n textUnderlineOffset: '2px',\n borderRadius: '.125rem',\n },\n '.cm-link > span': {\n color: 'var(--dx-accentText)',\n },\n\n /**\n * Tooltip.\n */\n '.cm-tooltip': {\n background: 'var(--dx-baseSurface)',\n },\n '.cm-tooltip-below': {},\n\n /**\n * Autocomplete.\n * https://github.com/codemirror/autocomplete/blob/main/src/completion.ts\n */\n '.cm-tooltip.cm-tooltip-autocomplete': {\n marginTop: '4px',\n marginLeft: '-3px',\n borderColor: 'var(--dx-separator)',\n borderTop: 'none',\n },\n '.cm-tooltip.cm-tooltip-autocomplete > ul': {\n maxHeight: '20em',\n },\n '.cm-tooltip.cm-tooltip-autocomplete > ul > li': {\n padding: '4px',\n },\n '.cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]': {\n background: 'var(--dx-hoverSurface)',\n },\n '.cm-tooltip.cm-tooltip-autocomplete > ul > completion-section': {\n paddingLeft: '4px !important',\n borderBottom: 'none !important',\n color: 'var(--dx-accentText)',\n },\n\n '.cm-completionInfo': {\n width: '360px !important',\n margin: '-10px 1px 0 1px',\n padding: '8px !important',\n borderColor: 'var(--dx-separator)',\n },\n '.cm-completionIcon': {\n display: 'none',\n },\n '.cm-completionLabel': {\n fontFamily: fontBody,\n },\n '.cm-completionMatchedText': {\n textDecoration: 'none !important',\n opacity: 0.5,\n },\n\n /**\n * Panels\n * https://github.com/codemirror/search/blob/main/src/search.ts#L745\n *\n * Find/replace panel.\n * <div class=\"cm-announced\">...</div>\n * <div class=\"cm-scroller\">...</div>\n * <div class=\"cm-panels cm-panels-bottom\">\n * <div class=\"cm-search cm-panel\">\n * <input class=\"cm-textfield\" />\n * <button class=\"cm-button\">...</button>\n * <label><input type=\"checkbox\" />...</label>\n * </div>\n * </div\n */\n // TODO(burdon): Implement custom panel (with icon buttons).\n '.cm-panels': {},\n '.cm-panel': {\n fontFamily: fontBody,\n backgroundColor: 'var(--surface-bg)',\n },\n '.cm-panel input, .cm-panel button, .cm-panel label': {\n color: 'var(--dx-subdued)',\n fontFamily: fontBody,\n fontSize: '14px',\n all: 'unset',\n margin: '3px !important',\n padding: '2px 6px !important',\n outline: '1px solid transparent',\n },\n '.cm-panel input, .cm-panel button': {\n backgroundColor: 'var(--dx-input)',\n },\n '.cm-panel input:focus, .cm-panel button:focus': {\n outline: '1px solid var(--dx-neutralFocusIndicator)',\n },\n '.cm-panel label': {\n display: 'inline-flex',\n alignItems: 'center',\n cursor: 'pointer',\n },\n '.cm-panel input.cm-textfield': {},\n '.cm-panel input[type=checkbox]': {\n width: '8px',\n height: '8px',\n marginRight: '6px !important',\n padding: '2px !important',\n color: 'var(--dx-neutralFocusIndicator)',\n },\n '.cm-panel button': {\n '&:hover': {\n backgroundColor: 'var(--dx-accentSurfaceHover) !important',\n },\n '&:active': {\n backgroundColor: 'var(--dx-accentSurfaceHover)',\n },\n },\n '.cm-panel.cm-search': {\n padding: '4px',\n borderTop: '1px solid var(--dx-separator)',\n },\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { codeFolding, foldGutter } from '@codemirror/language';\nimport { type Extension } from '@codemirror/state';\nimport { EditorView } from '@codemirror/view';\nimport React from 'react';\n\nimport { Icon } from '@dxos/react-ui';\n\nimport { createElement, renderRoot } from '../util';\n\nexport type FoldingOptions = {};\n\n/**\n * https://codemirror.net/examples/gutter\n */\n// TODO(burdon): Remember folding state (to state).\nexport const folding = (_props: FoldingOptions = {}): Extension => [\n codeFolding({\n placeholderDOM: () => {\n return document.createElement('span'); // Collapse content.\n },\n }),\n foldGutter({\n markerDOM: (open) => {\n // TODO(burdon): Use sprite directly.\n const el = createElement('div', { className: 'flex h-full items-center' });\n return renderRoot(\n el,\n <Icon icon='ph--caret-right--bold' size={3} classNames={['mx-3 cursor-pointer', open && 'rotate-90']} />,\n );\n },\n }),\n EditorView.theme({\n '.cm-foldGutter': {\n opacity: 0.3,\n transition: 'opacity 0.3s',\n width: '32px',\n },\n '.cm-foldGutter:hover': {\n opacity: 1,\n },\n }),\n];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type Extension } from '@codemirror/state';\nimport {\n Decoration,\n type DecorationSet,\n EditorView,\n MatchDecorator,\n ViewPlugin,\n type ViewUpdate,\n WidgetType,\n} from '@codemirror/view';\n\nimport { getHashColor, mx } from '@dxos/react-ui-theme';\n\nclass TagWidget extends WidgetType {\n constructor(private _text: string) {\n super();\n }\n\n toDOM(): HTMLSpanElement {\n const span = document.createElement('span');\n span.className = mx('cm-tag', getHashColor(this._text).tag);\n span.textContent = this._text;\n return span;\n }\n}\n\nconst tagMatcher = new MatchDecorator({\n regexp: /#(\\w+)\\W/g,\n decoration: (match) =>\n Decoration.replace({\n widget: new TagWidget(match[1]),\n }),\n});\n\n// TODO(burdon): Autocomplete from existing tags?\nexport const hashtag = (): Extension => [\n ViewPlugin.fromClass(\n class {\n tags: DecorationSet;\n constructor(view: EditorView) {\n this.tags = tagMatcher.createDeco(view);\n }\n\n update(update: ViewUpdate) {\n this.tags = tagMatcher.updateDeco(update, this.tags);\n }\n },\n {\n decorations: (instance) => instance.tags,\n provide: (plugin) =>\n EditorView.atomicRanges.of((view) => {\n return view.plugin(plugin)?.tags || Decoration.none;\n }),\n },\n ),\n\n EditorView.theme({\n '.cm-tag': {\n borderRadius: '4px',\n marginRight: '6px',\n padding: '2px 6px',\n },\n }),\n];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { json, jsonParseLinter } from '@codemirror/lang-json';\nimport { type LintSource, linter } from '@codemirror/lint';\nimport { type Extension } from '@codemirror/state';\nimport Ajv, { type ValidateFunction } from 'ajv';\n\nimport { type JsonSchemaType } from '@dxos/echo-schema';\n\nexport type JsonExtensionsOptions = {\n schema?: JsonSchemaType;\n};\n\nexport const createJsonExtensions = ({ schema }: JsonExtensionsOptions = {}): Extension => {\n let lintSource: LintSource = jsonParseLinter();\n if (schema) {\n // NOTE: Relaxing strict mode to allow additional custom schema properties.\n const ajv = new Ajv({ allErrors: false, strict: false });\n const validate = ajv.compile(schema);\n lintSource = schemaLinter(validate);\n }\n\n return [json(), linter(lintSource)];\n};\n\nconst schemaLinter =\n (validate: ValidateFunction): LintSource =>\n (view) => {\n try {\n const jsonText = view.state.doc.toString();\n const jsonData = JSON.parse(jsonText);\n const valid = validate(jsonData);\n if (valid) {\n return [];\n }\n\n return (\n validate.errors?.map((err: any) => ({\n from: 0,\n to: jsonText.length,\n severity: 'error',\n message: `${err.instancePath || '(root)'} ${err.message}`,\n })) ?? []\n );\n } catch (err: unknown) {\n return [\n {\n from: 0,\n to: view.state.doc.length,\n severity: 'error',\n message: 'Invalid JSON: ' + (err as Error).message,\n },\n ];\n }\n };\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Extension } from '@codemirror/state';\nimport { EditorView } from '@codemirror/view';\n\nimport { documentId } from './selection';\n\nexport type ListenerOptions = {\n onFocus?: (focusing: boolean) => void;\n onChange?: (text: string, id: string) => void;\n};\n\n/**\n * Event listener.\n * @deprecated Use EditorView.updateListener and listen for specific update events.\n */\nexport const listener = ({ onFocus, onChange }: ListenerOptions): Extension => {\n const extensions: Extension[] = [];\n\n onFocus &&\n extensions.push(\n EditorView.focusChangeEffect.of((_, focusing) => {\n onFocus(focusing);\n return null;\n }),\n );\n\n onChange &&\n extensions.push(\n EditorView.updateListener.of((update) => {\n onChange(update.state.doc.toString(), update.state.facet(documentId));\n }),\n );\n\n return extensions;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { snippet } from '@codemirror/autocomplete';\nimport { syntaxTree } from '@codemirror/language';\nimport {\n type ChangeSpec,\n EditorSelection,\n type Extension,\n type EditorState,\n type Line,\n type StateCommand,\n type Text,\n} from '@codemirror/state';\nimport { EditorView, keymap } from '@codemirror/view';\nimport { type SyntaxNodeRef, type SyntaxNode } from '@lezer/common';\nimport { useMemo } from 'react';\n\nimport { type Live } from '@dxos/live-object';\n\nimport { type EditorToolbarState } from '../../components';\n\n// Markdown refs:\n// https://github.github.com/gfm\n// https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax\n\n// Describes the formatting situation of the selection in an editor state.\n// For inline styles `strong`, `emphasis`, `strikethrough`, and `code`,\n// the field only holds true when *all* selected text has the style,\n// or when the selection is a cursor inside such a style.\nexport type Formatting = Partial<{\n blankLine: boolean;\n // The type of the block at the selection.\n // If multiple different block types are selected, this will hold null.\n blockType:\n | 'codeblock'\n | 'heading1'\n | 'heading2'\n | 'heading3'\n | 'heading4'\n | 'heading5'\n | 'heading6'\n | 'paragraph'\n | 'tablecell'\n | null;\n // Whether all selected text is wrapped in a blockquote.\n blockQuote: boolean;\n // Whether the selected text is strong.\n strong: boolean;\n // Whether the selected text is emphasized.\n emphasis: boolean;\n // Whether the selected text is stricken through.\n strikethrough: boolean;\n // Whether the selected text is inline code.\n code: boolean;\n // Whether there are links in the selected text.\n link: boolean;\n // If all selected blocks have the same (innermost) list style, that is indicated here.\n listStyle: null | 'ordered' | 'bullet' | 'task';\n}>;\n\nexport const formattingEquals = (a: Formatting, b: Formatting) =>\n a.blockType === b.blockType &&\n a.strong === b.strong &&\n a.emphasis === b.emphasis &&\n a.strikethrough === b.strikethrough &&\n a.code === b.code &&\n a.link === b.link &&\n a.listStyle === b.listStyle &&\n a.blockQuote === b.blockQuote;\n\nexport enum Inline {\n Strong = 0,\n Emphasis = 1,\n Strikethrough = 2,\n Code = 3,\n}\n\nexport enum List {\n Ordered,\n Bullet,\n Task,\n}\n\n//\n// Headings\n//\n\nexport const setHeading = (level: number): StateCommand => {\n return ({ state, dispatch }) => {\n const {\n selection: { ranges },\n doc,\n } = state;\n const changes: ChangeSpec[] = [];\n let prevBlock = -1;\n for (const range of ranges) {\n let sawBlock = false;\n syntaxTree(state).iterate({\n from: range.from,\n to: range.to,\n enter: (node) => {\n if (!Object.hasOwn(Textblocks, node.name) || prevBlock === node.from) {\n return;\n }\n sawBlock = true;\n prevBlock = node.from;\n const blockType = Textblocks[node.name];\n const isHeading = /heading(\\d)/.exec(blockType);\n const curLevel = isHeading ? +isHeading[1] : node.name === 'Paragraph' ? 0 : -1;\n if (curLevel < 0 || curLevel === level) {\n return;\n }\n if (curLevel === 0) {\n changes.push({ from: node.from, insert: '#'.repeat(level) + ' ' });\n } else if (node.name === 'SetextHeading1' || node.name === 'SetextHeading2') {\n // Change Setext heading to regular one.\n const nextLine = doc.lineAt(node.to);\n if (level) {\n changes.push({ from: node.from, insert: '#'.repeat(level) + ' ' });\n }\n changes.push({ from: nextLine.from - 1, to: nextLine.to });\n } else {\n // Adjust the level of an ATX heading.\n if (level === 0) {\n changes.push({ from: node.from, to: Math.min(node.to, node.from + curLevel + 1) });\n } else if (level < curLevel) {\n changes.push({ from: node.from, to: node.from + (curLevel - level) });\n } else {\n changes.push({ from: node.from, insert: '#'.repeat(level - curLevel) });\n }\n }\n },\n });\n let line;\n if (!sawBlock && range.empty && level > 0 && !/\\S/.test((line = state.doc.lineAt(range.from)).text)) {\n changes.push({ from: line.from, to: line.to, insert: '#'.repeat(level) + ' ' });\n }\n }\n\n if (!changes.length) {\n return false;\n }\n\n const changeSet = state.changes(changes);\n dispatch(\n state.update({\n changes: changeSet,\n selection: state.selection.map(changeSet, 1),\n userEvent: 'format.setHeading',\n scrollIntoView: true,\n }),\n );\n return true;\n };\n};\n\n//\n// Styles\n//\n\nexport const setStyle = (type: Inline, enable: boolean): StateCommand => {\n return ({ state, dispatch }) => {\n const marker = inlineMarkerText(type);\n const changes = state.changeByRange((range) => {\n // Special case for markers directly around the cursor, which will often not be parsed as valid styling.\n if (!enable && range.empty) {\n const after = state.doc.sliceString(range.head, range.head + 6);\n const found = after.indexOf(marker);\n if (found >= 0 && /^[*~`]*$/.test(after.slice(0, found))) {\n const before = state.doc.sliceString(range.head - 6, range.head);\n if (\n before.slice(before.length - found - marker.length, before.length - found) === marker &&\n [...before.slice(before.length - found)].reverse().join('') === after.slice(0, found)\n ) {\n return {\n changes: [\n { from: range.head - marker.length - found, to: range.head - found },\n { from: range.head + found, to: range.head + found + marker.length },\n ],\n range: EditorSelection.cursor(range.from - marker.length),\n };\n }\n }\n }\n\n const changes: ChangeSpec[] = [];\n // Used to add insertions that should happen *after* any other insertions at the same position.\n const changesAtEnd: ChangeSpec[] = [];\n let blockStart = -1;\n let blockEnd = -1;\n let startCovered: boolean | { from: number; to: number } = false;\n let endCovered: boolean | { from: number; to: number } = false;\n let { from, to } = range;\n\n // Iterate the selected range. For each textblock, determine a start and end position,\n // the overlap of the selected range and the block's extent, that should be styled/unstyled.\n syntaxTree(state).iterate({\n from,\n to,\n enter: (node) => {\n const { name } = node;\n if (Object.hasOwn(Textblocks, name) && Textblocks[name] !== 'codeblock') {\n // Set up for this textblock.\n blockStart = blockContentStart(node);\n blockEnd = blockContentEnd(node, state.doc);\n startCovered = endCovered = false;\n } else if (name === 'Link' || (name === 'Image' && enable)) {\n // If the range partially overlaps a link or image, expand it to cover it.\n if (from < node.from && to > node.from && to <= node.to) {\n to = node.to;\n } else if (to > node.to && from >= node.from && from < node.to) {\n from = node.from;\n }\n } else if (IgnoreInline.has(name) && enable) {\n // Move endpoints out of markers.\n if (node.from < from && node.to > from) {\n if (to === from) {\n to = node.to;\n }\n from = node.to;\n }\n if (node.from < to && node.to > to) {\n to = node.from;\n }\n } else if (Object.hasOwn(InlineMarker, name)) {\n // This is an inline marker node.\n const markType = InlineMarker[name];\n const size = inlineMarkerText(markType).length;\n const openEnd = node.from + size;\n const closeStart = node.to - size;\n // Determine whether the start/end of the range is covered\n // by this.\n if (markType === type) {\n if (openEnd <= from && closeStart >= from) {\n startCovered =\n !enable && openEnd === skipMarkers(from, node.node, -1, openEnd)\n ? { from: node.from, to: openEnd }\n : true;\n }\n if (openEnd <= to && closeStart >= to) {\n endCovered =\n !enable && closeStart === skipMarkers(to, node.node, 1, closeStart)\n ? { from: closeStart, to: node.to }\n : true;\n }\n }\n // Marks of the same type in range, or any mark if we're adding code style, need to be removed.\n if (markType === type || (type === Inline.Code && enable)) {\n if (node.from >= from && openEnd <= to) {\n changes.push({ from: node.from, to: openEnd });\n if (markType !== type && closeStart >= to) {\n // End marker outside, move start\n changesAtEnd.push({\n from: skipSpaces(Math.min(to, blockEnd), state.doc, 1, blockEnd),\n insert: inlineMarkerText(markType),\n });\n }\n }\n if (closeStart >= from && node.to <= to) {\n changes.push({ from: closeStart, to: node.to });\n if (markType !== type && openEnd <= from) {\n // Start marker outside, move end\n changes.push({\n from: skipSpaces(Math.max(from, blockStart), state.doc, -1, blockStart),\n insert: inlineMarkerText(markType),\n });\n }\n }\n }\n }\n },\n leave: (node) => {\n if (Object.hasOwn(Textblocks, node.name) && Textblocks[node.name] !== 'codeblock') {\n // Finish opening/closing the marks for this textblock.\n const rangeStart = Math.max(from, blockStart);\n const rangeEnd = Math.min(to, blockEnd);\n if (enable) {\n if (!startCovered) {\n changes.push({ from: rangeStart, insert: marker });\n }\n if (!endCovered) {\n changes.push({ from: rangeEnd, insert: marker });\n }\n } else {\n if (typeof startCovered === 'object') {\n changes.push(startCovered);\n } else if (startCovered) {\n changes.push({ from: skipSpaces(rangeStart, state.doc, -1, blockStart), insert: marker });\n }\n if (typeof endCovered === 'object') {\n changes.push(endCovered);\n } else if (endCovered) {\n changes.push({ from: skipSpaces(rangeEnd, state.doc, 1, blockEnd), insert: marker });\n }\n }\n }\n },\n });\n\n if (blockStart < 0 && range.empty && enable && !/\\S/.test(state.doc.lineAt(range.from).text)) {\n return {\n changes: { from: range.head, insert: marker + marker },\n range: EditorSelection.cursor(range.head + marker.length),\n };\n }\n\n const changeSet = state.changes(changes.concat(changesAtEnd));\n return {\n changes: changeSet,\n range:\n range.empty && !changeSet.empty\n ? EditorSelection.cursor(range.head + marker.length)\n : EditorSelection.range(changeSet.mapPos(range.from, 1), changeSet.mapPos(range.to, -1)),\n };\n });\n\n dispatch(\n state.update(changes, {\n userEvent: enable ? 'format.style.add' : 'format.style.remove',\n scrollIntoView: true,\n }),\n );\n\n return true;\n };\n};\n\nexport const addStyle = (style: Inline): StateCommand => setStyle(style, true);\n\nexport const removeStyle = (style: Inline): StateCommand => setStyle(style, false);\n\nexport const toggleStyle = (style: Inline): StateCommand => {\n return (arg) => {\n const form = getFormatting(arg.state);\n return setStyle(\n style,\n style === Inline.Strong\n ? !form.strong\n : style === Inline.Emphasis\n ? !form.emphasis\n : style === Inline.Strikethrough\n ? !form.strikethrough\n : !form.code,\n )(arg);\n };\n};\n\nexport const toggleStrong = toggleStyle(Inline.Strong);\nexport const toggleEmphasis = toggleStyle(Inline.Emphasis);\nexport const toggleStrikethrough = toggleStyle(Inline.Strikethrough);\nexport const toggleInlineCode = toggleStyle(Inline.Code);\n\nconst inlineMarkerText = (type: Inline) =>\n type === Inline.Strong ? '**' : type === Inline.Strikethrough ? '~~' : type === Inline.Emphasis ? '*' : '`';\n\n//\n// Utils\n//\n\nconst blockContentStart = (node: SyntaxNodeRef) => {\n const atx = /^ATXHeading(\\d)/.exec(node.name);\n if (atx) {\n return Math.min(node.to, node.from + +atx[1] + 1);\n }\n return node.from;\n};\n\nconst blockContentEnd = (node: SyntaxNodeRef, doc: Text) => {\n const setext = /^SetextHeading(\\d)/.exec(node.name);\n const lastLine = doc.lineAt(node.to);\n if (setext || /^[\\s>]*$/.exec(lastLine.text)) {\n return lastLine.from - 1;\n }\n return node.to;\n};\n\nconst skipSpaces = (pos: number, doc: Text, dir: -1 | 1, limit?: number) => {\n const line = doc.lineAt(pos);\n while (pos !== limit && line.text[pos - line.from - (dir < 0 ? 1 : 0)] === ' ') {\n pos += dir;\n }\n return pos;\n};\n\nconst skipMarkers = (pos: number, tree: SyntaxNode, dir: -1 | 1, limit?: number) => {\n for (;;) {\n const next = tree.resolve(pos, dir);\n if (!IgnoreInline.has(next.name)) {\n return pos;\n }\n const moveTo = dir < 0 ? next.from : next.to;\n if (limit != null && (dir < 0 ? moveTo < limit : moveTo > limit)) {\n return pos;\n }\n pos = moveTo;\n }\n};\n\n// TODO(burdon): Define and trigger snippets for codeblock, table, etc.\nconst snippets = {\n codeblock: snippet(\n [\n //\n '```#{}',\n '',\n '```',\n ].join('\\n'),\n ),\n table: snippet(\n [\n //\n '| #{col1} | #{col2} |',\n '| ---- | ---- |',\n '| #{val1} | #{val2} |',\n '| #{val3} | #{val4} |',\n '',\n ].join('\\n'),\n ),\n};\n\n//\n// Table\n//\n\nexport const insertTable = (view: EditorView) => {\n const {\n selection: { main },\n doc,\n } = view.state;\n const { number } = doc.lineAt(main.anchor);\n const { from } = doc.line(number);\n\n snippets.table(view, null, from, from);\n};\n\n//\n// Links\n//\n\n// For each link in the given range, remove the link markup\nconst removeLinkInner = (from: number, to: number, changes: ChangeSpec[], state: EditorState) => {\n syntaxTree(state).iterate({\n from,\n to,\n enter: (node) => {\n if (node.name === 'Link' && node.from < to && node.to > from) {\n node.node.cursor().iterate((node) => {\n const { name } = node;\n if (name === 'LinkMark' || name === 'LinkLabel') {\n changes.push({ from: node.from, to: node.to });\n } else if (name === 'LinkTitle' || name === 'URL') {\n changes.push({ from: skipSpaces(node.from, state.doc, -1), to: skipSpaces(node.to, state.doc, 1) });\n }\n });\n return false;\n }\n },\n });\n};\n\n// Remove all links touching the selection\nexport const removeLink: StateCommand = ({ state, dispatch }) => {\n const changes: ChangeSpec[] = [];\n for (const { from, to } of state.selection.ranges) {\n removeLinkInner(from, to, changes, state);\n }\n if (!changes) {\n return false;\n }\n dispatch(state.update({ changes, userEvent: 'format.link.remove', scrollIntoView: true }));\n return true;\n};\n\n// Add link markup around the selection.\nexport const addLink = ({ url, image }: { url?: string; image?: boolean } = {}): StateCommand => {\n return ({ state, dispatch }) => {\n const changes = state.changeByRange((range) => {\n let { from, to } = range;\n const cutStyles: SyntaxNode[] = [];\n let okay: boolean | null = null;\n // Check whether this range is in a position where a link makes sense.\n syntaxTree(state).iterate({\n from,\n to,\n enter: (node) => {\n if (Object.hasOwn(Textblocks, node.name)) {\n // If the selection spans multiple textblocks or is in a code block, abort.\n okay =\n Textblocks[node.name] !== 'codeblock' &&\n from >= blockContentStart(node) &&\n to <= blockContentEnd(node, state.doc);\n } else if (Object.hasOwn(InlineMarker, node.name)) {\n // Look for inline styles that partially overlap the range.\n // Expand the range over them if they start directly outside, otherwise mark them for later.\n const sNode = node.node;\n if (node.from < from && node.to <= to) {\n if (sNode.firstChild!.to === from) {\n from = node.from;\n } else {\n cutStyles.push(sNode);\n }\n } else if (node.from >= from && node.to > to) {\n if (sNode.lastChild!.from === to) {\n to = node.to;\n } else {\n cutStyles.push(sNode);\n }\n }\n }\n },\n });\n\n if (okay === null) {\n // No textblock found around selection. Check if the rest of the line is empty.\n const line = state.doc.lineAt(from);\n okay = to <= line.to && !/\\S/.test(line.text.slice(from - line.from));\n }\n if (!okay) {\n return { range };\n }\n\n const changes: ChangeSpec[] = [];\n // Some changes must be moved to end of change array so that they are applied in the right order.\n const changesAfter: ChangeSpec[] = [];\n // Clear existing links.\n removeLinkInner(from, to, changesAfter, state);\n let cursorOffset = 1;\n // Close and reopen inline styles that partially overlap the range.\n for (const style of cutStyles) {\n const type = InlineMarker[style.name];\n const mark = inlineMarkerText(type);\n if (style.from < from) {\n // Extends before.\n changes.push({ from: skipSpaces(from, state.doc, -1), insert: mark });\n changesAfter.push({ from: skipSpaces(from, state.doc, 1, to), insert: mark });\n } else {\n changes.push({ from: skipSpaces(to, state.doc, -1, from), insert: mark });\n const after = skipSpaces(to, state.doc, 1);\n if (after === to) {\n cursorOffset += mark.length;\n }\n changesAfter.push({ from: after, insert: mark });\n }\n }\n\n // Add the link markup.\n changes.push({ from, insert: image ? '` });\n const changeSet = state.changes(changes.concat(changesAfter));\n // Put the cursor between the title or parenthesis.\n return {\n changes: changeSet,\n range: EditorSelection.cursor(changeSet.mapPos(to, 1) - cursorOffset - (url ? url.length + 2 : 0)),\n };\n });\n\n if (changes.changes.empty) {\n return false;\n }\n\n dispatch(\n state.update(changes, {\n userEvent: 'format.link.add',\n scrollIntoView: true,\n }),\n );\n return true;\n };\n};\n\n//\n// Lists\n//\n\nexport const addList = (type: List): StateCommand => {\n return ({ state, dispatch }) => {\n let lastBlock = -1;\n let counter = 1;\n let first = true;\n let parentColumn: number | null = null;\n\n // Scan the syntax tree to locate textblocks that can be wrapped.\n const blocks: { node: SyntaxNode; counter: number; parentColumn: number | null }[] = [];\n for (const { from, to } of state.selection.ranges) {\n syntaxTree(state).iterate({\n from,\n to,\n enter: (node) => {\n if ((Object.hasOwn(Textblocks, node.name) && node.name !== 'TableCell') || node.name === 'Table') {\n if (first) {\n // For the first block, see if it follows a list,\n // so we can take indentation and numbering information from that one.\n let before = node.node.prevSibling;\n while (before && /Mark$/.test(before.name)) {\n before = before.prevSibling;\n }\n if (before?.name === (type === List.Ordered ? 'OrderedList' : 'BulletList')) {\n const item = before.lastChild!;\n const itemLine = state.doc.lineAt(item.from);\n const itemText = itemLine.text.slice(item.from - itemLine.from);\n parentColumn = item.from - itemLine.from + /^\\s*/.exec(itemText)![0].length;\n if (type === List.Ordered) {\n const mark = /^\\s*(\\d+)[.)]/.exec(itemText);\n if (mark) {\n parentColumn += mark[1].length;\n counter = +mark[1] + 1;\n }\n }\n }\n first = false;\n }\n if (node.from === lastBlock) {\n return;\n }\n\n lastBlock = node.from;\n blocks.push({ node: node.node, counter, parentColumn });\n counter++;\n return false;\n }\n },\n leave: (node) => {\n // When exiting block-level markup, reset the indentation and counter.\n if (node.name === 'BulletList' || node.name === 'OrderedList' || node.name === 'Blockquote') {\n counter = 1;\n parentColumn = null;\n }\n },\n });\n }\n\n if (!blocks.length) {\n // Insert a new list item if the selection is empty.\n const { from, to } = state.doc.lineAt(state.selection.main.anchor);\n if (from === to) {\n const insert = type === List.Bullet ? '- ' : type === List.Ordered ? '1. ' : '- [ ] ';\n dispatch(\n state.update({\n changes: [\n {\n from,\n insert,\n },\n ],\n selection: { anchor: from + insert.length },\n userEvent: 'format.list.add',\n scrollIntoView: true,\n }),\n );\n return true;\n }\n\n return false;\n }\n\n const changes: ChangeSpec[] = [];\n for (let i = 0; i < blocks.length; i++) {\n const { node, counter, parentColumn } = blocks[i];\n const nodeFrom = node.name === 'CodeBlock' ? node.from - 4 : node.from;\n // Compute a padding based on whether we are after whitespace.\n let padding = nodeFrom > 0 && !/\\s/.test(state.doc.sliceString(nodeFrom - 1, nodeFrom)) ? 1 : 0;\n // On ordered lists, the number is counted in the padding.\n if (type === List.Ordered) {\n padding += String(counter).length;\n }\n let line = state.doc.lineAt(nodeFrom);\n const column = nodeFrom - line.from;\n // Align to the list above if possible.\n if (parentColumn !== null && parentColumn > column) {\n padding = Math.max(padding, parentColumn - column);\n }\n\n let mark;\n if (type === List.Ordered) {\n // Scan ahead to find the max number we're adding, adjust padding for that.\n let max = counter;\n for (let j = i + 1; j < blocks.length; j++) {\n if (blocks[j].counter !== max + 1) {\n break;\n }\n max++;\n }\n const num = String(counter);\n padding = Math.max(String(max).length, padding);\n mark = ' '.repeat(Math.max(0, padding - num.length)) + num + '. ';\n } else {\n mark = ' '.repeat(padding) + '- ' + (type === List.Task ? '[ ] ' : '');\n }\n\n changes.push({ from: nodeFrom, insert: mark });\n // Add indentation for the other lines in this block.\n while (line.to < node.to) {\n line = state.doc.lineAt(line.to + 1);\n const open = /^[\\s>]*/.exec(line.text)![0].length;\n changes.push({ from: line.from + Math.min(open, column), insert: ' '.repeat(mark.length) });\n }\n }\n\n // If we are inserting an ordered list and there is another one right after the last selected block,\n // renumber that one to match the new order.\n if (type === List.Ordered) {\n const last = blocks[blocks.length - 1];\n let next = last.node.nextSibling;\n while (next && /Mark$/.test(next.name)) {\n next = next.nextSibling;\n }\n if (next?.name === 'OrderedList') {\n renumberListItems(next.firstChild, last.counter + 1, changes, state.doc);\n }\n }\n const changeSet = state.changes(changes);\n dispatch(\n state.update({\n changes: changeSet,\n selection: state.selection.map(changeSet, 1),\n userEvent: 'format.list.add',\n scrollIntoView: true,\n }),\n );\n return true;\n };\n};\n\nexport const removeList = (type: List): StateCommand => {\n return ({ state, dispatch }) => {\n let lastBlock = -1;\n const changes: ChangeSpec[] = [];\n const stack: string[] = [];\n const targetNodeType = type === List.Ordered ? 'OrderedList' : type === List.Bullet ? 'BulletList' : 'TaskList';\n // Scan the syntax tree to locate list items that can be unwrapped.\n for (const { from, to } of state.selection.ranges) {\n syntaxTree(state).iterate({\n from,\n to,\n enter: (node) => {\n const { name } = node;\n if (name === 'BulletList' || name === 'OrderedList' || name === 'Blockquote') {\n // Maintain block context.\n stack.push(name);\n } else if (name === 'Task' && stack[stack.length - 1] === 'BulletList') {\n stack[stack.length - 1] = 'TaskList';\n }\n },\n leave: (node) => {\n const { name } = node;\n if (name === 'BulletList' || name === 'OrderedList' || name === 'Blockquote') {\n stack.pop();\n } else if (name === 'ListItem' && stack[stack.length - 1] === targetNodeType && node.from !== lastBlock) {\n lastBlock = node.from;\n let line = state.doc.lineAt(node.from);\n const mark = /^\\s*(\\d+[.)] |[-*+] (\\[[ x]\\] )?)/.exec(line.text.slice(node.from - line.from));\n if (!mark) {\n return false;\n }\n const column = node.from - line.from;\n // Delete the marker on the first line.\n changes.push({ from: node.from, to: node.from + mark[0].length });\n // and indentation on subsequent lines.\n while (line.to < node.to) {\n line = state.doc.lineAt(line.to + 1);\n const open = /^[\\s>]*/.exec(line.text)![0].length;\n if (open > column) {\n changes.push({ from: line.from + column, to: line.from + Math.min(column + mark[0].length, open) });\n }\n }\n if (node.to >= to) {\n renumberListItems(node.node.nextSibling, 1, changes, state.doc);\n }\n return false;\n }\n },\n });\n }\n if (!changes.length) {\n return false;\n }\n\n dispatch(\n state.update({\n changes,\n userEvent: 'format.list.remove',\n scrollIntoView: true,\n }),\n );\n return true;\n };\n};\n\nexport const toggleList = (type: List): StateCommand => {\n return (target) => {\n const formatting = getFormatting(target.state);\n const active =\n formatting.listStyle === (type === List.Bullet ? 'bullet' : type === List.Ordered ? 'ordered' : 'task');\n return (active ? removeList(type) : addList(type))(target);\n };\n};\n\nconst renumberListItems = (item: SyntaxNode | null, counter: number, changes: ChangeSpec[], doc: Text) => {\n for (; item; item = item.nextSibling) {\n if (item.name === 'ListItem') {\n const number = /(\\s*)(\\d+)[.)]/.exec(doc.sliceString(item.from, item.from + 10));\n if (!number || +number[2] === counter) {\n break;\n }\n const size = number[1].length + number[2].length;\n const newNum = String(counter);\n changes.push({ from: item.from + Math.max(0, size - newNum.length), to: item.from + size, insert: newNum });\n counter++;\n }\n }\n};\n\n//\n// Block quotes\n//\n\nexport const setBlockquote = (enable: boolean): StateCommand => {\n return ({ state, dispatch }) => {\n const lines: Line[] = [];\n let lastBlock = -1;\n for (const { from, to } of state.selection.ranges) {\n const sawBlock = false;\n syntaxTree(state).iterate({\n from,\n to,\n enter: (node) => {\n if (Object.hasOwn(Textblocks, node.name) || node.name === 'Table') {\n if (node.from === lastBlock) {\n return false;\n }\n lastBlock = node.from;\n let line = state.doc.lineAt(node.from);\n if (line.number > 1) {\n const prevLine = state.doc.line(line.number - 1);\n if (/^[>\\s]*$/.test(prevLine.text)) {\n if (!enable || (lines.length && lines[lines.length - 1].number === prevLine.number - 1)) {\n lines.push(prevLine);\n }\n }\n }\n for (;;) {\n lines.push(line);\n if (line.to >= node.to) {\n break;\n }\n line = state.doc.line(line.number + 1);\n }\n if (!enable && line.number < state.doc.lines) {\n const nextLine = state.doc.line(line.number + 1);\n if (/^[>\\s]*$/.test(nextLine.text)) {\n lines.push(nextLine);\n }\n }\n return false;\n }\n },\n });\n let line;\n if (!sawBlock && enable && from === to && !/\\S/.test((line = state.doc.lineAt(from)).text)) {\n lines.push(line);\n }\n }\n\n const changes: ChangeSpec[] = [];\n for (const line of lines) {\n if (enable) {\n changes.push({ from: line.from, insert: /\\S/.test(line.text) ? '> ' : '>' });\n } else {\n const quote = /((?:[\\s>\\-+*]|\\d+[.)])*?)> ?/.exec(line.text);\n if (quote) {\n changes.push({ from: line.from + quote[1].length, to: line.from + quote[0].length });\n }\n }\n }\n if (!changes.length) {\n return false;\n }\n\n const changeSet = state.changes(changes);\n dispatch(\n state.update({\n changes: changeSet,\n selection: state.selection.map(changeSet, 1),\n userEvent: enable ? 'format.blockquote.add' : 'format.blockquote.remove',\n scrollIntoView: true,\n }),\n );\n return true;\n };\n};\n\nexport const addBlockquote = setBlockquote(true);\n\nexport const removeBlockquote = setBlockquote(false);\n\nexport const toggleBlockquote: StateCommand = (target) => {\n return (getFormatting(target.state).blockQuote ? removeBlockquote : addBlockquote)(target);\n};\n\n//\n// Code block\n//\n\nexport const addCodeblock: StateCommand = (target) => {\n const { state, dispatch } = target;\n const { selection } = state;\n // If on a blank line, use the code block snippet.\n if (selection.ranges.length === 1 && selection.main.empty) {\n const { head } = selection.main;\n const line = state.doc.lineAt(head);\n if (!/\\S/.test(line.text) && head === line.from) {\n snippets.codeblock(target, null, line.from, line.to);\n return true;\n }\n }\n\n // Otherwise, wrap any selected blocks in triple backticks.\n const ranges: { from: number; to: number }[] = [];\n for (const { from, to } of selection.ranges) {\n let blockFrom = from;\n let blockTo = to;\n syntaxTree(state).iterate({\n from,\n to,\n enter: (node) => {\n if (Object.hasOwn(Textblocks, node.name)) {\n if (from >= node.from && to <= node.to) {\n // Selection in a single block.\n blockFrom = node.from;\n blockTo = node.to;\n } else {\n // Expand to cover whole lines.\n blockFrom = Math.min(blockFrom, state.doc.lineAt(node.from).from);\n blockTo = Math.max(blockTo, state.doc.lineAt(node.to).to);\n }\n }\n },\n });\n if (ranges.length && ranges[ranges.length - 1].to >= blockFrom - 1) {\n ranges[ranges.length - 1].to = blockTo;\n } else {\n ranges.push({ from: blockFrom, to: blockTo });\n }\n }\n if (!ranges.length) {\n return false;\n }\n\n const changes: ChangeSpec[] = ranges.map(({ from, to }) => {\n const column = from - state.doc.lineAt(from).from;\n return [\n { from, insert: '```\\n' + ' '.repeat(column) },\n { from: to, insert: '\\n' + ' '.repeat(column) + '```' },\n ];\n });\n\n dispatch(\n state.update({\n changes,\n userEvent: 'format.codeblock.add',\n scrollIntoView: true,\n }),\n );\n\n return true;\n};\n\nexport const removeCodeblock: StateCommand = ({ state, dispatch }) => {\n let lastBlock = -1;\n\n // Find all code blocks, remove their markup.\n const changes: ChangeSpec[] = [];\n for (const { from, to } of state.selection.ranges) {\n syntaxTree(state).iterate({\n from,\n to,\n enter: (node) => {\n if (Textblocks[node.name] === 'codeblock' && lastBlock !== node.from) {\n lastBlock = node.from;\n const firstLine = state.doc.lineAt(node.from);\n if (node.name === 'FencedCode') {\n changes.push({ from: node.from, to: firstLine.to + 1 + node.from - firstLine.from });\n const lastLine = state.doc.lineAt(node.to);\n if (/^([\\s>]|[-*+] |\\d+[).])*`+$/.test(lastLine.text)) {\n changes.push({\n from: lastLine.from - (lastLine.number === firstLine.number + 1 ? 0 : 1),\n to: lastLine.to,\n });\n }\n } else {\n // Indented code block.\n const column = node.from - firstLine.from;\n for (let line = firstLine; ; line = state.doc.line(line.number + 1)) {\n changes.push({ from: line.from + column - 4, to: line.from + column });\n if (line.to >= node.to) {\n break;\n }\n }\n }\n }\n },\n });\n }\n if (!changes.length) {\n return false;\n }\n\n dispatch(state.update({ changes, userEvent: 'format.codeblock.remove', scrollIntoView: true }));\n return true;\n};\n\nexport const toggleCodeblock: StateCommand = (target) => {\n return (getFormatting(target.state).blockType === 'codeblock' ? removeCodeblock : addCodeblock)(target);\n};\n\n//\n// Formatting extension.\n//\n\nexport type FormattingOptions = {};\n\nexport const formattingKeymap = (_options: FormattingOptions = {}): Extension => {\n return [\n keymap.of([\n {\n key: 'meta-b',\n run: toggleStrong,\n },\n {\n key: 'meta-i',\n run: toggleEmphasis,\n },\n ]),\n ];\n};\n\nconst InlineMarker: { [name: string]: number } = {\n Emphasis: Inline.Emphasis,\n StrongEmphasis: Inline.Strong,\n InlineCode: Inline.Code,\n Strikethrough: Inline.Strikethrough,\n};\n\nconst IgnoreInline = new Set([\n 'Autolink',\n 'CodeMark',\n 'CodeText',\n 'Comment',\n 'EmphasisMark',\n 'Hardbreak',\n 'HeaderMark',\n 'HTMLTag',\n 'LinkMark',\n 'ListMark',\n 'ProcessingInstruction',\n 'QuoteMark',\n 'StrikethroughMark',\n 'SubscriptMark',\n 'SuperscriptMark',\n 'TaskMarker',\n]);\n\nconst Textblocks: { [name: string]: NonNullable<Formatting['blockType']> } = {\n ATXHeading1: 'heading1',\n ATXHeading2: 'heading2',\n ATXHeading3: 'heading3',\n ATXHeading4: 'heading4',\n ATXHeading5: 'heading5',\n ATXHeading6: 'heading6',\n CodeBlock: 'codeblock',\n FencedCode: 'codeblock',\n Paragraph: 'paragraph',\n SetextHeading1: 'heading1',\n SetextHeading2: 'heading2',\n TableCell: 'tablecell',\n Task: 'paragraph',\n};\n\n/**\n * Query the editor state for the active formatting at the selection.\n */\nexport const getFormatting = (state: EditorState): Formatting => {\n // These will track the formatting we've seen so far.\n // False indicates mixed block types.\n let blockType: Formatting['blockType'] | false = null;\n // Indexed by the Inline enum, tracks inline markup.\n // null = no text seen, true = all text had the mark, false = saw text without it.\n const inline: (boolean | null)[] = [null, null, null, null];\n let link: boolean = false;\n let blockQuote: boolean | null = null;\n // False indicates mixed list styles.\n let listStyle: Formatting['listStyle'] | null | false = null;\n\n // Track block context for list/blockquote handling.\n const stack: ('BulletList' | 'OrderedList' | 'Blockquote' | 'TaskList')[] = [];\n // This is set when entering a textblock (paragraph, heading, etc.)\n // and cleared when exiting again. It is used to track inline style.\n // `active` holds an array that indicates, for the various style (`Inline` enum) whether they are currently active.\n let currentBlock: { pos: number; end: number; active: boolean[] } | null = null;\n // Advance over regular inline text. Will update `inline` depending on what styles are active.\n const advanceInline = (upto: number) => {\n if (!currentBlock) {\n return;\n }\n upto = Math.min(upto, currentBlock.end);\n if (upto <= currentBlock.pos) {\n return;\n }\n for (let i = 0; i < currentBlock.active.length; i++) {\n if (inline[i] === false) {\n continue;\n } else if (currentBlock.active[i]) {\n inline[i] = true;\n } else if (/\\S/.test(state.doc.sliceString(currentBlock.pos, upto))) {\n inline[i] = false;\n }\n }\n currentBlock.pos = upto;\n };\n\n // Skip markup that shouldn't be treated as inline text for style-tracking purposes.\n const skipInline = (upto: number) => {\n if (currentBlock && upto > currentBlock.pos) {\n currentBlock.pos = Math.min(upto, currentBlock.end);\n }\n };\n\n const { selection } = state;\n for (const range of selection.ranges) {\n if (range.empty && inline.some((v) => v === null)) {\n // Check for markers directly around the cursor (which, not being valid Markdown, the syntax tree won't pick up).\n const contextSize = Math.min(range.head, 6);\n const contextBefore = state.doc.sliceString(range.head - contextSize, range.head);\n let contextAfter = state.doc.sliceString(range.head, range.head + contextSize);\n for (let i = 0; i < contextSize; i++) {\n const ch = contextAfter[i];\n if (ch !== contextBefore[contextBefore.length - 1 - i] || !/[~`*]/.test(ch)) {\n contextAfter = contextAfter.slice(0, i);\n break;\n }\n }\n for (let i = 0; i < inline.length; i++) {\n const mark = inlineMarkerText(i);\n const found = contextAfter.indexOf(mark);\n if (found > -1) {\n contextAfter = contextAfter.slice(0, found) + contextAfter.slice(found + mark.length);\n if (inline[i] === null) {\n inline[i] = true;\n }\n }\n }\n }\n\n syntaxTree(state).iterate({\n from: range.from,\n to: range.to,\n enter: (node) => {\n advanceInline(node.from);\n const { name } = node;\n if (name === 'BulletList' || name === 'OrderedList' || name === 'Blockquote') {\n // Maintain block context.\n stack.push(name);\n } else if (name === 'Link') {\n link = true;\n } else if (Object.hasOwn(Textblocks, name) && (range.empty || node.to > range.from || node.from < range.to)) {\n if (name === 'Task' && stack[stack.length - 1] === 'BulletList') {\n stack[stack.length - 1] = 'TaskList';\n }\n const blockCode = Textblocks[name];\n if (blockType === null) {\n blockType = blockCode;\n } else if (blockType !== blockCode) {\n blockType = false;\n }\n if (blockCode !== 'codeblock' && inline.some((i) => i !== false)) {\n // Set up inline content tracking for non-code textblocks.\n currentBlock = {\n pos: Math.max(range.from, node.from),\n end: Math.min(range.to, node.to),\n active: [false, false, false, false],\n };\n }\n } else if (Object.hasOwn(InlineMarker, name) && currentBlock) {\n const index = InlineMarker[name];\n // Cursors selections always count as active.\n if (range.empty && inline[index] === null) {\n inline[index] = true;\n }\n currentBlock.active[index] = true;\n } else if (IgnoreInline.has(name)) {\n skipInline(node.to);\n }\n },\n leave: (node) => {\n advanceInline(node.to);\n const { name } = node;\n if (name === 'BulletList' || name === 'OrderedList' || name === 'Blockquote') {\n // Track block context.\n stack.pop();\n } else if (Object.hasOwn(Textblocks, name)) {\n // Scan the stack for blockquote/list context.\n // Done at end of node because task lists aren't recognized until a task is seen\n let hasList: Formatting['listStyle'] | false = false;\n let hasQuote = false;\n for (let i = stack.length - 1; i >= 0; i--) {\n if (stack[i] === 'Blockquote') {\n hasQuote = true;\n } else if (!hasList) {\n hasList = stack[i] === 'TaskList' ? 'task' : stack[i] === 'BulletList' ? 'bullet' : 'ordered';\n }\n }\n if (blockQuote === null) {\n blockQuote = hasQuote;\n } else if (!hasQuote && blockQuote) {\n blockQuote = false;\n }\n if (listStyle === null) {\n listStyle = hasList;\n } else if (listStyle !== hasList) {\n listStyle = false;\n }\n\n // End textblock.\n currentBlock = null;\n } else if (Object.hasOwn(InlineMarker, name) && currentBlock) {\n // Track markup in textblock.\n currentBlock.active[InlineMarker[name]] = false;\n }\n },\n });\n }\n\n const { from, to } = state.doc.lineAt(selection.main.anchor);\n const blankLine = from === to;\n\n return {\n blankLine,\n blockType: blockType || null,\n blockQuote: blockQuote ?? false,\n code: inline[Inline.Code] ?? false,\n emphasis: inline[Inline.Emphasis] ?? false,\n strong: inline[Inline.Strong] ?? false,\n strikethrough: inline[Inline.Strikethrough] ?? false,\n link,\n listStyle: listStyle || null,\n };\n};\n\n/**\n * Hook provides an extension to compute the current formatting state.\n */\nexport const useFormattingState = (state: Live<EditorToolbarState>): Extension => {\n return useMemo(\n () =>\n EditorView.updateListener.of((update) => {\n if (update.docChanged || update.selectionSet) {\n Object.entries(getFormatting(update.state)).forEach(([key, active]) => {\n state[key as keyof Formatting] = active as any;\n });\n }\n }),\n [],\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type EditorView } from '@codemirror/view';\n\nimport { type Action } from '@dxos/app-graph';\nimport { type MenuActionProperties } from '@dxos/react-ui-menu';\n\nimport {\n Inline,\n List,\n addBlockquote,\n addCodeblock,\n addLink,\n addList,\n insertTable,\n removeBlockquote,\n removeCodeblock,\n removeLink,\n removeList,\n setHeading,\n setStyle,\n toggleBlockquote,\n toggleList,\n toggleStyle,\n} from './formatting';\nimport { createComment } from '../comments';\n\nexport type PayloadType =\n | 'view-mode'\n | 'blockquote'\n | 'strong'\n | 'codeblock'\n | 'comment'\n | 'heading'\n | 'image'\n | 'emphasis'\n | 'code'\n | 'link'\n | 'list-bullet'\n | 'list-ordered'\n | 'list-task'\n | 'mention'\n | 'prompt'\n | 'search'\n | 'strikethrough'\n | 'table';\n\nexport type EditorActionPayload = {\n type: PayloadType;\n data?: any;\n};\n\nexport type EditorAction = Action<MenuActionProperties & EditorActionPayload>;\n\nexport type EditorPayloadHandler = (view: EditorView, payload: EditorActionPayload) => void;\n\nexport const processEditorPayload: EditorPayloadHandler = (view, { type, data }) => {\n let inlineType, listType;\n switch (type) {\n case 'heading':\n setHeading(parseInt(data))(view);\n break;\n\n case 'strong':\n case 'emphasis':\n case 'strikethrough':\n case 'code':\n inlineType =\n type === 'strong'\n ? Inline.Strong\n : type === 'emphasis'\n ? Inline.Emphasis\n : type === 'strikethrough'\n ? Inline.Strikethrough\n : Inline.Code;\n (typeof data === 'boolean' ? setStyle(inlineType, data) : toggleStyle(inlineType))(view);\n break;\n\n case 'list-ordered':\n case 'list-bullet':\n case 'list-task':\n listType = type === 'list-ordered' ? List.Ordered : type === 'list-bullet' ? List.Bullet : List.Task;\n (data === false ? removeList(listType) : data === true ? addList(listType) : toggleList(listType))(view);\n break;\n\n case 'blockquote':\n (data === false ? removeBlockquote : data === true ? addBlockquote : toggleBlockquote)(view);\n break;\n case 'codeblock':\n (data === false ? removeCodeblock : addCodeblock)(view);\n break;\n case 'table':\n insertTable(view);\n break;\n\n case 'link':\n (data === false ? removeLink : addLink())(view);\n break;\n\n case 'image':\n addLink({ url: data, image: true })(view);\n break;\n\n case 'comment':\n createComment(view);\n break;\n }\n\n requestAnimationFrame(() => {\n if (!view.hasFocus) {\n view.focus();\n }\n });\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { completionKeymap } from '@codemirror/autocomplete';\nimport { defaultKeymap, indentWithTab } from '@codemirror/commands';\nimport { markdownLanguage, markdown } from '@codemirror/lang-markdown';\nimport { syntaxHighlighting } from '@codemirror/language';\nimport { languages } from '@codemirror/language-data';\nimport { type Extension } from '@codemirror/state';\nimport { keymap } from '@codemirror/view';\n\nimport { type ThemeMode } from '@dxos/react-ui';\nimport { isNotFalsy } from '@dxos/util';\n\nimport { markdownHighlightStyle, markdownTagsExtensions } from './highlight';\n\nexport type MarkdownBundleOptions = {\n themeMode?: ThemeMode;\n indentWithTab?: boolean;\n};\n\n/**\n * Creates markdown extensions.\n * To be used in conjunction with createBasicExtensions.\n *\n * Refs:\n * https://codemirror.net/docs/community\n * https://codemirror.net/docs/ref/#codemirror.basicSetup\n */\nexport const createMarkdownExtensions = (options: MarkdownBundleOptions = {}): Extension[] => {\n return [\n // Main extension.\n // https://github.com/codemirror/lang-markdown\n // https://codemirror.net/5/mode/markdown/index.html (demo).\n markdown({\n // GRM by default (vs strict CommonMark):\n // Table, TaskList, Strikethrough, and Autolink.\n // NOTE: This extends the parser; it doesn't affect rendering.\n // https://github.github.com/gfm\n // https://github.com/lezer-parser/markdown?tab=readme-ov-file#github-flavored-markdown\n base: markdownLanguage,\n\n // Languages for syntax highlighting fenced code blocks.\n codeLanguages: languages,\n\n // Don't complete HTML tags.\n completeHTMLTags: false,\n\n // Parser extensions.\n extensions: [\n // GFM provided by default.\n markdownTagsExtensions,\n ],\n }),\n\n // Custom styles.\n syntaxHighlighting(markdownHighlightStyle()),\n\n keymap.of(\n [\n // https://codemirror.net/docs/ref/#commands.indentWithTab\n options.indentWithTab !== false && indentWithTab,\n\n // https://codemirror.net/docs/ref/#commands.defaultKeymap\n ...defaultKeymap,\n ...completionKeymap,\n ].filter(isNotFalsy),\n ),\n ];\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { markdownLanguage } from '@codemirror/lang-markdown';\nimport { HighlightStyle } from '@codemirror/language';\nimport { tags, styleTags, Tag } from '@lezer/highlight';\nimport { type MarkdownConfig, Table } from '@lezer/markdown';\n\nimport { fontBody, theme } from '../../styles';\n\n/**\n * Custom tags defined and processed by the GFM lezer extension.\n * https://github.com/lezer-parser/markdown\n * https://github.com/lezer-parser/markdown/blob/main/src/markdown.ts\n */\nexport const markdownTags = {\n Blockquote: Tag.define(),\n CodeMark: Tag.define(),\n CodeText: Tag.define(),\n EmphasisMark: Tag.define(),\n HeaderMark: Tag.define(),\n InlineCode: Tag.define(),\n LinkLabel: Tag.define(),\n LinkReference: Tag.define(),\n ListMark: Tag.define(),\n QuoteMark: Tag.define(),\n URL: Tag.define(),\n\n // Custom.\n TableCell: Tag.define(),\n};\n\n// TODO(burdon): Customize table parser (make all content monospace).\n// https://github.com/lezer-parser/markdown/blob/main/src/extension.ts\nTable.defineNodes?.forEach((node: any) => {\n switch (node?.name) {\n case 'TableCell': {\n node.style = markdownTags.TableCell;\n break;\n }\n }\n});\n\nexport const markdownTagsExtensions: MarkdownConfig[] = [\n Table,\n {\n props: [styleTags(markdownTags)],\n },\n];\n\nexport type HighlightOptions = {};\n\n/**\n * Styling based on `lezer` parser tags.\n * https://codemirror.net/examples/styling\n * https://github.com/lezer-parser/highlight\n * https://github.com/lezer-parser/highlight/blob/main/src/highlight.ts#L427\n * https://lezer.codemirror.net/docs/ref/#highlight.tags (list of tags)\n *\n * Examples:\n * - https://github.com/codemirror/language/blob/main/src/highlight.ts#L194\n * - https://github.com/codemirror/theme-one-dark/blob/main/src/one-dark.ts#L115\n */\nexport const markdownHighlightStyle = (_options: HighlightOptions = {}) => {\n return HighlightStyle.define(\n [\n {\n tag: [\n tags.keyword,\n tags.name,\n tags.deleted,\n tags.character,\n tags.propertyName,\n tags.macroName,\n tags.color,\n tags.constant(tags.name),\n tags.standard(tags.name),\n tags.definition(tags.name),\n tags.separator,\n tags.typeName,\n tags.className,\n tags.number,\n tags.changed,\n tags.annotation,\n tags.modifier,\n tags.self,\n tags.namespace,\n tags.operator,\n tags.operatorKeyword,\n tags.escape,\n tags.regexp,\n tags.special(tags.string),\n tags.meta,\n tags.comment,\n tags.atom,\n tags.bool,\n tags.special(tags.variableName),\n tags.processingInstruction,\n tags.string,\n tags.inserted,\n tags.invalid,\n ],\n // TODO(burdon): Explain.\n color: 'inherit !important',\n },\n\n // Markdown marks.\n {\n tag: [\n tags.meta,\n tags.processingInstruction,\n markdownTags.LinkLabel,\n markdownTags.LinkReference,\n markdownTags.ListMark,\n ],\n class: theme.mark,\n },\n\n // Markdown marks.\n {\n tag: [\n //\n markdownTags.CodeMark,\n markdownTags.HeaderMark,\n markdownTags.QuoteMark,\n markdownTags.EmphasisMark,\n ],\n class: theme.mark,\n },\n\n // E.g., code block language (after ```).\n {\n tag: [\n //\n tags.function(tags.variableName),\n tags.labelName,\n ],\n class: theme.codeMark,\n },\n\n // Fonts.\n {\n tag: [tags.monospace],\n class: 'font-mono',\n },\n\n // Headings.\n { tag: tags.heading1, class: theme.heading(1) },\n { tag: tags.heading2, class: theme.heading(2) },\n { tag: tags.heading3, class: theme.heading(3) },\n { tag: tags.heading4, class: theme.heading(4) },\n { tag: tags.heading5, class: theme.heading(5) },\n { tag: tags.heading6, class: theme.heading(6) },\n\n // Emphasis.\n { tag: tags.emphasis, class: 'italic' },\n { tag: tags.strong, class: 'font-bold' },\n { tag: tags.strikethrough, class: 'line-through' },\n\n // NOTE: The `markdown` extension configures extensions for `lezer` to parse markdown tokens (incl. below).\n // However, since `codeLanguages` is also defined, the `lezer` will not parse fenced code blocks,\n // when a language is specified. In this case, the syntax highlighting extensions will colorize\n // the code, but all other CSS properties will be inherited.\n // IMPORTANT: Therefore, the fenced code block will use the base editor font unless changed by an extension.\n {\n tag: [markdownTags.CodeText, markdownTags.InlineCode],\n class: theme.code,\n },\n\n {\n tag: [markdownTags.TableCell],\n class: 'font-mono',\n },\n ],\n {\n scope: markdownLanguage,\n all: {\n fontFamily: fontBody,\n },\n },\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { syntaxTree } from '@codemirror/language';\nimport { type EditorState, type Extension, StateField } from '@codemirror/state';\nimport { type TreeCursor } from '@lezer/common';\n\nexport const debugTree = (cb: (tree: DebugNode) => void): Extension =>\n StateField.define({\n create: (state) => cb(convertTreeToJson(state)),\n update: (value, tr) => cb(convertTreeToJson(tr.state)),\n });\n\nexport type DebugNode = {\n type: string;\n from: number;\n to: number;\n text: string;\n children: DebugNode[];\n};\n\nexport const convertTreeToJson = (state: EditorState): DebugNode => {\n const treeToJson = (cursor: TreeCursor): DebugNode => {\n const node: DebugNode = {\n type: cursor.type.name,\n from: cursor.from,\n to: cursor.to,\n text: state.doc.slice(cursor.from, cursor.to).toString(),\n children: [],\n };\n\n if (cursor.firstChild()) {\n do {\n node.children.push(treeToJson(cursor));\n } while (cursor.nextSibling());\n cursor.parent();\n }\n\n return node;\n };\n\n return treeToJson(syntaxTree(state).cursor());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { syntaxTree } from '@codemirror/language';\nimport { RangeSetBuilder, type EditorState, StateEffect } from '@codemirror/state';\nimport { EditorView, Decoration, type DecorationSet, WidgetType, ViewPlugin, type ViewUpdate } from '@codemirror/view';\nimport { type SyntaxNodeRef } from '@lezer/common';\n\nimport { invariant } from '@dxos/invariant';\nimport { mx } from '@dxos/react-ui-theme';\n\nimport { adjustChanges } from './changes';\nimport { image } from './image';\nimport { formattingStyles, bulletListIndentationWidth, orderedListIndentationWidth } from './styles';\nimport { table } from './table';\nimport { theme, type HeadingLevel } from '../../styles';\nimport { type RenderCallback } from '../../types';\nimport { wrapWithCatch } from '../../util';\n\n/**\n * Unicode characters.\n * NOTE: Depends on font.\n * https://www.compart.com/en/unicode (nice resource).\n * https://en.wikipedia.org/wiki/List_of_Unicode_characters\n */\nconst Unicode = {\n emDash: '\\u2014',\n bullet: '\\u2022',\n bulletSmall: '\\u2219',\n bulletSquare: '\\u2b1d',\n};\n\n//\n// Widgets\n//\n\nclass HorizontalRuleWidget extends WidgetType {\n override toDOM(): HTMLSpanElement {\n const el = document.createElement('span');\n el.className = 'cm-hr';\n return el;\n }\n}\n\nclass LinkButton extends WidgetType {\n constructor(\n private readonly url: string,\n private readonly render: RenderCallback<{ url: string }>,\n ) {\n super();\n }\n\n override eq(other: this): boolean {\n return this.url === other.url;\n }\n\n // TODO(burdon): Create icon and link directly without react?\n override toDOM(view: EditorView): HTMLSpanElement {\n const el = document.createElement('span');\n this.render(el, { url: this.url }, view);\n return el;\n }\n}\n\nclass CheckboxWidget extends WidgetType {\n constructor(private _checked: boolean) {\n super();\n }\n\n override eq(other: this): boolean {\n return this._checked === other._checked;\n }\n\n override toDOM(view: EditorView): HTMLSpanElement {\n const input = document.createElement('input');\n input.className = 'cm-task-checkbox dx-checkbox';\n input.type = 'checkbox';\n input.tabIndex = -1;\n input.checked = this._checked;\n if (view.state.readOnly) {\n input.setAttribute('disabled', 'true');\n } else {\n input.onmousedown = (event: Event) => {\n // Could be beginning of line.\n const line = view.state.doc.lineAt(view.posAtDOM(span));\n const text = view.state.sliceDoc(line.from, line.to);\n const match = text.match(/^\\s*- (\\[[xX ]]).*/);\n if (match) {\n const [, checked] = match;\n const pos = line.from + text.indexOf(checked);\n this._checked = checked !== '[ ]';\n view.dispatch({\n changes: { from: pos + 1, to: pos + 2, insert: this._checked ? ' ' : 'x' },\n });\n\n event.preventDefault();\n }\n };\n }\n\n const span = document.createElement('span');\n span.className = 'cm-task';\n span.appendChild(input);\n return span;\n }\n\n override ignoreEvent(): boolean {\n return false;\n }\n}\n\nclass TextWidget extends WidgetType {\n constructor(\n private readonly text: string,\n private readonly className?: string,\n ) {\n super();\n }\n\n override toDOM(): HTMLSpanElement {\n const el = document.createElement('span');\n if (this.className) {\n el.className = this.className;\n }\n el.innerText = this.text;\n return el;\n }\n}\n\nconst hide = Decoration.replace({});\nconst blockQuote = Decoration.line({ class: 'cm-blockquote' });\nconst fencedCodeLine = Decoration.line({ class: 'cm-code cm-codeblock-line' });\nconst fencedCodeLineFirst = Decoration.line({ class: mx('cm-code cm-codeblock-line', 'cm-codeblock-start') });\nconst fencedCodeLineLast = Decoration.line({ class: mx('cm-code cm-codeblock-line', 'cm-codeblock-end') });\nconst commentBlockLine = fencedCodeLine;\nconst commentBlockLineFirst = fencedCodeLineFirst;\nconst commentBlockLineLast = fencedCodeLineLast;\nconst horizontalRule = Decoration.replace({ widget: new HorizontalRuleWidget() });\nconst checkedTask = Decoration.replace({ widget: new CheckboxWidget(true) });\nconst uncheckedTask = Decoration.replace({ widget: new CheckboxWidget(false) });\n\n/**\n * Checks if cursor is inside text.\n */\nconst editingRange = (state: EditorState, range: { from: number; to: number }, focus: boolean) => {\n const {\n readOnly,\n selection: {\n main: { head },\n },\n } = state;\n return focus && !readOnly && head >= range.from && head <= range.to;\n};\n\nconst autoHideTags = new Set([\n 'CodeMark',\n 'CodeInfo',\n 'EmphasisMark',\n 'StrikethroughMark',\n 'SubscriptMark',\n 'SuperscriptMark',\n]);\n\n/**\n * Markdown list level.\n */\ntype NumberingLevel = { type: string; from: number; to: number; level: number; number: number };\n\nconst buildDecorations = (view: EditorView, options: DecorateOptions, focus: boolean) => {\n const deco = new RangeSetBuilder<Decoration>();\n const atomicDeco = new RangeSetBuilder<Decoration>();\n const { state } = view;\n\n // Header numbering.\n // TODO(burdon): Pre-parse headers to allow virtualization.\n const headerLevels: (NumberingLevel | null)[] = [];\n const getHeaderLevels = (node: SyntaxNodeRef, level: number): (NumberingLevel | null)[] => {\n invariant(level > 0);\n if (level > headerLevels.length) {\n const len = headerLevels.length;\n headerLevels.length = level;\n headerLevels.fill(null, len);\n headerLevels[level - 1] = { type: node.name, from: node.from, to: node.to, level, number: 0 };\n } else {\n headerLevels.splice(level);\n }\n\n return headerLevels.slice(0, level);\n };\n\n // List numbering and indentation.\n const listLevels: NumberingLevel[] = [];\n const enterList = (node: SyntaxNodeRef) => {\n listLevels.push({ type: node.name, from: node.from, to: node.to, level: listLevels.length, number: 0 });\n };\n const leaveList = () => {\n listLevels.pop();\n };\n const getCurrentListLevel = (): NumberingLevel => {\n invariant(listLevels.length);\n return listLevels[listLevels.length - 1];\n };\n\n // let count = 0;\n const enterNode = (node: SyntaxNodeRef) => {\n // console.log(`[${count++}]`, { node: node.name, from: node.from, to: node.to });\n switch (node.name) {\n // ATXHeading > HeaderMark > Paragraph\n // NOTE: Numbering requires processing the entire document since otherwise only the visible range will be\n // processed and the numbering will be incorrect.\n case 'ATXHeading1':\n case 'ATXHeading2':\n case 'ATXHeading3':\n case 'ATXHeading4':\n case 'ATXHeading5':\n case 'ATXHeading6': {\n const level = parseInt(node.name['ATXHeading'.length]) as HeadingLevel;\n const headers = getHeaderLevels(node, level);\n if (options.numberedHeadings?.from !== undefined) {\n const header = headers[level - 1];\n // TODO(burdon): Header will be missing if headers are out of order (e.g., ## header then # header).\n if (header) {\n header.number++;\n }\n }\n\n const editing = editingRange(state, node, focus);\n if (editing) {\n break;\n }\n\n const mark = node.node.firstChild!;\n if (mark?.name === 'HeaderMark') {\n const { from, to = 6 } = options.numberedHeadings ?? {};\n const text = view.state.sliceDoc(node.from, node.to);\n const len = text.match(/[#\\s]+/)![0].length;\n if (!from || level < from || level > to) {\n atomicDeco.add(mark.from, mark.from + len, hide);\n } else {\n // TODO(burdon): Number format/style.\n const num =\n headers\n .slice(from - 1)\n .map((level) => level?.number ?? 0)\n .join('.') + ' ';\n\n if (num.length) {\n atomicDeco.add(\n mark.from,\n mark.from + len,\n Decoration.replace({\n widget: new TextWidget(num, theme.heading(level)),\n }),\n );\n }\n }\n }\n\n return false;\n }\n\n //\n // Lists.\n // [BulletList | OrderedList] > (ListItem > ListMark) > (Task > TaskMarker)?\n //\n\n case 'BulletList':\n case 'OrderedList': {\n enterList(node);\n break;\n }\n\n case 'ListItem': {\n const line = state.doc.lineAt(node.from);\n\n // Set indentation.\n const list = getCurrentListLevel();\n const width = list.type === 'OrderedList' ? orderedListIndentationWidth : bulletListIndentationWidth;\n const offset = (options?.listPaddingLeft ?? 0) + ((list.level ?? 0) + 1) * width;\n if (node.from === line.to - 1) {\n // Abort if only the hyphen is typed.\n return false;\n }\n\n // Add line decoration for the continuation indent.\n // TODO(burdon): Bug if indentation is more than one indentation unit (e.g., 4 spaces) from the previous line.\n deco.add(\n line.from,\n line.from,\n Decoration.line({\n class: 'cm-list-item',\n attributes: {\n style: `padding-left: ${offset}px; text-indent: -${width}px;`,\n },\n }),\n );\n\n break;\n }\n\n case 'ListMark': {\n const list = getCurrentListLevel();\n\n // Look-ahead for task marker.\n // NOTE: Requires space to exist (otherwise the text is parsed as the start of a link).\n const next = tree.resolve(node.to + 1, 1);\n if (next?.name === 'TaskMarker') {\n break;\n }\n\n // TODO(burdon): Option to make hierarchical; or a), i), etc.\n const label = list.type === 'OrderedList' ? `${++list.number}.` : Unicode.bulletSmall;\n const line = state.doc.lineAt(node.from);\n const to = state.doc.sliceString(node.to, node.to + 1) === ' ' ? node.to + 1 : node.to;\n atomicDeco.add(\n line.from,\n to,\n Decoration.replace({\n widget: new TextWidget(\n label,\n list.type === 'OrderedList' ? 'cm-list-mark cm-list-mark-ordered' : 'cm-list-mark cm-list-mark-bullet',\n ),\n }),\n );\n break;\n }\n\n case 'TaskMarker': {\n const checked = state.doc.sliceString(node.from + 1, node.to - 1) === 'x';\n // Check if the next character is a space and if so, include it in the replacement.\n const line = state.doc.lineAt(node.from);\n const to = state.doc.sliceString(node.to, node.to + 1) === ' ' ? node.to + 1 : node.to;\n atomicDeco.add(line.from, to, checked ? checkedTask : uncheckedTask);\n break;\n }\n\n //\n // Blockquote > QuoteMark > Paragraph\n //\n\n case 'Blockquote': {\n const editing = editingRange(state, node, focus);\n const quoteMark = node.node.getChild('QuoteMark');\n const paragraph = node.node.getChild('Paragraph');\n if (!editing && quoteMark && paragraph) {\n atomicDeco.add(quoteMark.from, paragraph.from, hide);\n }\n\n for (const block of view.viewportLineBlocks) {\n if (block.to < node.from) {\n continue;\n }\n if (block.from > node.to) {\n break;\n }\n\n deco.add(block.from, block.from, blockQuote);\n }\n\n break;\n }\n\n //\n // CommentBlock\n //\n\n case 'CommentBlock': {\n const editing = editingRange(state, node, focus);\n for (const block of view.viewportLineBlocks) {\n if (block.to < node.from) {\n continue;\n }\n if (block.from > node.to) {\n break;\n }\n\n const isFirst = block.from <= node.from;\n const isLast = block.to >= node.to && /^(\\s>)*-->$/.test(state.doc.sliceString(block.from, block.to));\n\n deco.add(\n block.from,\n block.from,\n isFirst ? commentBlockLineFirst : isLast ? commentBlockLineLast : commentBlockLine,\n );\n\n if (!editing && (isFirst || isLast)) {\n atomicDeco.add(block.from, block.to, hide);\n }\n }\n break;\n }\n\n //\n // FencedCode > CodeMark > [CodeInfo] > CodeText > CodeMark\n //\n\n case 'FencedCode': {\n for (const block of view.viewportLineBlocks) {\n if (block.to < node.from) {\n continue;\n }\n if (block.from > node.to) {\n break;\n }\n\n const first = block.from <= node.from;\n const last = block.to >= node.to && /```$/.test(state.doc.sliceString(block.from, block.to));\n deco.add(block.from, block.from, first ? fencedCodeLineFirst : last ? fencedCodeLineLast : fencedCodeLine);\n\n const editing = editingRange(state, node, focus);\n if (!editing && (first || last)) {\n atomicDeco.add(block.from, block.to, hide);\n }\n }\n return false;\n }\n\n //\n // Link > [LinkMark, URL]\n //\n\n case 'Link': {\n const marks = node.node.getChildren('LinkMark');\n const urlNode = node.node.getChild('URL');\n const editing = editingRange(state, node, focus);\n if (urlNode && marks.length >= 2) {\n const url = state.sliceDoc(urlNode.from, urlNode.to);\n if (!editing) {\n atomicDeco.add(node.from, marks[0].to, hide);\n }\n\n deco.add(\n marks[0].to,\n marks[1].from,\n Decoration.mark({\n tagName: 'a',\n attributes: {\n class: 'cm-link',\n href: url,\n rel: 'noreferrer',\n target: '_blank',\n },\n }),\n );\n if (!editing) {\n atomicDeco.add(\n marks[1].from,\n node.to,\n options.renderLinkButton\n ? Decoration.replace({ widget: new LinkButton(url, options.renderLinkButton) })\n : hide,\n );\n }\n }\n break;\n }\n\n //\n // HR\n //\n\n case 'HorizontalRule': {\n if (!editingRange(state, node, focus)) {\n deco.add(node.from, node.to, horizontalRule);\n }\n break;\n }\n\n default: {\n if (autoHideTags.has(node.name)) {\n if (!editingRange(state, node.node.parent!, focus)) {\n atomicDeco.add(node.from, node.to, hide);\n }\n }\n }\n }\n };\n\n const leaveNode = (node: SyntaxNodeRef) => {\n switch (node.name) {\n case 'BulletList':\n case 'OrderedList': {\n leaveList();\n break;\n }\n }\n };\n\n const tree = syntaxTree(state);\n if (options.numberedHeadings?.from === undefined) {\n for (const { from, to } of view.visibleRanges) {\n tree.iterate({\n from,\n to,\n enter: wrapWithCatch(enterNode),\n leave: wrapWithCatch(leaveNode),\n });\n }\n } else {\n // NOTE: If line numbering then we must iterate from the start of document.\n tree.iterate({\n enter: wrapWithCatch(enterNode),\n leave: wrapWithCatch(leaveNode),\n });\n }\n\n return {\n deco: deco.finish(),\n atomicDeco: atomicDeco.finish(),\n };\n};\n\nconst forceUpdate = StateEffect.define<null>();\n\nexport interface DecorateOptions {\n /**\n * Prevents triggering decorations as the cursor moves through the document.\n */\n selectionChangeDelay?: number;\n numberedHeadings?: { from: number; to?: number };\n renderLinkButton?: RenderCallback<{ url: string }>;\n // TODO(burdon): Additional padding for each line.\n listPaddingLeft?: number;\n}\n\nexport const decorateMarkdown = (options: DecorateOptions = {}) => {\n return [\n ViewPlugin.fromClass(\n class {\n deco: DecorationSet;\n atomicDeco: DecorationSet;\n pendingUpdate?: NodeJS.Timeout;\n\n constructor(view: EditorView) {\n ({ deco: this.deco, atomicDeco: this.atomicDeco } = buildDecorations(view, options, view.hasFocus));\n }\n\n update(update: ViewUpdate) {\n if (\n update.docChanged ||\n update.viewportChanged ||\n update.focusChanged ||\n update.transactions.some((tr) => tr.effects.some((effect) => effect.is(forceUpdate))) ||\n (update.selectionSet && !options.selectionChangeDelay)\n ) {\n ({ deco: this.deco, atomicDeco: this.atomicDeco } = buildDecorations(\n update.view,\n options,\n update.view.hasFocus,\n ));\n\n this.clearUpdate();\n } else if (update.selectionSet) {\n this.scheduleUpdate(update.view);\n }\n }\n\n // Defer update in case moving through the document.\n scheduleUpdate(view: EditorView) {\n this.clearUpdate();\n this.pendingUpdate = setTimeout(() => {\n view.dispatch({ effects: forceUpdate.of(null) });\n }, options.selectionChangeDelay);\n }\n\n clearUpdate() {\n if (this.pendingUpdate) {\n clearTimeout(this.pendingUpdate);\n this.pendingUpdate = undefined;\n }\n }\n\n destroy() {\n this.clearUpdate();\n }\n },\n {\n provide: (plugin) => [\n EditorView.atomicRanges.of((view) => view.plugin(plugin)?.atomicDeco ?? Decoration.none),\n EditorView.decorations.of((view) => view.plugin(plugin)?.atomicDeco ?? Decoration.none),\n EditorView.decorations.of((view) => view.plugin(plugin)?.deco ?? Decoration.none),\n ],\n },\n ),\n image(),\n table(),\n adjustChanges(),\n formattingStyles,\n ];\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { syntaxTree } from '@codemirror/language';\nimport { type ChangeSpec, Transaction } from '@codemirror/state';\nimport { ViewPlugin, type ViewUpdate, type PluginValue } from '@codemirror/view';\n\n/**\n * Monitors and augments changes.\n */\n// TODO(burdon): Tests.\nexport const adjustChanges = () => {\n return ViewPlugin.fromClass(\n class implements PluginValue {\n update(update: ViewUpdate) {\n const tree = syntaxTree(update.state);\n const adjustments: ChangeSpec[] = [];\n\n for (const tr of update.transactions) {\n const event = tr.annotation(Transaction.userEvent);\n switch (event) {\n //\n // Enter\n //\n case 'input': {\n const changes = tr.changes;\n if (changes.empty) {\n break;\n }\n\n changes.iterChanges((fromA) => {\n const node = tree.resolveInner(fromA, 1);\n if (node?.name === 'BulletList') {\n // Add space to previous line if an empty list item (otherwise it is not interpreted as a Task).\n const { text } = update.state.doc.lineAt(fromA);\n if (text.endsWith(']')) {\n adjustments.push({ from: fromA, to: fromA, insert: ' ' });\n }\n }\n });\n\n break;\n }\n\n //\n // Paste\n //\n case 'input.paste': {\n const changes = tr.changes;\n if (changes.empty) {\n break;\n }\n\n changes.iterChanges((fromA, toA, fromB, toB, text) => {\n // Check for URL.\n const url = getValidUrl(update.view.state.sliceDoc(fromB, toB));\n if (url) {\n // Check if pasting inside existing link.\n const node = tree.resolveInner(fromA, -1);\n const invalidPositions = new Set(['Code', 'CodeText', 'FencedCode', 'Link', 'LinkMark', 'URL']);\n if (!invalidPositions.has(node?.name)) {\n const replacedText = tr.startState.sliceDoc(fromA, toA);\n adjustments.push({ from: fromA, to: toB, insert: createLink(url, replacedText) });\n }\n } else {\n const node = tree.resolveInner(fromA, 1);\n switch (node?.name) {\n case 'Task': {\n // Remove task marker if pasting into task list.\n const str = text.toString();\n const match = str.match(/\\s*- \\[[ xX]\\]\\s*(.+)/);\n if (match) {\n const [, replacement] = match;\n adjustments.push({ from: fromA, to: toB, insert: replacement });\n }\n break;\n }\n }\n }\n });\n\n break;\n }\n }\n }\n\n // TODO(burdon): Is this the right way to augment changes? Alt: EditorState.transactionFilter\n if (adjustments.length) {\n setTimeout(() => {\n update.view.dispatch(\n update.view.state.update({\n changes: adjustments,\n }),\n );\n });\n }\n }\n },\n );\n};\n\n//\n// Links\n//\n\nexport const createLink = (url: URL, label: string): string => {\n // Check if image.\n // Example: https://dxos.network/dxos-logotype-blue.png\n const { host, pathname } = url;\n const [, extension] = pathname.split('.');\n const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp'];\n if (imageExtensions.includes(extension)) {\n return ``;\n }\n\n if (!label) {\n label = createLinkLabel(url);\n }\n\n return `[${label}](${url})`;\n};\n\nexport const createLinkLabel = (url: URL): string => {\n let { protocol, host, pathname } = url;\n if (protocol === 'http:' || protocol === 'https:') {\n protocol = '';\n }\n\n // NOTE(Zan): Consult: https://github.com/dxos/dxos/issues/7331 before changing this.\n // Remove 'www.' if at the beginning of the URL\n host = host.replace(/^www\\./, '');\n\n return [protocol, host].filter(Boolean).join('//') + (pathname !== '/' ? pathname : '');\n};\n\nconst getValidUrl = (str: string): URL | undefined => {\n const validProtocols = ['http:', 'https:', 'mailto:', 'tel:'];\n try {\n const url = new URL(str);\n if (!validProtocols.includes(url.protocol)) {\n return undefined;\n }\n\n return url;\n } catch (_err) {\n return undefined;\n }\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { syntaxTree } from '@codemirror/language';\nimport { type EditorState, type Extension, type Range, StateField, type Transaction } from '@codemirror/state';\nimport { Decoration, type DecorationSet, EditorView, WidgetType } from '@codemirror/view';\n\nimport { focusField } from '../focus';\n\nexport type ImageOptions = {};\n\n/**\n * Create image decorations.\n */\nexport const image = (_options: ImageOptions = {}): Extension => {\n return [\n StateField.define<DecorationSet>({\n create: (state) => {\n // Process all images.\n return Decoration.set(buildDecorations(0, state.doc.length, state));\n },\n update: (value: DecorationSet, tr: Transaction) => {\n if (!tr.docChanged && !tr.selection) {\n return value;\n }\n\n // Find range of changes and cursor changes.\n const cursor = tr.state.selection.main.head;\n const oldCursor = tr.changes.mapPos(tr.startState.selection.main.head);\n let from = Math.min(cursor, oldCursor);\n let to = Math.max(cursor, oldCursor);\n tr.changes.iterChangedRanges((fromA, toA, fromB, toB) => {\n from = Math.min(from, fromB);\n to = Math.max(to, toB);\n });\n\n // Expand to cover lines.\n from = tr.state.doc.lineAt(from).from;\n to = tr.state.doc.lineAt(to).to;\n\n return value.map(tr.changes).update({\n filterFrom: from,\n filterTo: to,\n filter: () => false,\n add: buildDecorations(from, to, tr.state),\n });\n },\n provide: (field) => EditorView.decorations.from(field),\n }),\n ];\n};\n\nconst buildDecorations = (from: number, to: number, state: EditorState) => {\n const decorations: Range<Decoration>[] = [];\n const cursor = state.selection.main.head;\n syntaxTree(state).iterate({\n enter: (node) => {\n if (node.name === 'Image') {\n const urlNode = node.node.getChild('URL');\n if (urlNode) {\n const hide = state.readOnly || cursor < node.from || cursor > node.to || !state.field(focusField);\n\n const url = state.sliceDoc(urlNode.from, urlNode.to);\n // Some plugins might be using custom URLs; avoid attempts to render those URLs.\n if (url.match(/^https?:\\/\\//) === null && url.match(/^file?:\\/\\//) === null) {\n return;\n }\n\n preloadImage(url);\n decorations.push(\n Decoration.replace({\n block: true, // Prevent cursor from entering.\n widget: new ImageWidget(url),\n }).range(hide ? node.from : node.to, node.to),\n );\n }\n }\n },\n from,\n to,\n });\n\n return decorations;\n};\n\nconst preloaded = new Set<string>();\n\nconst preloadImage = (url: string) => {\n if (!preloaded.has(url)) {\n const img = document.createElement('img');\n img.src = url;\n preloaded.add(url);\n }\n};\n\nclass ImageWidget extends WidgetType {\n constructor(readonly _url: string) {\n super();\n }\n\n override eq(other: this): boolean {\n return this._url === other._url;\n }\n\n override toDOM(view: EditorView): HTMLImageElement {\n const img = document.createElement('img');\n img.setAttribute('src', this._url);\n img.setAttribute('class', 'cm-image');\n // If focused, hide image until successfully loaded to avoid flickering effects.\n if (view.state.field(focusField)) {\n img.onload = () => img.classList.add('cm-loaded-image');\n } else {\n img.classList.add('cm-loaded-image');\n }\n\n return img;\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { EditorView } from '@codemirror/view';\n\nimport { fontMono } from '../../styles';\n\nexport const bulletListIndentationWidth = 24;\nexport const orderedListIndentationWidth = 36; // TODO(burdon): Make variable length based on number of digits.\n\nexport const formattingStyles = EditorView.theme({\n /**\n * Horizontal rule.\n */\n '& .cm-hr': {\n display: 'inline-block',\n width: '100%',\n height: '0',\n verticalAlign: 'middle',\n borderTop: '1px solid var(--dx-cmSeparator)',\n opacity: 0.5,\n },\n\n /**\n * Lists.\n */\n '& .cm-list-item': {},\n '& .cm-list-mark': {\n display: 'inline-block',\n textAlign: 'right',\n paddingRight: '0.5em',\n fontVariant: 'tabular-nums',\n },\n '& .cm-list-mark-bullet': {\n width: `${bulletListIndentationWidth}px`,\n },\n '& .cm-list-mark-ordered': {\n width: `${orderedListIndentationWidth}px`,\n },\n\n /**\n * Blockquote.\n */\n '& .cm-blockquote': {\n background: 'var(--dx-cmCodeblock)',\n borderLeft: '2px solid var(--dx-cmSeparator)',\n paddingLeft: '1rem',\n margin: '0',\n },\n\n /**\n * Code and codeblocks.\n */\n '& .cm-code': {\n fontFamily: fontMono,\n },\n '& .cm-codeblock-line': {\n background: 'var(--dx-cmCodeblock)',\n paddingInline: '1rem !important',\n },\n '& .cm-codeblock-start': {\n borderTopLeftRadius: '.25rem',\n borderTopRightRadius: '.25rem',\n },\n '& .cm-codeblock-end': {\n borderBottomLeftRadius: '.25rem',\n borderBottomRightRadius: '.25rem',\n },\n\n /**\n * Task list.\n */\n '& .cm-task': {\n display: 'inline-flex',\n width: `${bulletListIndentationWidth}px`,\n height: '20px',\n },\n '& .cm-task-checkbox': {\n display: 'grid',\n margin: '0',\n transform: 'translateY(2px)',\n },\n\n /**\n * Table.\n */\n '.cm-table *': {\n fontFamily: fontMono,\n textDecoration: 'none !important',\n },\n '.cm-table-head': {\n padding: '2px 16px 2px 0px',\n textAlign: 'left',\n borderBottom: '1px solid var(--dx-cmSeparator)',\n color: 'var(--dx-subdued)',\n },\n '.cm-table-cell': {\n padding: '2px 16px 2px 0px',\n },\n\n /**\n * Image.\n */\n '.cm-image': {\n display: 'block',\n height: '0',\n },\n '.cm-image.cm-loaded-image': {\n height: 'auto',\n borderTop: '0.5rem solid transparent',\n borderBottom: '0.5rem solid transparent',\n },\n '.cm-image-with-loader': {\n display: 'block',\n opacity: '0',\n transitionDuration: '350ms',\n transitionProperty: 'opacity',\n },\n '.cm-image-with-loader.cm-loaded-image': {\n opacity: '1',\n },\n '.cm-image-wrapper': {\n 'grid-template-columns': '1fr',\n display: 'grid',\n margin: '0.5rem 0',\n overflow: 'hidden',\n transitionDuration: '350ms',\n transitionProperty: 'height',\n '& > *': {\n 'grid-row-start': 1,\n 'grid-column-start': 1,\n },\n },\n});\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { syntaxTree } from '@codemirror/language';\nimport {\n type EditorState,\n type Extension,\n type RangeSet,\n RangeSetBuilder,\n StateField,\n type Transaction,\n} from '@codemirror/state';\nimport { Decoration, EditorView, WidgetType } from '@codemirror/view';\n\n// TODO(burdon): Snippet to create basic table.\n// https://codemirror.net/docs/ref/#autocomplete.snippet\n// TODO(burdon): Advanced formatting (left/right/center).\n// TODO(burdon): Editor to auto balance columns.\n\nexport type TableOptions = {};\n\n/**\n * GFM tables.\n * https://github.github.com/gfm/#tables-extension\n */\nexport const table = (options: TableOptions = {}): Extension => {\n return StateField.define<RangeSet<Decoration>>({\n create: (state) => update(state, options),\n update: (_: RangeSet<Decoration>, tr: Transaction) => update(tr.state, options),\n provide: (field) => EditorView.decorations.from(field),\n });\n};\n\ntype Table = {\n from: number;\n to: number;\n header?: string[];\n rows?: string[][];\n};\n\nconst update = (state: EditorState, _options: TableOptions) => {\n const builder = new RangeSetBuilder<Decoration>();\n const cursor = state.selection.main.head;\n\n const tables: Table[] = [];\n const getTable = () => tables[tables.length - 1];\n const getRow = () => {\n const table = getTable();\n return table.rows?.[table.rows.length - 1];\n };\n\n // Parse table.\n syntaxTree(state).iterate({\n enter: (node) => {\n // Check if cursor is inside text.\n switch (node.name) {\n case 'Table': {\n tables.push({ from: node.from, to: node.to });\n break;\n }\n case 'TableHeader': {\n getTable().header = [];\n break;\n }\n case 'TableRow': {\n (getTable().rows ??= []).push([]);\n break;\n }\n case 'TableCell': {\n const row = getRow();\n if (row) {\n row.push(state.sliceDoc(node.from, node.to));\n } else {\n getTable().header?.push(state.sliceDoc(node.from, node.to));\n }\n break;\n }\n }\n },\n });\n\n tables.forEach((table) => {\n const replace = state.readOnly || cursor < table.from || cursor > table.to;\n if (replace) {\n builder.add(\n table.from,\n table.to,\n Decoration.replace({\n block: true,\n widget: new TableWidget(table),\n }),\n );\n } else {\n // Add class for styling.\n // TODO(burdon): Apply to each line?\n builder.add(table.from, table.to, Decoration.mark({ class: 'cm-table' }));\n }\n });\n\n return builder.finish();\n};\n\nclass TableWidget extends WidgetType {\n constructor(readonly _table: Table) {\n super();\n }\n\n override eq(other: this): boolean {\n return (\n this._table.header?.join() === other._table.header?.join() &&\n this._table.rows?.join() === other._table.rows?.join()\n );\n }\n\n override toDOM(view: EditorView): HTMLDivElement {\n const div = document.createElement('div');\n const table = div.appendChild(document.createElement('table'));\n\n const header = table.appendChild(document.createElement('thead'));\n const tr = header.appendChild(document.createElement('tr'));\n this._table.header?.forEach((cell) => {\n const th = document.createElement('th');\n th.setAttribute('class', 'cm-table-head');\n tr.appendChild(th).textContent = cell;\n });\n\n const body = table.appendChild(document.createElement('tbody'));\n this._table.rows?.forEach((row) => {\n const tr = body.appendChild(document.createElement('tr'));\n row.forEach((cell) => {\n const td = document.createElement('td');\n td.setAttribute('class', 'cm-table-cell');\n tr.appendChild(td).textContent = cell;\n });\n });\n\n return div;\n }\n\n override ignoreEvent(e: Event): boolean {\n return !/^mouse/.test(e.type);\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n// Copyright CodeMirror\n//\n\nimport { syntaxTree } from '@codemirror/language';\nimport { hoverTooltip } from '@codemirror/view';\nimport { type SyntaxNode } from '@lezer/common';\n\nimport { tooltipContent } from '@dxos/react-ui-theme';\n\nimport { type RenderCallback } from '../../types';\n\nexport const linkTooltip = (renderTooltip: RenderCallback<{ url: string }>) => {\n return hoverTooltip(\n (view, pos, side) => {\n const syntax = syntaxTree(view.state).resolveInner(pos, side);\n let link = null;\n for (let i = 0, node: SyntaxNode | null = syntax; !link && node && i < 5; node = node.parent, i++) {\n link = node.name === 'Link' ? node : null;\n }\n\n const url = link && link.getChild('URL');\n if (!url || !link) {\n return null;\n }\n\n const urlText = view.state.sliceDoc(url.from, url.to);\n return {\n pos: link.from,\n end: link.to,\n // NOTE: Forcing above causes the tooltip to flicker.\n // above: true,\n create: () => {\n const el = document.createElement('div');\n el.className = tooltipContent({});\n renderTooltip(el, { url: urlText }, view);\n return { dom: el, offset: { x: 0, y: 4 } };\n },\n };\n },\n {\n // NOTE: 0 = default of 300ms.\n hoverTime: 1,\n },\n );\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { autocompletion, type CompletionContext, type CompletionResult } from '@codemirror/autocomplete';\nimport type { Extension } from '@codemirror/state';\n\nimport { log } from '@dxos/log';\n\nexport type MentionOptions = {\n debug?: boolean;\n onSearch: (text: string) => string[];\n};\n\n// TODO(burdon): Can only have a single autocompletion. Merge configuration with autocomplete.\nexport const mention = ({ debug, onSearch }: MentionOptions): Extension => {\n return autocompletion({\n // TODO(burdon): Not working.\n activateOnTyping: true,\n // activateOnTypingDelay: 100,\n // selectOnOpen: true,\n closeOnBlur: !debug,\n // defaultKeymap: false,\n icons: false,\n override: [\n (context: CompletionContext): CompletionResult | null => {\n log.info('completion context', { context });\n\n const match = context.matchBefore(/@(\\w+)?/);\n if (!match || (match.from === match.to && !context.explicit)) {\n return null;\n }\n\n return {\n from: match.from,\n options: onSearch(match.text.slice(1).toLowerCase()).map((value) => ({ label: `@${value}` })),\n };\n },\n ],\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Extension } from '@codemirror/state';\nimport { keymap } from '@codemirror/view';\nimport { vim } from '@replit/codemirror-vim';\nimport { vscodeKeymap } from '@replit/codemirror-vscode-keymap';\nimport { Schema } from 'effect';\n\nimport { singleValueFacet } from '../util';\n\nexport const EditorViewModes = ['preview', 'readonly', 'source'] as const;\nexport const EditorViewMode = Schema.Union(...EditorViewModes.map((mode) => Schema.Literal(mode)));\nexport type EditorViewMode = Schema.Schema.Type<typeof EditorViewMode>;\n\nexport const EditorInputModes = ['default', 'vim', 'vscode'] as const;\nexport const EditorInputMode = Schema.Union(...EditorInputModes.map((mode) => Schema.Literal(mode)));\nexport type EditorInputMode = Schema.Schema.Type<typeof EditorInputMode>;\n\nexport type EditorInputConfig = {\n type?: string;\n noTabster?: boolean;\n};\n\nexport const editorInputMode = singleValueFacet<EditorInputConfig>({});\n\nexport const InputModeExtensions: { [mode: string]: Extension } = {\n default: [],\n vscode: [\n // https://github.com/replit/codemirror-vscode-keymap\n editorInputMode.of({ type: 'vscode' }),\n keymap.of(vscodeKeymap),\n ],\n vim: [\n // https://github.com/replit/codemirror-vim\n vim(),\n editorInputMode.of({ type: 'vim', noTabster: true }),\n keymap.of([\n {\n key: 'Alt-Escape',\n run: (view) => {\n // Focus container for tab navigation.\n view.dom.parentElement?.focus();\n return true;\n },\n },\n ]),\n ],\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { indentMore } from '@codemirror/commands';\nimport { getIndentUnit } from '@codemirror/language';\nimport { type ChangeSpec, EditorSelection, type Extension } from '@codemirror/state';\nimport { type Command, type EditorView, keymap } from '@codemirror/view';\n\nimport { getSelection, selectAll, selectDown, selectNone, selectUp } from './selection';\nimport { getRange, treeFacet } from './tree';\n\n//\n// Indentation comnmands.\n//\n\nexport const indentItemMore: Command = (view: EditorView) => {\n const pos = getSelection(view.state).from;\n const tree = view.state.facet(treeFacet);\n const current = tree.find(pos);\n if (current) {\n const previous = tree.prev(current);\n if (previous && current.level <= previous.level) {\n // TODO(burdon): Indent descendants?\n indentMore(view);\n }\n }\n\n return true;\n};\n\nexport const indentItemLess: Command = (view: EditorView) => {\n const pos = getSelection(view.state).from;\n const tree = view.state.facet(treeFacet);\n const current = tree.find(pos);\n if (current) {\n if (current.level > 0) {\n // Unindent current line and all descendants.\n // NOTE: The markdown extension doesn't provide an indentation service.\n const indentUnit = getIndentUnit(view.state);\n const changes: ChangeSpec[] = [];\n tree.traverse(current, (item) => {\n const line = view.state.doc.lineAt(item.lineRange.from);\n changes.push({ from: line.from, to: line.from + indentUnit });\n });\n\n if (changes.length > 0) {\n view.dispatch({ changes });\n }\n }\n }\n\n return true;\n};\n\n//\n// Moving commands.\n//\n\nexport const moveItemDown: Command = (view: EditorView) => {\n const pos = getSelection(view.state)?.from;\n const tree = view.state.facet(treeFacet);\n const current = tree.find(pos);\n if (current && current.nextSibling) {\n const next = current.nextSibling;\n const currentContent = view.state.doc.sliceString(...getRange(tree, current));\n const nextContent = view.state.doc.sliceString(...getRange(tree, next));\n const changes: ChangeSpec[] = [\n {\n from: current.lineRange.from,\n to: current.lineRange.from + currentContent.length,\n insert: nextContent,\n },\n {\n from: next.lineRange.from,\n to: next.lineRange.from + nextContent.length,\n insert: currentContent,\n },\n ];\n\n view.dispatch({\n changes,\n selection: EditorSelection.cursor(pos + nextContent.length + 1),\n scrollIntoView: true,\n });\n }\n\n return true;\n};\n\nexport const moveItemUp: Command = (view: EditorView) => {\n const pos = getSelection(view.state)?.from;\n const tree = view.state.facet(treeFacet);\n const current = tree.find(pos);\n if (current && current.prevSibling) {\n const prev = current.prevSibling;\n const currentContent = view.state.doc.sliceString(...getRange(tree, current));\n const prevContent = view.state.doc.sliceString(...getRange(tree, prev));\n const changes: ChangeSpec[] = [\n {\n from: prev.lineRange.from,\n to: prev.lineRange.from + prevContent.length,\n insert: currentContent,\n },\n {\n from: current.lineRange.from,\n to: current.lineRange.from + currentContent.length,\n insert: prevContent,\n },\n ];\n\n view.dispatch({\n changes,\n selection: EditorSelection.cursor(pos - prevContent.length - 1),\n scrollIntoView: true,\n });\n }\n\n return true;\n};\n\n//\n// Misc commands.\n//\n\nexport const deleteItem: Command = (view: EditorView) => {\n const tree = view.state.facet(treeFacet);\n const pos = getSelection(view.state).from;\n const current = tree.find(pos);\n if (current) {\n view.dispatch({\n selection: EditorSelection.cursor(current.lineRange.from),\n changes: [\n {\n from: current.lineRange.from,\n to: Math.min(current.lineRange.to + 1, view.state.doc.length),\n },\n ],\n });\n }\n\n return true;\n};\n\nexport const toggleTask: Command = (view: EditorView) => {\n const tree = view.state.facet(treeFacet);\n const pos = getSelection(view.state)?.from;\n const current = tree.find(pos);\n if (current) {\n const type = current.type === 'task' ? 'bullet' : 'task';\n const indent = ' '.repeat(getIndentUnit(view.state) * current.level);\n view.dispatch({\n changes: [\n {\n from: current.lineRange.from,\n to: current.contentRange.from,\n insert: indent + (type === 'task' ? '- [ ] ' : '- '),\n },\n ],\n });\n }\n\n return true;\n};\n\nexport const commands = (): Extension =>\n keymap.of([\n //\n // Indentation.\n //\n {\n key: 'Tab',\n preventDefault: true,\n run: indentItemMore,\n shift: indentItemLess,\n },\n\n //\n // Continuation.\n //\n {\n key: 'Enter',\n shift: (view) => {\n const pos = getSelection(view.state).from;\n const insert = '\\n '; // TODO(burdon): Fix parsing.\n view.dispatch({\n changes: [{ from: pos, to: pos, insert }],\n selection: EditorSelection.cursor(pos + insert.length),\n });\n return true;\n },\n },\n\n //\n // Navigation.\n //\n {\n key: 'ArrowDown',\n // Jump to next item (default moves to end of currentline).\n run: (view) => {\n const tree = view.state.facet(treeFacet);\n const item = tree.find(getSelection(view.state).from);\n if (\n item &&\n view.state.doc.lineAt(item.lineRange.to).number - view.state.doc.lineAt(item.lineRange.from).number === 0\n ) {\n const next = tree.next(item);\n if (next) {\n view.dispatch({ selection: EditorSelection.cursor(next.contentRange.from) });\n return true;\n }\n }\n\n return false;\n },\n },\n\n //\n // Line selection.\n // TODO(burdon): Shortcut to select current item?\n //\n {\n key: 'Mod-a',\n preventDefault: true,\n run: selectAll,\n },\n {\n key: 'Escape',\n preventDefault: true,\n run: selectNone,\n },\n {\n key: 'ArrowUp',\n shift: selectUp,\n },\n {\n key: 'ArrowDown',\n shift: selectDown,\n },\n\n //\n // Move.\n //\n {\n key: 'Alt-ArrowDown',\n preventDefault: true,\n run: moveItemDown,\n },\n {\n key: 'Alt-ArrowUp',\n preventDefault: true,\n run: moveItemUp,\n },\n //\n // Delete.\n //\n {\n key: 'Mod-Backspace',\n preventDefault: true,\n run: deleteItem,\n },\n //\n // Misc.\n //\n {\n key: 'Alt-t',\n preventDefault: true,\n run: toggleTask,\n },\n ]);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Compartment, type EditorState, Facet, type SelectionRange } from '@codemirror/state';\nimport { type EditorView, type Command } from '@codemirror/view';\n\nimport { treeFacet } from './tree';\n\nexport type Selection = number[];\n\nexport const getSelection = (state: EditorState): SelectionRange => state.selection.main;\n\nexport const selectionEquals = (a: number[], b: number[]) => a.length === b.length && a.every((i) => b.includes(i));\n\nexport const selectionFacet = Facet.define<Selection, Selection>({\n combine: (values) => values[0],\n});\n\nexport const selectionCompartment = new Compartment();\n\nexport const selectNone: Command = (view: EditorView) => {\n view.dispatch({\n effects: selectionCompartment.reconfigure(selectionFacet.of([])),\n });\n\n return true;\n};\n\nexport const selectAll: Command = (view: EditorView) => {\n const tree = view.state.facet(treeFacet);\n const selection = view.state.facet(selectionFacet);\n const items: Selection = [];\n tree.traverse((item) => items.push(item.index));\n view.dispatch({\n effects: selectionCompartment.reconfigure(selectionFacet.of(selectionEquals(selection, items) ? [] : items)),\n });\n\n return true;\n};\n\n// TODO(burdon): Implement.\nexport const selectUp: Command = (view: EditorView) => {\n return true;\n};\n\n// TODO(burdon): Implement.\nexport const selectDown: Command = (view: EditorView) => {\n return true;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { syntaxTree } from '@codemirror/language';\nimport { StateField, type Transaction, type Extension, type EditorState } from '@codemirror/state';\nimport { Facet } from '@codemirror/state';\nimport { type SyntaxNode } from '@lezer/common';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { type Range } from '../../types';\n\n/**\n * Represents a single item in the tree.\n */\nexport interface Item {\n type: 'root' | 'bullet' | 'task' | 'unknown';\n index: number;\n level: number;\n node: SyntaxNode;\n parent?: Item;\n nextSibling?: Item;\n prevSibling?: Item;\n children: Item[];\n /**\n * Actual range.\n * Starts at the start of the line containing the item and ends at the end of the line before the\n * first child or next sibling.\n */\n lineRange: Range;\n /**\n * Range of the editable content.\n * This doesn't include the list or task marker or indentation.\n */\n contentRange: Range;\n}\n\nexport const itemToJSON = ({ type, index, level, lineRange, contentRange, children }: Item): any => {\n return { type, index, level, lineRange, contentRange, children: children.map(itemToJSON) };\n};\n\n/**\n * Tree assumes the entire document is a single contiguous well-formed hierarchy of markdown LiteItem nodes.\n */\nexport class Tree implements Item {\n type: Item['type'] = 'root';\n index = -1;\n level = -1;\n node: Item['node'];\n lineRange: Item['lineRange'];\n contentRange: Item['contentRange'];\n children: Item['children'] = [];\n\n constructor(node: SyntaxNode) {\n this.node = node;\n this.lineRange = { from: node.from, to: node.to };\n this.contentRange = this.lineRange;\n }\n\n toJSON() {\n return itemToJSON(this);\n }\n\n get root(): Item {\n return this;\n }\n\n traverse<T = any>(cb: (item: Item, level: number) => T | void): T | undefined;\n traverse<T = any>(item: Item, cb: (item: Item, level: number) => T | void): T | undefined;\n traverse<T = any>(\n itemOrCb: Item | ((item: Item, level: number) => T | undefined | void),\n maybeCb?: (item: Item, level: number) => T | undefined | void,\n ): T | undefined {\n if (typeof itemOrCb === 'function') {\n return traverse<T>(this, itemOrCb);\n } else {\n return traverse<T>(itemOrCb, maybeCb!);\n }\n }\n\n /**\n * Return the closest item.\n */\n find(pos: number): Item | undefined {\n return this.traverse<Item>((item) => (item.lineRange.from <= pos && item.lineRange.to >= pos ? item : undefined));\n }\n\n /**\n * Return the first child, next sibling, or parent's next sibling.\n */\n next(item: Item, enter = true): Item | undefined {\n if (enter && item.children.length > 0) {\n return item.children[0];\n }\n\n if (item.nextSibling) {\n return item.nextSibling;\n }\n\n if (item.parent) {\n return this.next(item.parent, false);\n }\n\n return undefined;\n }\n\n /**\n * Return the previous sibling, or parent.\n */\n prev(item: Item): Item | undefined {\n if (item.prevSibling) {\n return this.lastDescendant(item.prevSibling);\n }\n\n return item.parent?.type === 'root' ? undefined : item.parent;\n }\n\n /**\n * Return the last descendant of the item, or the item itself if it has no children.\n */\n lastDescendant(item: Item): Item {\n return item.children.length > 0 ? this.lastDescendant(item.children.at(-1)!) : item;\n }\n}\n\nexport const getRange = (tree: Tree, item: Item): [number, number] => {\n const lastDescendant = tree.lastDescendant(item);\n return [item.lineRange.from, lastDescendant.lineRange.to];\n};\n\n/**\n * Traverse the tree, calling the callback for each item.\n * If the callback returns a value, the traversal is stopped and the value is returned.\n */\nexport const traverse = <T = any>(root: Item, cb: (item: Item, level: number) => T | void): T | undefined => {\n const t = (item: Item, level: number): T | undefined => {\n if (item.type !== 'root') {\n const value = cb(item, level);\n if (value != null) {\n return value;\n }\n }\n\n for (const child of item.children) {\n const value = t(child, level + 1);\n if (value != null) {\n return value;\n }\n }\n\n return undefined;\n };\n\n return t(root, root.type === 'root' ? -1 : 0);\n};\n\nexport const getListItemContent = (state: EditorState, item: Item): string => {\n return state.doc.sliceString(item.contentRange.from, item.contentRange.to);\n};\n\nexport const listItemToString = (item: Item, level = 0) => {\n const indent = ' '.repeat(level);\n const data = {\n i: item.index,\n n: item.nextSibling?.index ?? '∅',\n p: item.prevSibling?.index ?? '∅',\n level: item.level,\n node: format([item.node.from, item.node.to]),\n line: format([item.lineRange.from, item.lineRange.to]),\n content: format([item.contentRange.from, item.contentRange.to]),\n };\n\n return `${indent}${item.type[0].toUpperCase()}(${Object.entries(data)\n .map(([k, v]) => `${k}=${v}`)\n .join(', ')})`;\n};\n\nconst format = (value: any) =>\n JSON.stringify(value, (key: string, value: any) => {\n if (typeof value === 'number') {\n return value.toString().padStart(3, ' ');\n }\n return value;\n }).replaceAll('\"', '');\n\nexport const treeFacet = Facet.define<Tree, Tree>({\n combine: (values) => values[0],\n});\n\nexport type TreeOptions = {};\n\n/**\n * Creates a shadow tree of `ListItem` nodes whenever the document changes.\n * This adds overhead relative to the markdown AST, but allows for efficient traversal of the list items.\n * NOTE: Requires markdown parser to be enabled.\n */\nexport const outlinerTree = (options: TreeOptions = {}): Extension => {\n const buildTree = (state: EditorState): Tree => {\n let tree: Tree | undefined;\n let parent: Item | undefined;\n let current: Item | undefined;\n let prev: Item | undefined;\n let level = -1;\n let index = -1;\n\n // Array to track previous siblings at each level.\n const prevSiblings: (Item | undefined)[] = [];\n\n syntaxTree(state).iterate({\n enter: (node) => {\n switch (node.name) {\n case 'Document': {\n tree = new Tree(node.node);\n current = tree;\n break;\n }\n case 'BulletList': {\n invariant(current);\n parent = current;\n if (current) {\n current.lineRange.to = current.node.from;\n }\n prevSiblings[++level] = undefined;\n break;\n }\n case 'ListItem': {\n invariant(parent);\n\n // Include all content up to the next sibling or the end of the document.\n const nextSibling = node.node.nextSibling ?? node.node.parent?.nextSibling;\n const docRange: Range = {\n from: state.doc.lineAt(node.from).from,\n to: nextSibling ? nextSibling.from - 1 : state.doc.length,\n };\n\n current = {\n type: 'unknown',\n index: ++index,\n level,\n node: node.node,\n lineRange: docRange,\n contentRange: { ...docRange },\n parent,\n prevSibling: prevSiblings[level],\n children: [],\n };\n\n // Update sibling refs.\n if (current.prevSibling) {\n current.prevSibling.nextSibling = current;\n }\n\n // Update previous siblings array at current level.\n prevSiblings[level] = current;\n\n // Update previous item (not sibling).\n if (prev) {\n prev.lineRange.to = prev.contentRange.to = current.lineRange.from - 1;\n }\n prev = current;\n\n // Update parent.\n parent.children.push(current);\n if (parent.lineRange.to === parent.node.from) {\n parent.lineRange.to = parent.contentRange.to = current.lineRange.from - 1;\n }\n\n break;\n }\n case 'ListMark': {\n invariant(current);\n current.type = 'bullet';\n current.contentRange.from = node.from + '- '.length;\n break;\n }\n case 'Task': {\n invariant(current);\n current.type = 'task';\n break;\n }\n case 'TaskMarker': {\n invariant(current);\n current.contentRange.from = node.from + '[ ] '.length;\n break;\n }\n }\n },\n leave: (node) => {\n if (node.name === 'BulletList') {\n invariant(parent);\n prevSiblings[level--] = undefined;\n parent = parent.parent;\n }\n },\n });\n\n invariant(tree);\n return tree;\n };\n\n return [\n StateField.define<Tree | undefined>({\n create: (state) => {\n return buildTree(state);\n },\n update: (value: Tree | undefined, tr: Transaction) => {\n if (!tr.docChanged) {\n return value;\n }\n\n return buildTree(tr.state);\n },\n provide: (field) => treeFacet.from(field),\n }),\n ];\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type EditorState, type Extension, Prec, type Range } from '@codemirror/state';\nimport { Decoration, type DecorationSet, EditorView, ViewPlugin, type ViewUpdate } from '@codemirror/view';\n\nimport { mx } from '@dxos/react-ui-theme';\n\nimport { commands } from './commands';\nimport { editor } from './editor';\nimport { selectionCompartment, selectionFacet, selectionEquals } from './selection';\nimport { outlinerTree, treeFacet } from './tree';\nimport { floatingMenu } from '../command';\nimport { decorateMarkdown } from '../markdown';\n\n// ISSUES:\n// TODO(burdon): Remove requirement for continuous lines to be indented (so that user's can't accidentally delete them and break the layout).\n// TODO(burdon): Prevent unterminated fenced code from breaking subsequent items (\"firewall\" markdown parsing within each item?)\n// TODO(burdon): What if a different editor \"breaks\" the layout?\n// TODO(burdon): Check Automerge recognizes text that is moved/indented (e.g., concurrent editing item while being moved).\n\n// NEXT:\n// TODO(burdon): Update selection when adding/removing items.\n// TODO(burdon): When selecting across items, select entire items (don't show selection that spans the gaps).\n// TODO(burdon): Handle backspace at start of line (or empty line).\n// TODO(burdon): Convert to task object and insert link (menu button).\n// TODO(burdon): Smart Cut-and-paste.\n// TODO(burdon): DND.\n\nexport type OutlinerProps = {};\n\n/**\n * Outliner extension.\n * - Stores outline as a standard markdown document with task and list markers.\n * - Supports continuation lines and rich formatting (with Shift+Enter).\n * - Constrains editor to outline structure.\n * - Supports smart cut-and-paste.\n */\nexport const outliner = (options: OutlinerProps = {}): Extension => [\n // Commands.\n Prec.highest(commands()),\n\n // Selection.\n selectionCompartment.of(selectionFacet.of([])),\n\n // State.\n outlinerTree(),\n\n // Filter and possibly modify changes.\n editor(),\n\n // Floating menu.\n floatingMenu(),\n\n // Line decorations.\n decorations(),\n\n // Default markdown decorations.\n decorateMarkdown({ listPaddingLeft: 8 }),\n\n // Researve space for menu.\n EditorView.contentAttributes.of({ class: 'is-full !mr-[3rem]' }),\n];\n\n/**\n * Line decorations (for border and selection).\n */\nconst decorations = () => [\n ViewPlugin.fromClass(\n class {\n decorations: DecorationSet = Decoration.none;\n constructor(view: EditorView) {\n this.updateDecorations(view.state, view);\n }\n\n update(update: ViewUpdate) {\n const selectionChanged = !selectionEquals(\n update.state.facet(selectionFacet),\n update.startState.facet(selectionFacet),\n );\n\n if (\n update.focusChanged ||\n update.docChanged ||\n update.viewportChanged ||\n update.selectionSet ||\n selectionChanged\n ) {\n this.updateDecorations(update.state, update.view);\n }\n }\n\n private updateDecorations(state: EditorState, { viewport: { from, to }, hasFocus }: EditorView) {\n const selection = state.facet(selectionFacet);\n const tree = state.facet(treeFacet);\n const current = tree.find(state.selection.ranges[state.selection.mainIndex]?.from);\n const doc = state.doc;\n\n const decorations: Range<Decoration>[] = [];\n for (let lineNum = doc.lineAt(from).number; lineNum <= doc.lineAt(to).number; lineNum++) {\n const line = doc.line(lineNum);\n const item = tree.find(line.from);\n if (item) {\n const lineFrom = doc.lineAt(item.contentRange.from);\n const lineTo = doc.lineAt(item.contentRange.to);\n const isSelected = selection.includes(item.index) || item === current;\n decorations.push(\n Decoration.line({\n class: mx(\n 'cm-list-item',\n lineFrom.number === line.number && 'cm-list-item-start',\n lineTo.number === line.number && 'cm-list-item-end',\n isSelected && (hasFocus ? 'cm-list-item-focused' : 'cm-list-item-selected'),\n ),\n }).range(line.from, line.from),\n );\n }\n }\n\n this.decorations = Decoration.set(decorations);\n }\n },\n {\n decorations: (v) => v.decorations,\n },\n ),\n\n // Theme.\n EditorView.theme(\n Object.assign({\n '.cm-list-item': {\n borderLeftWidth: '1px',\n borderRightWidth: '1px',\n paddingLeft: '32px',\n borderColor: 'transparent',\n },\n '.cm-list-item.cm-codeblock-start': {\n borderRadius: '0',\n },\n\n '.cm-list-item-start': {\n borderTopWidth: '1px',\n borderTopLeftRadius: '4px',\n borderTopRightRadius: '4px',\n paddingTop: '4px',\n marginTop: '2px',\n },\n\n '.cm-list-item-end': {\n borderBottomWidth: '1px',\n borderBottomLeftRadius: '4px',\n borderBottomRightRadius: '4px',\n paddingBottom: '4px',\n marginBottom: '2px',\n },\n\n '.cm-list-item-focused': {\n borderColor: 'var(--dx-accentFocusIndicator)',\n },\n '[data-has-focus] & .cm-list-item-selected': {\n borderColor: 'var(--dx-separator)',\n },\n }),\n ),\n];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type ChangeSpec, EditorSelection, EditorState } from '@codemirror/state';\nimport { type EditorView, ViewPlugin } from '@codemirror/view';\n\nimport { log } from '@dxos/log';\n\nimport { getSelection } from './selection';\nimport { treeFacet } from './tree';\n\nconst LIST_ITEM_REGEX = /^\\s*- (\\[ \\]|\\[x\\])? /;\n\n/**\n * Initialize empty document.\n */\nconst initialize = () => {\n return ViewPlugin.fromClass(\n class {\n constructor(view: EditorView) {\n const first = view.state.doc.lineAt(0);\n const text = view.state.sliceDoc(first.from, first.to);\n const match = text.match(LIST_ITEM_REGEX);\n if (!match) {\n setTimeout(() => {\n const insert = '- [ ] ';\n view.dispatch({\n changes: [{ from: 0, to: 0, insert }],\n selection: EditorSelection.cursor(insert.length),\n });\n });\n }\n }\n },\n );\n};\n\n/**\n * Handle cursor movement, selection, and editing.\n */\nexport const editor = () => [\n initialize(),\n\n EditorState.transactionFilter.of((tr) => {\n const tree = tr.state.facet(treeFacet);\n\n //\n // Check cursor is in a valid position.\n //\n if (!tr.docChanged) {\n const current = getSelection(tr.state).from;\n if (current != null) {\n const currentItem = tree.find(current);\n if (!currentItem) {\n return [];\n }\n\n // Check if outside of editable range.\n if (current < currentItem.contentRange.from || current > currentItem.contentRange.to) {\n const prev = getSelection(tr.startState).from;\n const prevItem = prev != null ? tree.find(prev) : undefined;\n if (!prevItem) {\n return [{ selection: EditorSelection.cursor(currentItem.contentRange.from) }];\n } else {\n if (currentItem.index < prevItem.index) {\n // Moving line up.\n return [{ selection: EditorSelection.cursor(currentItem.contentRange.to) }];\n } else if (currentItem.index > prevItem.index) {\n // Moving line down.\n return [{ selection: EditorSelection.cursor(currentItem.contentRange.from) }];\n } else {\n // Moving left.\n if (current < prev) {\n if (currentItem.index === 0) {\n // At start of the list.\n return [];\n } else {\n // Go to previous line.\n return [{ selection: EditorSelection.cursor(currentItem.lineRange.from - 1) }];\n }\n } else {\n // Go to end of line.\n return [{ selection: EditorSelection.cursor(currentItem.contentRange.to) }];\n }\n }\n }\n }\n }\n\n return tr;\n }\n\n //\n // Validate changes that don't break the tree.\n //\n let cancel = false;\n const changes: ChangeSpec[] = [];\n tr.changes.iterChanges((fromA, toA, fromB, toB, insert) => {\n const line = tr.startState.doc.lineAt(fromA);\n const match = line.text.match(LIST_ITEM_REGEX);\n if (match) {\n // Check cursor was in a valid position.\n const startTree = tr.startState.facet(treeFacet);\n const startItem = startTree.find(tr.startState.selection.main.from);\n\n // Check if entire line was deleted (which is ok).\n const deleteLine = fromA === startItem?.lineRange.from && toA === startItem?.lineRange.to + 1;\n if (deleteLine) {\n return;\n }\n\n // if (!deleteLine && (!startItem || fromA < startItem.contentRange.from || toA > startItem.contentRange.to)) {\n // cancel = true;\n // return;\n // }\n\n // Check valid item.\n const currentItem = tree.find(tr.state.selection.main.from);\n if (!currentItem?.contentRange) {\n cancel = true;\n return;\n }\n\n // Detect and cancel replacement of task marker with continuation indent.\n // Task markers are atomic so will be deleted when backspace is pressed.\n // The markdown extension inserts 2 or 6 spaces when deleting a list or task marker in order to create a continuation.\n // - [ ] <- backspace here deletes the task marker.\n // - [ ] <- backspace here inserts 6 spaces (creates continuation).\n // - [ ] <- backspace here deletes the task marker.\n const start = line.from + (match?.[0]?.length ?? 0);\n const replace = start === toA && toA - fromA === insert.length;\n if (replace) {\n changes.push({ from: line.from - 1, to: toA });\n return;\n }\n\n // Detect deletion of marker.\n if (fromB === toB) {\n if (toA === line.to) {\n const line = tr.state.doc.lineAt(fromA);\n if (line.text.match(/^\\s*$/)) {\n if (line.from === 0) {\n // Don't delete first line.\n cancel = true;\n return;\n } else {\n // Delete indent and marker.\n changes.push({ from: line.from - 1, to: toA });\n return;\n }\n }\n }\n return;\n }\n\n // Prevent newline if line is empty.\n const item = tree.find(fromA);\n if (item?.contentRange.from === item?.contentRange.to && fromA === toA) {\n cancel = true;\n return;\n }\n\n log('change', {\n item,\n line: { from: line.from, to: line.to },\n a: [fromA, toA],\n b: [fromB, toB],\n insert: { text: insert.toString(), length: insert.length },\n });\n }\n });\n\n if (changes.length > 0) {\n log('modified,', { changes });\n return [{ changes }];\n } else if (cancel) {\n log('cancel');\n return [];\n }\n\n return tr;\n }),\n];\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport '@dxos/lit-ui/dx-ref-tag.pcss';\n\nimport { syntaxTree } from '@codemirror/language';\nimport {\n type EditorState,\n type Extension,\n type RangeSet,\n RangeSetBuilder,\n StateField,\n type Transaction,\n} from '@codemirror/state';\nimport { Decoration, type DecorationSet, EditorView, WidgetType } from '@codemirror/view';\nimport { type SyntaxNode } from '@lezer/common';\n\nexport type PreviewLinkRef = {\n suggest?: boolean;\n block?: boolean;\n label: string;\n ref: string;\n};\n\nexport type PreviewLinkTarget = {\n label: string;\n text?: string;\n object?: any;\n};\n\n// TODO(wittjosiah): Remove.\n// TODO(burdon): Handle error.\nexport type PreviewLookup = (link: PreviewLinkRef) => Promise<PreviewLinkTarget | null | undefined>;\n\nexport type PreviewOptions = {\n addBlockContainer?: (link: PreviewLinkRef, el: HTMLElement) => void;\n removeBlockContainer?: (link: PreviewLinkRef) => void;\n};\n\n/**\n * Create preview decorations.\n */\nexport const preview = (options: PreviewOptions = {}): Extension => {\n return [\n // NOTE: Atomic block decorations must be created from a state field, now a widget, otherwise it results in the following error:\n // \"Block decorations may not be specified via plugins\"\n StateField.define<DecorationSet>({\n create: (state) => buildDecorations(state, options),\n update: (_: RangeSet<Decoration>, tr: Transaction) => buildDecorations(tr.state, options),\n provide: (field) => [\n EditorView.decorations.from(field),\n EditorView.atomicRanges.of((view) => view.state.field(field)),\n ],\n }),\n ];\n};\n\n/**\n * Link references.\n *\n * [Label][dxn:echo:123] Inline reference\n * ![Label][dxn:echo:123] Block reference\n * ![Label][?dxn:echo:123] Suggestion\n */\nexport const getLinkRef = (state: EditorState, node: SyntaxNode): PreviewLinkRef | undefined => {\n const mark = node.getChild('LinkMark');\n const label = node.getChild('LinkLabel');\n if (mark && label) {\n const ref = state.sliceDoc(label.from + 1, label.to - 1);\n return {\n suggest: ref.startsWith('?'),\n block: state.sliceDoc(mark.from, mark.from + 1) === '!',\n label: state.sliceDoc(mark.to, label.from - 1),\n ref: ref.startsWith('?') ? ref.slice(1) : ref,\n };\n }\n};\n\n/**\n * Echo references are represented as markdown reference links.\n * https://www.markdownguide.org/basic-syntax/#reference-style-links\n * [Label|block][dxn:echo:123]\n * [Label|inline][dxn:echo:123]\n */\nconst buildDecorations = (state: EditorState, options: PreviewOptions) => {\n const builder = new RangeSetBuilder<Decoration>();\n\n syntaxTree(state).iterate({\n enter: (node) => {\n switch (node.name) {\n //\n // Decoration.\n // [Label][dxn:echo:123]\n //\n case 'Link': {\n const link = getLinkRef(state, node.node);\n if (link) {\n builder.add(\n node.from,\n node.to,\n Decoration.replace({\n widget: new PreviewInlineWidget(options, link),\n }),\n );\n }\n break;\n }\n //\n // Block widget.\n // ![Label][dxn:echo:123]\n //\n case 'Image': {\n const link = getLinkRef(state, node.node);\n if (options.addBlockContainer && options.removeBlockContainer && link) {\n builder.add(\n node.from,\n node.to,\n Decoration.replace({\n block: true,\n // atomic: true,\n widget: new PreviewBlockWidget(options, link),\n }),\n );\n }\n break;\n }\n }\n },\n });\n\n return builder.finish();\n};\n\n/**\n * Inline widget.\n * [Label][dxn:echo:123]\n */\nclass PreviewInlineWidget extends WidgetType {\n constructor(\n readonly _options: PreviewOptions,\n readonly _link: PreviewLinkRef,\n ) {\n super();\n }\n\n // override ignoreEvent() {\n // return false;\n // }\n\n override eq(other: this): boolean {\n return this._link.ref === other._link.ref && this._link.label === other._link.label;\n }\n\n override toDOM(view: EditorView): HTMLElement {\n const root = document.createElement('dx-ref-tag');\n root.textContent = this._link.label;\n root.setAttribute('refId', this._link.ref);\n return root;\n }\n}\n\n/**\n * Block widget.\n * ![Label][dxn:echo:123]\n */\nclass PreviewBlockWidget extends WidgetType {\n constructor(\n readonly _options: PreviewOptions,\n readonly _link: PreviewLinkRef,\n ) {\n super();\n }\n\n // override ignoreEvent() {\n // return true;\n // }\n\n override eq(other: this): boolean {\n return this._link.ref === other._link.ref;\n }\n\n override toDOM(view: EditorView): HTMLDivElement {\n const root = document.createElement('div');\n root.classList.add('cm-preview-block', 'density-coarse');\n this._options.addBlockContainer?.(this._link, root);\n return root;\n }\n\n override destroy() {\n this._options.removeBlockContainer?.(this._link);\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Extension } from '@codemirror/state';\nimport { keymap } from '@codemirror/view';\n\n// TODO(burdon): Review https://github.com/sergeche/codemirror-movie?tab=readme-ov-file\n\nexport type DemoOptions = {\n delay?: number;\n items?: string[];\n};\n\nconst defaultItems = ['hello world!', 'this is a test.', 'this is [DXOS](https://dxos.org)'];\n\n/**\n * Configurable plugin that let's user cycle through pre-configured input script.\n */\nexport const typewriter = ({ delay = 75, items = defaultItems }: DemoOptions = {}): Extension => {\n let t: any;\n let idx = 0; // TODO(burdon): Make global.\n\n return [\n keymap.of([\n {\n // Reset.\n key: \"alt-meta-'\",\n run: (view) => {\n clearTimeout(t);\n idx = 0;\n return true;\n },\n },\n {\n // Next prompt.\n // TODO(burdon): Press 1-9 to select prompt?\n key: \"shift-meta-'\",\n run: (view) => {\n clearTimeout(t);\n // TODO(burdon): Add space if needed.\n const text = items[idx++];\n if (idx === items?.length) {\n idx = 0;\n }\n\n let i = 0;\n const insert = (d = 0) => {\n t = setTimeout(() => {\n const pos = view.state.selection.main.head;\n view.dispatch({\n changes: { from: pos, insert: text[i++] },\n selection: { anchor: pos + 1 },\n });\n\n if (i < text.length) {\n insert(Math.random() * delay * (text[i] === ' ' ? 2 : 1));\n }\n }, d);\n };\n\n insert();\n return true;\n },\n },\n ]),\n ];\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type EditorView } from '@codemirror/view';\n\nimport { type NodeArg } from '@dxos/app-graph';\nimport { type ToolbarMenuActionGroupProperties } from '@dxos/react-ui-menu';\n\nimport { createEditorAction, createEditorActionGroup, type EditorToolbarState } from './util';\nimport { removeBlockquote, addBlockquote, removeCodeblock, addCodeblock, insertTable } from '../../extensions';\n\nconst createBlockGroupAction = (value: string) =>\n createEditorActionGroup('block', {\n variant: 'toggleGroup',\n selectCardinality: 'single',\n value,\n } as ToolbarMenuActionGroupProperties);\n\nconst createBlockActions = (value: string, getView: () => EditorView, blankLine?: boolean) =>\n Object.entries({\n blockquote: 'ph--quotes--regular',\n codeblock: 'ph--code-block--regular',\n table: 'ph--table--regular',\n }).map(([type, icon]) => {\n const checked = type === value;\n return createEditorAction(\n type,\n () => {\n const view = getView();\n if (!view) {\n return;\n }\n\n switch (type) {\n case 'blockquote':\n checked ? removeBlockquote(view) : addBlockquote(view);\n break;\n case 'codeblock':\n checked ? removeCodeblock(view) : addCodeblock(view);\n break;\n case 'table':\n insertTable(view);\n break;\n }\n },\n { checked, ...(type === 'table' && { disabled: !!blankLine }), icon },\n );\n });\n\nexport const createBlocks = (state: EditorToolbarState, getView: () => EditorView) => {\n const value = state?.blockQuote ? 'blockquote' : state.blockType ?? '';\n const blockGroupAction = createBlockGroupAction(value);\n const blockActions = createBlockActions(value, getView, state.blankLine);\n return {\n nodes: [blockGroupAction as NodeArg<any>, ...blockActions],\n edges: [\n { source: 'root', target: 'block' },\n ...blockActions.map(({ id }) => ({ source: blockGroupAction.id, target: id })),\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type EditorView } from '@codemirror/view';\n\nimport { type NodeArg } from '@dxos/app-graph';\nimport { type ToolbarMenuActionGroupProperties } from '@dxos/react-ui-menu';\n\nimport { createEditorAction, createEditorActionGroup, type EditorToolbarState } from './util';\nimport { addLink, Inline, removeLink, setStyle, type Formatting } from '../../extensions';\n\nconst formats = {\n strong: 'ph--text-b--regular',\n emphasis: 'ph--text-italic--regular',\n strikethrough: 'ph--text-strikethrough--regular',\n code: 'ph--code--regular',\n link: 'ph--link--regular',\n};\n\nconst createFormattingGroup = (formatting: Formatting) =>\n createEditorActionGroup('formatting', {\n variant: 'toggleGroup',\n selectCardinality: 'multiple',\n value: Object.keys(formats).filter((key) => !!formatting[key as keyof Formatting]),\n } as ToolbarMenuActionGroupProperties);\n\nconst createFormattingActions = (formatting: Formatting, getView: () => EditorView) =>\n Object.entries(formats).map(([type, icon]) => {\n const checked = !!formatting[type as keyof Formatting];\n return createEditorAction(\n type,\n () => {\n const view = getView();\n if (!view) {\n return;\n }\n\n if (type === 'link') {\n checked ? removeLink(view) : addLink()(view);\n return;\n }\n\n const inlineType =\n type === 'strong'\n ? Inline.Strong\n : type === 'emphasis'\n ? Inline.Emphasis\n : type === 'strikethrough'\n ? Inline.Strikethrough\n : Inline.Code;\n setStyle(inlineType, !checked)(view);\n },\n { checked, icon },\n );\n });\n\nexport const createFormatting = (state: EditorToolbarState, getView: () => EditorView) => {\n const formattingGroupAction = createFormattingGroup(state);\n const formattingActions = createFormattingActions(state, getView);\n return {\n nodes: [formattingGroupAction as NodeArg<any>, ...formattingActions],\n edges: [\n { source: 'root', target: 'formatting' },\n ...formattingActions.map(({ id }) => ({ source: formattingGroupAction.id, target: id })),\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type EditorView } from '@codemirror/view';\n\nimport { type NodeArg } from '@dxos/app-graph';\nimport { type ToolbarMenuActionGroupProperties } from '@dxos/react-ui-menu';\n\nimport { createEditorAction, createEditorActionGroup, type EditorToolbarState } from './util';\nimport { setHeading } from '../../extensions';\nimport { translationKey } from '../../translations';\n\nconst createHeadingGroupAction = (value: string) =>\n createEditorActionGroup(\n 'heading',\n {\n variant: 'dropdownMenu',\n applyActive: true,\n selectCardinality: 'single',\n value,\n } as ToolbarMenuActionGroupProperties,\n 'ph--text-h--regular',\n );\n\nconst createHeadingActions = (getView: () => EditorView) =>\n Object.entries({\n '0': 'ph--paragraph--regular',\n '1': 'ph--text-h-one--regular',\n '2': 'ph--text-h-two--regular',\n '3': 'ph--text-h-three--regular',\n '4': 'ph--text-h-four--regular',\n '5': 'ph--text-h-five--regular',\n '6': 'ph--text-h-six--regular',\n }).map(([levelStr, icon]) => {\n const level = parseInt(levelStr);\n return createEditorAction(`heading--${levelStr}`, () => setHeading(level)(getView()), {\n label: ['heading level label', { count: level, ns: translationKey }],\n icon,\n });\n });\n\nconst computeHeadingValue = (state: EditorToolbarState) => {\n const blockType = state ? state.blockType : 'paragraph';\n const header = blockType && /heading(\\d)/.exec(blockType);\n return header ? header[1] : blockType === 'paragraph' || !blockType ? '0' : '';\n};\n\nexport const createHeadings = (state: EditorToolbarState, getView: () => EditorView) => {\n const headingValue = computeHeadingValue(state);\n const headingGroupAction = createHeadingGroupAction(headingValue);\n const headingActions = createHeadingActions(getView);\n return {\n nodes: [headingGroupAction as NodeArg<any>, ...headingActions],\n edges: [\n { source: 'root', target: 'heading' },\n ...headingActions.map(({ id }) => ({ source: headingGroupAction.id, target: id })),\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { createEditorAction } from './util';\n\nconst createImageUploadAction = (onImageUpload: () => void) =>\n createEditorAction('image', onImageUpload, {\n testId: 'editor.toolbar.image',\n icon: 'ph--image-square--regular',\n });\n\nexport const createImageUpload = (onImageUpload: () => void) => ({\n nodes: [createImageUploadAction(onImageUpload)],\n edges: [{ source: 'root', target: 'image' }],\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type EditorView } from '@codemirror/view';\n\nimport { type NodeArg } from '@dxos/app-graph';\nimport { type ToolbarMenuActionGroupProperties } from '@dxos/react-ui-menu';\n\nimport { createEditorAction, createEditorActionGroup, type EditorToolbarState } from './util';\nimport { addList, List, removeList } from '../../extensions';\n\nconst listStyles = {\n bullet: 'ph--list-bullets--regular',\n ordered: 'ph--list-numbers--regular',\n task: 'ph--list-checks--regular',\n};\n\nconst createListGroupAction = (value: string) =>\n createEditorActionGroup('list', {\n variant: 'toggleGroup',\n selectCardinality: 'single',\n value,\n } as ToolbarMenuActionGroupProperties);\n\nconst createListActions = (value: string, getView: () => EditorView) =>\n Object.entries(listStyles).map(([listStyle, icon]) => {\n const checked = value === listStyle;\n return createEditorAction(\n `list-${listStyle}`,\n () => {\n const view = getView();\n if (!view) {\n return;\n }\n\n const listType = listStyle === 'ordered' ? List.Ordered : listStyle === 'bullet' ? List.Bullet : List.Task;\n if (checked) {\n removeList(listType)(view);\n } else {\n addList(listType)(view);\n }\n },\n { checked, icon },\n );\n });\n\nexport const createLists = (state: EditorToolbarState, getView: () => EditorView) => {\n const value = state.listStyle ?? '';\n const listGroupAction = createListGroupAction(value);\n const listActionsMap = createListActions(value, getView);\n return {\n nodes: [listGroupAction as NodeArg<any>, ...listActionsMap],\n edges: [\n { source: 'root', target: 'list' },\n ...listActionsMap.map(({ id }) => ({ source: listGroupAction.id, target: id })),\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { openSearchPanel } from '@codemirror/search';\nimport { type EditorView } from '@codemirror/view';\n\nimport { createEditorAction } from './util';\n\nconst createSearchAction = (getView: () => EditorView) =>\n createEditorAction('search', () => openSearchPanel(getView()), {\n testId: 'editor.toolbar.search',\n icon: 'ph--magnifying-glass--regular',\n });\n\nexport const createSearch = (getView: () => EditorView) => ({\n nodes: [createSearchAction(getView)],\n edges: [{ source: 'root', target: 'search' }],\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type NodeArg } from '@dxos/app-graph';\nimport { type ToolbarMenuActionGroupProperties } from '@dxos/react-ui-menu';\n\nimport { createEditorAction, createEditorActionGroup, type EditorToolbarState } from './util';\nimport { type EditorViewMode } from '../../extensions';\nimport { translationKey } from '../../translations';\n\nconst createViewModeGroupAction = (value: string) =>\n createEditorActionGroup(\n 'viewMode',\n {\n variant: 'dropdownMenu',\n applyActive: true,\n selectCardinality: 'single',\n value,\n } as ToolbarMenuActionGroupProperties,\n 'ph--eye--regular',\n );\n\nconst createViewModeActions = (value: string, onViewModeChange: (mode: EditorViewMode) => void) =>\n Object.entries({\n preview: 'ph--eye--regular',\n source: 'ph--pencil-simple--regular',\n readonly: 'ph--pencil-slash--regular',\n }).map(([viewMode, icon]) => {\n const checked = viewMode === value;\n return createEditorAction(`view-mode--${viewMode}`, () => onViewModeChange(viewMode as EditorViewMode), {\n label: [`${viewMode} mode label`, { ns: translationKey }],\n checked,\n icon,\n });\n });\n\nexport const createViewMode = (state: EditorToolbarState, onViewModeChange: (mode: EditorViewMode) => void) => {\n const value = state.viewMode ?? 'source';\n const viewModeGroupAction = createViewModeGroupAction(value);\n const viewModeActions = createViewModeActions(value, onViewModeChange);\n return {\n nodes: [viewModeGroupAction as NodeArg<any>, ...viewModeActions],\n edges: [\n { source: 'root', target: 'viewMode' },\n ...viewModeActions.map(({ id }) => ({ source: viewModeGroupAction.id, target: id })),\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type EditorView } from '@codemirror/view';\nimport React, { useCallback, useEffect, useRef } from 'react';\n\nimport { Icon, type Label, Popover, toLocalizedString, useThemeContext, useTranslation } from '@dxos/react-ui';\nimport { type MaybePromise } from '@dxos/util';\n\nimport { commandRangeEffect } from '../../extensions';\n\nexport type CommandMenuGroup = {\n id: string;\n label?: Label;\n items: CommandMenuItem[];\n};\n\nexport type CommandMenuItem = {\n id: string;\n label: Label;\n icon?: string;\n onSelect?: (view: EditorView, head: number) => MaybePromise<void>;\n};\n\nexport type CommandMenuProps = {\n groups: CommandMenuGroup[];\n currentItem?: string;\n onSelect: (item: CommandMenuItem) => void;\n};\n\n// NOTE: Not using DropdownMenu because the command menu needs to manage focus explicitly.\nexport const CommandMenu = ({ groups, currentItem, onSelect }: CommandMenuProps) => {\n const { tx } = useThemeContext();\n const groupsWithItems = groups.filter((group) => group.items.length > 0);\n return (\n <Popover.Portal>\n <Popover.Content\n align='start'\n onOpenAutoFocus={(event) => event.preventDefault()}\n classNames={tx('menu.content', 'menu--exotic-unfocusable', { elevation: 'positioned' }, [\n 'max-h-[300px] overflow-y-auto',\n ])}\n >\n <Popover.Viewport classNames={tx('menu.viewport', 'menu__viewport--exotic-unfocusable', {})}>\n <ul>\n {groupsWithItems.map((group, index) => (\n <React.Fragment key={group.id}>\n <CommandGroup group={group} currentItem={currentItem} onSelect={onSelect} />\n {index < groupsWithItems.length - 1 && <div className={tx('menu.separator', 'menu__item', {})} />}\n </React.Fragment>\n ))}\n </ul>\n </Popover.Viewport>\n </Popover.Content>\n </Popover.Portal>\n );\n};\n\nconst CommandGroup = ({\n group,\n currentItem,\n onSelect,\n}: {\n group: CommandMenuGroup;\n currentItem?: string;\n onSelect: (item: CommandMenuItem) => void;\n}) => {\n const { tx } = useThemeContext();\n const { t } = useTranslation();\n return (\n <>\n {group.label && (\n <div className={tx('menu.groupLabel', 'menu__group__label', {})}>\n <span>{toLocalizedString(group.label, t)}</span>\n </div>\n )}\n {group.items.map((item) => (\n <CommandItem key={item.id} item={item} current={currentItem === item.id} onSelect={onSelect} />\n ))}\n </>\n );\n};\n\nconst CommandItem = ({\n item,\n current,\n onSelect,\n}: {\n item: CommandMenuItem;\n current: boolean;\n onSelect: (item: CommandMenuItem) => void;\n}) => {\n const ref = useRef<HTMLLIElement>(null);\n const { tx } = useThemeContext();\n const { t } = useTranslation();\n const handleSelect = useCallback(() => onSelect(item), [item, onSelect]);\n\n useEffect(() => {\n if (current && ref.current) {\n ref.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });\n }\n }, [current]);\n\n return (\n <li\n ref={ref}\n className={tx('menu.item', 'menu__item--exotic-unfocusable', {}, [current && 'bg-hoverSurface'])}\n onClick={handleSelect}\n >\n {item.icon && <Icon icon={item.icon} size={5} />}\n <span className='grow truncate'>{toLocalizedString(item.label, t)}</span>\n </li>\n );\n};\n\n// TODO(wittjosiah): Factor out into a separate file.\n\n//\n// Helpers\n//\n\nexport const getItem = (groups: CommandMenuGroup[], id?: string): CommandMenuItem | undefined => {\n return groups.flatMap((group) => group.items).find((item) => item.id === id);\n};\n\nexport const getNextItem = (groups: CommandMenuGroup[], id?: string): CommandMenuItem => {\n const items = groups.flatMap((group) => group.items);\n const index = items.findIndex((item) => item.id === id);\n return items[(index + 1) % items.length];\n};\n\nexport const getPreviousItem = (groups: CommandMenuGroup[], id?: string): CommandMenuItem => {\n const items = groups.flatMap((group) => group.items);\n const index = items.findIndex((item) => item.id === id);\n return items[(index - 1 + items.length) % items.length];\n};\n\nexport const filterItems = (\n groups: CommandMenuGroup[],\n filter: (item: CommandMenuItem) => boolean,\n): CommandMenuGroup[] => {\n return groups.map((group) => ({\n ...group,\n items: group.items.filter(filter),\n }));\n};\n\nexport const insertAtCursor = (view: EditorView, head: number, insert: string) => {\n view.dispatch({\n changes: { from: head, to: head, insert },\n selection: { anchor: head + insert.length, head: head + insert.length },\n });\n};\n\n/**\n * If the cursor is at the start of a line, insert the text at the cursor.\n * Otherwise, insert the text on a new line.\n */\nexport const insertAtLineStart = (view: EditorView, head: number, insert: string) => {\n const line = view.state.doc.lineAt(head);\n if (line.from === head) {\n insertAtCursor(view, head, insert);\n } else {\n insert = '\\n' + insert;\n view.dispatch({\n changes: { from: line.to, to: line.to, insert },\n selection: { anchor: line.to + insert.length, head: line.to + insert.length },\n });\n }\n};\n\nexport const coreSlashCommands: CommandMenuGroup = {\n id: 'markdown',\n label: 'Markdown',\n items: [\n {\n id: 'heading-1',\n label: 'Heading 1',\n icon: 'ph--text-h-one--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '# '),\n },\n {\n id: 'heading-2',\n label: 'Heading 2',\n icon: 'ph--text-h-two--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '## '),\n },\n {\n id: 'heading-3',\n label: 'Heading 3',\n icon: 'ph--text-h-three--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '### '),\n },\n {\n id: 'heading-4',\n label: 'Heading 4',\n icon: 'ph--text-h-four--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '#### '),\n },\n {\n id: 'heading-5',\n label: 'Heading 5',\n icon: 'ph--text-h-five--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '##### '),\n },\n {\n id: 'heading-6',\n label: 'Heading 6',\n icon: 'ph--text-h-six--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '###### '),\n },\n {\n id: 'bullet-list',\n label: 'Bullet List',\n icon: 'ph--list-bullets--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '- '),\n },\n {\n id: 'numbered-list',\n label: 'Numbered List',\n icon: 'ph--list-numbers--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '1. '),\n },\n {\n id: 'task-list',\n label: 'Task List',\n icon: 'ph--list-checks--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '- [ ] '),\n },\n {\n id: 'quote',\n label: 'Quote',\n icon: 'ph--quotes--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '> '),\n },\n {\n id: 'code-block',\n label: 'Code Block',\n icon: 'ph--code-block--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '```\\n\\n```'),\n },\n {\n id: 'table',\n label: 'Table',\n icon: 'ph--table--regular',\n onSelect: (view, head) => insertAtLineStart(view, head, '| | | |\\n|---|---|---|\\n| | | |'),\n },\n ],\n};\n\nexport const linkSlashCommands: CommandMenuGroup = {\n id: 'link',\n label: 'Link',\n items: [\n {\n id: 'inline-link',\n label: 'Inline link',\n icon: 'ph--link--regular',\n onSelect: (view, head) =>\n view.dispatch({\n changes: { from: head, insert: '@' },\n selection: { anchor: head + 1, head: head + 1 },\n effects: commandRangeEffect.of({ trigger: '@', range: { from: head, to: head + 1 } }),\n }),\n },\n {\n id: 'block-embed',\n label: 'Block embed',\n icon: 'ph--lego--regular',\n onSelect: (view, head) =>\n view.dispatch({\n changes: { from: head, insert: '@@' },\n selection: { anchor: head + 2, head: head + 2 },\n effects: commandRangeEffect.of({ trigger: '@', range: { from: head, to: head + 2 } }),\n }),\n },\n ],\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { createContext } from '@radix-ui/react-context';\nimport React, {\n type PropsWithChildren,\n useRef,\n useState,\n useEffect,\n useCallback,\n type RefObject,\n forwardRef,\n} from 'react';\n\nimport { addEventListener } from '@dxos/async';\nimport { type DxRefTag, type DxRefTagActivate } from '@dxos/lit-ui';\nimport { Popover } from '@dxos/react-ui';\n\nimport { type PreviewLinkRef, type PreviewLinkTarget, type PreviewLookup } from '../../extensions';\n\nconst customEventOptions = { capture: true, passive: false };\n\nexport type RefPopoverProps = PropsWithChildren<{\n modal?: boolean;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n onActivate?: (event: DxRefTagActivate) => void;\n}>;\n\nexport const RefPopover = forwardRef<DxRefTag | null, RefPopoverProps>(\n ({ children, open, onOpenChange, modal, onActivate }, ref) => {\n const [rootRef, setRootRef] = useState<HTMLDivElement | null>(null);\n\n useEffect(() => {\n if (!rootRef || !onActivate) {\n return;\n }\n\n return addEventListener(rootRef, 'dx-ref-tag-activate' as any, onActivate, customEventOptions);\n }, [rootRef, onActivate]);\n\n return (\n <Popover.Root open={open} onOpenChange={onOpenChange} modal={modal}>\n <Popover.VirtualTrigger virtualRef={ref as unknown as RefObject<HTMLButtonElement>} />\n <div role='none' className='contents' ref={setRootRef}>\n {children}\n </div>\n </Popover.Root>\n );\n },\n);\n\n// Create a context for the dxn value.\ntype RefPopoverValue = Partial<{ link: PreviewLinkRef; target: PreviewLinkTarget; pending: boolean }>;\n\nconst REF_POPOVER = 'RefPopover';\nconst [RefPopoverContextProvider, useRefPopover] = createContext<RefPopoverValue>(REF_POPOVER, {});\n\ntype PreviewProviderProps = PropsWithChildren<{ onLookup?: PreviewLookup }>;\n\nconst PreviewProvider = ({ children, onLookup }: PreviewProviderProps) => {\n const trigger = useRef<DxRefTag | null>(null);\n const [value, setValue] = useState<RefPopoverValue>({});\n const [open, setOpen] = useState(false);\n\n const handleDxRefTagActivate = useCallback(\n (event: DxRefTagActivate) => {\n const { refId, label, trigger: dxTrigger } = event;\n setValue((value) => ({\n ...value,\n link: { label, ref: refId },\n pending: true,\n }));\n trigger.current = dxTrigger;\n queueMicrotask(() => setOpen(true));\n void onLookup?.({ label, ref: refId }).then((target) =>\n setValue((value) => ({\n ...value,\n target: target ?? undefined,\n pending: false,\n })),\n );\n },\n [onLookup],\n );\n\n return (\n <RefPopoverContextProvider pending={value.pending} link={value.link} target={value.target}>\n <RefPopover ref={trigger} open={open} onOpenChange={setOpen} onActivate={handleDxRefTagActivate}>\n {children}\n </RefPopover>\n </RefPopoverContextProvider>\n );\n};\n\nexport { PreviewProvider, useRefPopover };\n\nexport type { PreviewProviderProps, RefPopoverValue };\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { createContext } from '@radix-ui/react-context';\nimport React, { type PropsWithChildren, useRef, useState, useEffect, useCallback, type RefObject } from 'react';\n\nimport { addEventListener } from '@dxos/async';\nimport { type DxRefTag, type DxRefTagActivate } from '@dxos/lit-ui';\nimport { DropdownMenu } from '@dxos/react-ui';\n\nimport { type PreviewLinkRef, type PreviewLinkTarget, type PreviewLookup } from '../../extensions';\n\n// TODO(burdon): Reconcile with RefPopover?\n\nconst customEventOptions = { capture: true, passive: false };\n\n// Create a context for the dxn value.\ntype RefDropdownMenuValue = Partial<{ link: PreviewLinkRef; target: PreviewLinkTarget; pending: boolean }>;\n\nconst REF_DROPDOWN_MENU = 'RefDropdownMenu';\nconst [RefDropdownMenuContextProvider, useRefDropdownMenu] = createContext<RefDropdownMenuValue>(REF_DROPDOWN_MENU, {});\n\ntype RefDropdownMenuProviderProps = PropsWithChildren<{ onLookup?: PreviewLookup }>;\n\nconst RefDropdownMenuProvider = ({ children, onLookup }: RefDropdownMenuProviderProps) => {\n const trigger = useRef<DxRefTag | null>(null);\n const [value, setValue] = useState<RefDropdownMenuValue>({});\n const [rootRef, setRootRef] = useState<HTMLDivElement | null>(null);\n const [open, setOpen] = useState(false);\n\n const handleDxRefTagActivate = useCallback(\n (event: DxRefTagActivate) => {\n const { refId, label, trigger: dxTrigger } = event;\n setValue((value) => ({\n ...value,\n link: { label, ref: refId },\n pending: true,\n }));\n trigger.current = dxTrigger;\n queueMicrotask(() => setOpen(true));\n void onLookup?.({ label, ref: refId }).then((target) =>\n setValue((value) => ({\n ...value,\n target: target ?? undefined,\n pending: false,\n })),\n );\n },\n [onLookup],\n );\n\n useEffect(() => {\n if (!rootRef) {\n return;\n }\n\n return addEventListener(rootRef, 'dx-ref-tag-activate' as any, handleDxRefTagActivate, customEventOptions);\n }, [rootRef]);\n\n return (\n <RefDropdownMenuContextProvider pending={value.pending} link={value.link} target={value.target}>\n <DropdownMenu.Root open={open} onOpenChange={setOpen}>\n <DropdownMenu.VirtualTrigger virtualRef={trigger as unknown as RefObject<HTMLButtonElement>} />\n <div role='none' className='contents' ref={setRootRef}>\n {children}\n </div>\n </DropdownMenu.Root>\n </RefDropdownMenuContextProvider>\n );\n};\n\nexport const RefDropdownMenu = {\n Provider: RefDropdownMenuProvider,\n};\n\nexport { useRefDropdownMenu };\n\nexport type { RefDropdownMenuProviderProps, RefDropdownMenuValue };\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { EditorState, type EditorStateConfig, type Text } from '@codemirror/state';\nimport { EditorView } from '@codemirror/view';\nimport { useFocusableGroup, type TabsterTypes } from '@fluentui/react-tabster';\nimport {\n type DependencyList,\n type KeyboardEventHandler,\n type RefObject,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport { log } from '@dxos/log';\nimport { getProviderValue, isNotFalsy, type MaybeProvider } from '@dxos/util';\n\nimport { type EditorSelection, documentId, createEditorStateTransaction, editorInputMode } from '../extensions';\nimport { debugDispatcher } from '../util';\n\nlet instanceCount = 0;\n\nexport type CursorInfo = {\n from: number;\n to: number;\n line: number;\n lines: number;\n length: number;\n after?: string;\n};\n\nexport type UseTextEditor = {\n // TODO(burdon): Rename.\n parentRef: RefObject<HTMLDivElement>;\n view?: EditorView;\n focusAttributes?: TabsterTypes.TabsterDOMAttribute & {\n tabIndex: 0;\n onKeyUp: KeyboardEventHandler<HTMLDivElement>;\n };\n};\n\nexport type UseTextEditorProps = Pick<EditorStateConfig, 'extensions'> & {\n id?: string;\n doc?: Text;\n initialValue?: string;\n autoFocus?: boolean;\n scrollTo?: number;\n selection?: EditorSelection;\n moveToEndOfLine?: boolean;\n debug?: boolean;\n};\n\n/**\n * Creates codemirror text editor.\n */\nexport const useTextEditor = (\n props: MaybeProvider<UseTextEditorProps> = {},\n deps: DependencyList = [],\n): UseTextEditor => {\n const { id, doc, initialValue, extensions, autoFocus, scrollTo, selection, moveToEndOfLine, debug } =\n useMemo<UseTextEditorProps>(() => getProviderValue(props), deps ?? []);\n\n // NOTE: Increments by 2 in strict mode.\n const [instanceId] = useState(() => `text-editor-${++instanceCount}`);\n const [view, setView] = useState<EditorView>();\n const parentRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n let view: EditorView;\n if (parentRef.current) {\n log('create', { id, instanceId, doc: initialValue?.length ?? 0 });\n\n let initialSelection;\n if (selection?.anchor && initialValue?.length) {\n if (selection.anchor <= initialValue.length && (selection?.head ?? 0) <= initialValue.length) {\n initialSelection = selection;\n }\n } else if (moveToEndOfLine && selection === undefined) {\n const index = initialValue?.indexOf('\\n');\n const anchor = !index || index === -1 ? 0 : index;\n initialSelection = { anchor };\n }\n\n // https://codemirror.net/docs/ref/#state.EditorStateConfig\n const state = EditorState.create({\n doc: doc ?? initialValue,\n // selection: initialSelection,\n extensions: [\n id && documentId.of(id),\n extensions,\n // NOTE: This doesn't catch errors in keymap functions.\n EditorView.exceptionSink.of((err) => {\n log.catch(err);\n }),\n // TODO(burdon): Factor out debug inspector.\n // ViewPlugin.fromClass(\n // class {\n // constructor(_view: EditorView) {\n // log('construct', { id });\n // }\n //\n // destroy() {\n // log('destroy', { id });\n // }\n // },\n // ),\n ].filter(isNotFalsy),\n });\n\n // https://codemirror.net/docs/ref/#view.EditorViewConfig\n view = new EditorView({\n parent: parentRef.current,\n state,\n scrollTo: scrollTo ? EditorView.scrollIntoView(scrollTo, { yMargin: 96 }) : undefined, // TODO(burdon): Const.\n dispatchTransactions: debug ? debugDispatcher : undefined,\n });\n\n // Move to end of line after document loaded (unless selection is specified).\n if (moveToEndOfLine && !initialSelection) {\n const { to } = view.state.doc.lineAt(0);\n if (to) {\n view.dispatch({ selection: { anchor: to } });\n }\n }\n\n setView(view);\n }\n\n return () => {\n log('destroy', { id });\n view?.destroy();\n };\n }, deps);\n\n useEffect(() => {\n if (view) {\n if (scrollTo || selection) {\n if (selection && selection.anchor > view.state.doc.length) {\n log.warn('invalid selection', { length: view.state.doc.length, scrollTo, selection });\n return;\n }\n\n view.dispatch(createEditorStateTransaction({ scrollTo, selection }));\n }\n }\n }, [view, scrollTo, selection]);\n\n useEffect(() => {\n if (view && autoFocus) {\n view.focus();\n }\n }, [autoFocus, view]);\n\n const focusableGroupAttrs = useFocusableGroup({\n tabBehavior: 'limited',\n ignoreDefaultKeydown: {\n Escape: view?.state.facet(editorInputMode).noTabster,\n },\n });\n\n // Focus editor on Enter (e.g., when tabbing to this component).\n const handleKeyUp = useCallback<KeyboardEventHandler<HTMLDivElement>>(\n (event) => {\n const { key, target, currentTarget } = event;\n if (target === currentTarget) {\n switch (key) {\n case 'Enter': {\n view?.focus();\n break;\n }\n }\n }\n },\n [view],\n );\n\n return {\n parentRef,\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ui_menu", "import_state", "import_view", "import_automerge", "import_log", "import_react_ui", "import_async", "import_context", "import_invariant", "import_lodash", "import_util", "import_autocomplete", "import_commands", "import_language", "import_react_ui_theme", "import_lang_markdown", "import_highlight", "import_search", "import_react_context", "translationKey", "useEditorToolbarState", "initialState", "useMemo", "live", "createEditorAction", "id", "invoke", "properties", "label", "ns", "rest", "createMenuAction", "createEditorActionGroup", "props", "icon", "createMenuItemGroup", "iconOnly", "annotationMark", "Decoration", "mark", "class", "annotations", "match", "ViewPlugin", "fromClass", "decorations", "none", "update", "builder", "RangeSetBuilder", "from", "to", "view", "viewport", "text", "state", "doc", "sliceString", "matches", "matchAll", "m", "index", "undefined", "start", "end", "length", "add", "finish", "v", "EditorView", "theme", "textDecoration", "textDecorationStyle", "textDecorationColor", "autocomplete", "activateOnTyping", "override", "onSearch", "extensions", "keymap", "of", "completionKeymap", "autocompletion", "push", "markdownLanguage", "data", "context", "matchBefore", "explicit", "options", "toLowerCase", "cursorConverter", "accessor", "toCursor", "pos", "assoc", "err", "log", "catch", "fromCursor", "cursor", "getPath", "field", "path", "getLastHeads", "lastHeads", "updateHeadsEffect", "StateEffect", "define", "updateHeads", "newHeads", "reconcileAnnotation", "Annotation", "isReconcile", "tr", "annotation", "updateAutomerge", "handle", "transactions", "hasChanges", "changes", "iterChanges", "changeAt", "invertedTransactions", "fromA", "toA", "_fromB", "_toB", "insert", "del", "reverse", "forEach", "A", "splice", "slice", "toString", "updateCodeMirror", "selection", "target", "patches", "patch", "changeSpec", "handlePatch", "changeSet", "ChangeSet", "map", "dispatch", "action", "handleInsert", "handleSplice", "handleDel", "handlePut", "charPath", "values", "value", "join", "textPath", "candidatePath", "i", "Syncer", "_handle", "_state", "_pending", "reconcile", "editor", "onEditorChange", "onAutomergeChange", "unreconciledTransactions", "filter", "tx", "effects", "oldHeads", "getHeads", "diff", "equals", "singleValueFacet", "defaultValue", "Facet", "combine", "providers", "overlap", "a", "b", "defaultCursorConverter", "position", "parseInt", "Cursor", "converter", "getCursorFromRange", "range", "facet", "getRangeFromCursor", "parts", "split", "wrapWithCatch", "fn", "args", "callbackWrapper", "debugDispatcher", "trs", "logChanges", "flatMap", "empty", "fromB", "toB", "inserted", "JSON", "stringify", "Boolean", "flattenRect", "rect", "left", "x", "right", "top", "bottom", "scratchRange", "textRange", "node", "document", "createRange", "setEnd", "setStart", "clientRectsFor", "dom", "nodeType", "nodeValue", "getClientRects", "createElement", "tag", "children", "el", "className", "textContent", "append", "Array", "isArray", "renderRoot", "root", "createRoot", "render", "React", "ThemeProvider", "defaultTx", "createRenderer", "Component", "Tooltip", "Provider", "automerge", "syncState", "StateField", "create", "result", "clearUnreconciled", "effect", "is", "syncer", "_view", "_handleChange", "addListener", "destroy", "removeListener", "updateListener", "dummyProvider", "remoteStateChange", "Event", "open", "close", "getRemoteStates", "awarenessProvider", "RemoteSelectionChangedAnnotation", "awareness", "provider", "RemoteSelectionsDecorator", "styles", "_ctx", "Context", "RangeSet", "_cursorConverter", "_provider", "on", "dispose", "_updateLocalSelection", "_updateRemoteSelections", "hasFocus", "ownerDocument", "anchor", "head", "main", "_lastAnchor", "_lastHead", "awarenessStates", "Math", "min", "max", "startLine", "lineAt", "endLine", "darkColor", "info", "lightColor", "number", "attributes", "style", "linePos", "line", "widget", "side", "block", "RemoteCaretWidget", "displayName", "set", "WidgetType", "_name", "_color", "toDOM", "span", "backgroundColor", "borderColor", "dot", "innerText", "appendChild", "createTextNode", "updateDOM", "eq", "estimatedHeight", "ignoreEvent", "padding", "margin", "borderLeft", "borderRight", "marginLeft", "marginRight", "boxSizing", "display", "borderRadius", "width", "height", "transition", "transform", "transformOrigin", "fontSize", "fontFamily", "fontStyle", "fontWeight", "lineHeight", "userSelect", "color", "zIndex", "opacity", "transitionDelay", "whiteSpace", "DEBOUNCE_INTERVAL", "SpaceAwarenessProvider", "params", "_remoteStates", "Map", "_space", "space", "_channel", "channel", "_peerId", "peerId", "_info", "_postTask", "DeferredTask", "_localState", "postMessage", "kind", "sleep", "onDispose", "listen", "message", "payload", "_handleQueryMessage", "_handlePostMessage", "debug", "invariant", "schedule", "emit", "defaultOptions", "maxParticles", "particleGravity", "particleAlphaFadeout", "particleSize", "particleNumRange", "particleVelocityRange", "y", "particleShrinkRate", "shakeIntensity", "blast", "blaster", "last", "getPoint", "coordsForChar", "element", "elementFromPoint", "offsetLeft", "offsetTop", "scrollDOM", "parentElement", "point", "Blaster", "defaultsDeep", "random", "initialize", "resize", "current", "spawn", "any", "_", "event", "key", "shiftKey", "shake", "time", "_node", "_options", "_running", "_shakeTime", "_shakeTimeMax", "_particles", "_particlePointer", "_lastPoint", "throttle", "getRGBComponents", "numParticles", "dir", "_effect", "Effect1", "Effect2", "_canvas", "pointerEvents", "getContext", "parent", "stop", "remove", "offsetWidth", "offsetHeight", "loop", "clearRect", "now", "Date", "getTime", "_lastTime", "dt", "magnitude", "shakeX", "shakeY", "drawParticles", "requestAnimationFrame", "bind", "particle", "alpha", "size", "Effect", "vx", "vy", "ctx", "fillStyle", "fillRect", "round", "theta", "PI", "drag", "wander", "sin", "cos", "beginPath", "arc", "fill", "callback", "limit", "wait", "apply", "setTimeout", "bgColor", "getComputedStyle", "commandConfig", "commandState", "closeEffect", "renderDialog", "openEffect", "fullWidth", "tooltip", "above", "arrow", "strictSide", "tooltipView", "mount", "paddingLeft", "paddingRight", "window", "widthWithoutPadding", "clientWidth", "parseFloat", "onAction", "type", "focus", "provide", "showTooltip", "openCommand", "closeCommand", "commandKeyBindings", "preventDefault", "run", "hint", "delay", "onHint", "timeout", "clearTimeout", "cState", "Hint", "plugin", "content", "wrap", "setAttribute", "coordsAt", "rects", "firstChild", "parentNode", "direction", "command", "Prec", "highest", "focusChangeEffect", "focusing", "background", "isNonNullable", "placeholder", "activeLine", "isEmpty", "trim", "lineStart", "Placeholder", "contentAttributes", "cloneNode", "commandMenu", "commandMenuPlugin", "activeRange", "trigger", "commandMenuState", "shouldShowWidget", "tagName", "activeRangeChanged", "some", "commandRangeEffect", "sliceDoc", "onTextChange", "triggers", "commandKeymap", "onEnter", "onArrowDown", "onArrowUp", "firstChar", "shouldRemove", "nextRange", "docChanged", "onClose", "Object", "assign", "newValue", "floatingMenu", "container", "button", "classList", "handler", "scheduleUpdate", "cleanup", "addEventListener", "rafId", "cancelAnimationFrame", "dataset", "focused", "focusChanged", "geometryChanged", "selectionSet", "viewportChanged", "updateButtonPosition", "contentDOM", "getBoundingClientRect", "lineBlockAt", "coords", "coordsAtPos", "dy", "border", "alignItems", "justifyContent", "useCommandMenu", "viewRef", "getMenu", "triggerRef", "useRef", "currentRef", "groupsRef", "currentItem", "setCurrentItem", "useState", "setOpen", "refresh", "handleOpenChange", "useCallback", "handleActivate", "item", "getItem", "triggerKey", "getAttribute", "handleSelect", "onSelect", "serializedTrigger", "_commandMenu", "next", "getNextItem", "previous", "getPreviousItem", "firstItem", "group", "items", "ref", "onActivate", "onOpenChange", "typeahead", "onComplete", "complete", "EditorSelection", "str", "staticCompletion", "completions", "defaultCompletion", "words", "word", "at", "completion", "matchCompletion", "startsWith", "documentId", "stateRestoreAnnotation", "createEditorStateTransaction", "scrollTo", "scrollIntoView", "yMargin", "Transaction", "userEvent", "createEditorStateStore", "keyPrefix", "getState", "localStorage", "parse", "setState", "setItem", "selectionState", "setStateDebounced", "debounce", "isUserEvent", "scrollTop", "posAtCoords", "isNotFalsy", "setComments", "setSelection", "setCommentState", "commentsState", "comments", "commentStates", "comment", "createCommentMark", "isCurrent", "commentsDecorations", "compute", "sortBy", "warn", "commentClickedEffect", "handleCommentClick", "domEventHandlers", "click", "editorRoot", "hasAttribute", "commentId", "trackPastedComments", "onUpdate", "tracked", "handleTrack", "selectedRanges", "cut", "copy", "invertedEffects", "startState", "iterChangedRanges", "restoreCommentEffect", "restore", "j", "mapTrackedComment", "paste", "find", "found", "indexOf", "mapPos", "moved", "exists", "c", "createComment", "optionsFacet", "onCreate", "location", "shortcut", "renderTooltip", "hoverTooltip", "offset", "hoverTime", "mod", "from2", "to2", "newRange", "onDelete", "Infinity", "closest", "d", "abs", "scrollThreadIntoView", "center", "currentSelection", "currentScrollPosition", "targetScrollPosition", "needsScroll", "clientHeight", "needsSelectionUpdate", "flat", "ExternalCommentSync", "subscribe", "getComments", "unsubscribe", "updateComments", "queueMicrotask", "createExternalCommentSync", "useComments", "useEffect", "debugNodeLogger", "console", "logTokens", "syntaxTree", "iterate", "enter", "dropFile", "dropCursor", "drop", "files", "dataTransfer", "onDrop", "focusEffect", "focusField", "blur", "headings", "code", "codeMark", "heading", "level", "mx", "getToken", "get", "tokens", "fontBody", "fontMono", "defaultTheme", "outline", "overflowY", "minWidth", "alignContent", "paddingInline", "textDecorationLine", "textDecorationThickness", "textUnderlineOffset", "marginTop", "borderTop", "maxHeight", "borderBottom", "all", "editorWidth", "editorSlots", "scroll", "editorGutter", "editorMonospace", "editorWithToolbarLayout", "stackItemContentEditorClassNames", "role", "preventNewline", "EditorState", "transactionFilter", "newDoc", "lines", "defaultBasicOptions", "allowMultipleSelections", "bracketMatching", "closeBrackets", "drawSelection", "history", "lineWrapping", "search", "keymaps", "standard", "standardKeymap", "default", "defaultKeymap", "createBasicExtensions", "_props", "exceptionSink", "cursorBlinkRate", "editable", "highlightActiveLine", "lineNumbers", "monospace", "readOnly", "scrollPastEnd", "tabSize", "indentWithTab", "closeBracketsKeymap", "historyKeymap", "searchKeymap", "defaultThemeSlots", "createThemeExtensions", "themeMode", "syntaxHighlighting", "_syntaxHighlighting", "slots", "_slots", "darkTheme", "baseTheme", "merge", "oneDarkHighlightStyle", "defaultHighlightStyle", "editorAttributes", "createDataExtensions", "identity", "identityKey", "toHex", "hue", "profile", "hexToHue", "generateName", "folding", "codeFolding", "placeholderDOM", "foldGutter", "markerDOM", "Icon", "classNames", "TagWidget", "_text", "getHashColor", "tagMatcher", "MatchDecorator", "regexp", "decoration", "replace", "hashtag", "tags", "createDeco", "updateDeco", "instance", "atomicRanges", "createJsonExtensions", "schema", "lintSource", "jsonParseLinter", "ajv", "Ajv", "allErrors", "strict", "validate", "compile", "schemaLinter", "json", "linter", "jsonText", "jsonData", "valid", "errors", "severity", "instancePath", "listener", "onFocus", "onChange", "formattingEquals", "blockType", "strong", "emphasis", "strikethrough", "link", "listStyle", "blockQuote", "Inline", "List", "setHeading", "ranges", "prevBlock", "sawBlock", "hasOwn", "Textblocks", "name", "isHeading", "exec", "curLevel", "repeat", "nextLine", "test", "setStyle", "enable", "marker", "inlineMarkerText", "changeByRange", "after", "before", "changesAtEnd", "blockStart", "blockEnd", "startCovered", "endCovered", "blockContentStart", "blockContentEnd", "IgnoreInline", "has", "InlineMarker", "markType", "openEnd", "closeStart", "skipMarkers", "skipSpaces", "leave", "rangeStart", "rangeEnd", "concat", "addStyle", "removeStyle", "toggleStyle", "arg", "form", "getFormatting", "toggleStrong", "toggleEmphasis", "toggleStrikethrough", "toggleInlineCode", "atx", "setext", "lastLine", "tree", "resolve", "moveTo", "snippets", "codeblock", "snippet", "table", "insertTable", "removeLinkInner", "removeLink", "addLink", "url", "image", "cutStyles", "okay", "sNode", "lastChild", "changesAfter", "cursorOffset", "addList", "lastBlock", "counter", "first", "parentColumn", "blocks", "prevSibling", "itemLine", "itemText", "nodeFrom", "String", "column", "num", "nextSibling", "renumberListItems", "removeList", "stack", "targetNodeType", "pop", "toggleList", "formatting", "active", "newNum", "setBlockquote", "prevLine", "quote", "addBlockquote", "removeBlockquote", "toggleBlockquote", "addCodeblock", "blockFrom", "blockTo", "removeCodeblock", "firstLine", "toggleCodeblock", "formattingKeymap", "Emphasis", "StrongEmphasis", "InlineCode", "Strikethrough", "Set", "ATXHeading1", "ATXHeading2", "ATXHeading3", "ATXHeading4", "ATXHeading5", "ATXHeading6", "CodeBlock", "FencedCode", "Paragraph", "SetextHeading1", "SetextHeading2", "TableCell", "Task", "inline", "currentBlock", "advanceInline", "upto", "skipInline", "contextSize", "contextBefore", "contextAfter", "ch", "blockCode", "hasList", "hasQuote", "blankLine", "useFormattingState", "entries", "processEditorPayload", "inlineType", "listType", "Strong", "Code", "Ordered", "Bullet", "markdownTags", "Blockquote", "Tag", "CodeMark", "CodeText", "EmphasisMark", "HeaderMark", "LinkLabel", "LinkReference", "ListMark", "QuoteMark", "URL", "Table", "defineNodes", "markdownTagsExtensions", "styleTags", "markdownHighlightStyle", "HighlightStyle", "keyword", "deleted", "character", "propertyName", "macroName", "constant", "definition", "separator", "typeName", "changed", "modifier", "self", "namespace", "operator", "operatorKeyword", "escape", "special", "string", "meta", "atom", "bool", "variableName", "processingInstruction", "invalid", "function", "labelName", "heading1", "heading2", "heading3", "heading4", "heading5", "heading6", "scope", "createMarkdownExtensions", "markdown", "base", "codeLanguages", "languages", "completeHTMLTags", "debugTree", "cb", "convertTreeToJson", "treeToJson", "adjustChanges", "adjustments", "resolveInner", "endsWith", "getValidUrl", "invalidPositions", "replacedText", "createLink", "replacement", "host", "pathname", "extension", "imageExtensions", "includes", "createLinkLabel", "protocol", "validProtocols", "_err", "buildDecorations", "oldCursor", "filterFrom", "filterTo", "urlNode", "getChild", "hide", "preloadImage", "ImageWidget", "preloaded", "img", "src", "_url", "other", "onload", "bulletListIndentationWidth", "orderedListIndentationWidth", "formattingStyles", "verticalAlign", "textAlign", "fontVariant", "borderTopLeftRadius", "borderTopRightRadius", "borderBottomLeftRadius", "borderBottomRightRadius", "transitionDuration", "transitionProperty", "overflow", "tables", "getTable", "getRow", "rows", "header", "row", "TableWidget", "_table", "div", "cell", "th", "body", "td", "e", "Unicode", "emDash", "bullet", "bulletSmall", "bulletSquare", "HorizontalRuleWidget", "LinkButton", "CheckboxWidget", "_checked", "input", "tabIndex", "checked", "onmousedown", "posAtDOM", "TextWidget", "fencedCodeLine", "fencedCodeLineFirst", "fencedCodeLineLast", "commentBlockLine", "commentBlockLineFirst", "commentBlockLineLast", "horizontalRule", "checkedTask", "uncheckedTask", "editingRange", "autoHideTags", "deco", "atomicDeco", "headerLevels", "getHeaderLevels", "len", "listLevels", "enterList", "leaveList", "getCurrentListLevel", "enterNode", "headers", "numberedHeadings", "editing", "list", "listPaddingLeft", "quoteMark", "paragraph", "viewportLineBlocks", "isFirst", "isLast", "marks", "getChildren", "href", "rel", "renderLinkButton", "leaveNode", "visibleRanges", "forceUpdate", "decorateMarkdown", "selectionChangeDelay", "clearUpdate", "pendingUpdate", "linkTooltip", "syntax", "urlText", "tooltipContent", "mention", "closeOnBlur", "icons", "EditorViewModes", "EditorViewMode", "Schema", "Union", "mode", "Literal", "EditorInputModes", "EditorInputMode", "editorInputMode", "InputModeExtensions", "vscode", "vscodeKeymap", "vim", "noTabster", "itemToJSON", "lineRange", "contentRange", "Tree", "toJSON", "traverse", "itemOrCb", "maybeCb", "prev", "lastDescendant", "getRange", "t", "child", "getListItemContent", "listItemToString", "indent", "n", "p", "format", "toUpperCase", "k", "padStart", "replaceAll", "treeFacet", "outlinerTree", "buildTree", "prevSiblings", "docRange", "getSelection", "selectionEquals", "every", "selectionFacet", "selectionCompartment", "Compartment", "selectNone", "reconfigure", "selectAll", "selectUp", "selectDown", "indentItemMore", "indentMore", "indentItemLess", "indentUnit", "getIndentUnit", "moveItemDown", "currentContent", "nextContent", "moveItemUp", "prevContent", "deleteItem", "toggleTask", "commands", "shift", "LIST_ITEM_REGEX", "prevItem", "cancel", "startTree", "startItem", "deleteLine", "outliner", "updateDecorations", "selectionChanged", "mainIndex", "lineNum", "lineFrom", "lineTo", "isSelected", "borderLeftWidth", "borderRightWidth", "borderTopWidth", "paddingTop", "borderBottomWidth", "paddingBottom", "marginBottom", "preview", "getLinkRef", "suggest", "PreviewInlineWidget", "addBlockContainer", "removeBlockContainer", "PreviewBlockWidget", "_link", "defaultItems", "typewriter", "idx", "createBlockGroupAction", "variant", "selectCardinality", "createBlockActions", "getView", "blockquote", "disabled", "createBlocks", "blockGroupAction", "blockActions", "nodes", "edges", "source", "formats", "createFormattingGroup", "keys", "createFormattingActions", "createFormatting", "formattingGroupAction", "formattingActions", "createHeadingGroupAction", "applyActive", "createHeadingActions", "levelStr", "count", "computeHeadingValue", "createHeadings", "headingValue", "headingGroupAction", "headingActions", "createImageUploadAction", "onImageUpload", "testId", "createImageUpload", "listStyles", "ordered", "task", "createListGroupAction", "createListActions", "createLists", "listGroupAction", "listActionsMap", "createSearchAction", "openSearchPanel", "createSearch", "createViewModeGroupAction", "createViewModeActions", "onViewModeChange", "readonly", "viewMode", "createViewMode", "viewModeGroupAction", "viewModeActions", "createToolbar", "customActions", "features", "Rx", "make", "rxFromSignal", "lists", "editorToolbarGap", "createGapSeparator", "custom", "useEditorToolbarActionGraph", "menuCreator", "useMenuActions", "EditorToolbar", "memo", "attendableId", "menuProps", "ElevationProvider", "elevation", "MenuProvider", "ToolbarMenu", "textBlockWidth", "CommandMenu", "groups", "useThemeContext", "groupsWithItems", "Popover", "Portal", "Content", "align", "onOpenAutoFocus", "Viewport", "ul", "Fragment", "CommandGroup", "useTranslation", "toLocalizedString", "CommandItem", "behavior", "li", "onClick", "findIndex", "filterItems", "insertAtCursor", "insertAtLineStart", "coreSlashCommands", "linkSlashCommands", "customEventOptions", "capture", "passive", "RefPopover", "forwardRef", "modal", "rootRef", "setRootRef", "Root", "VirtualTrigger", "virtualRef", "REF_POPOVER", "RefPopoverContextProvider", "useRefPopover", "createContext", "PreviewProvider", "onLookup", "setValue", "handleDxRefTagActivate", "refId", "dxTrigger", "pending", "then", "REF_DROPDOWN_MENU", "RefDropdownMenuContextProvider", "useRefDropdownMenu", "RefDropdownMenuProvider", "DropdownMenu", "RefDropdownMenu", "instanceCount", "useTextEditor", "deps", "initialValue", "autoFocus", "moveToEndOfLine", "getProviderValue", "instanceId", "setView", "parentRef", "initialSelection", "dispatchTransactions", "focusableGroupAttrs", "useFocusableGroup", "tabBehavior", "ignoreDefaultKeydown", "Escape", "handleKeyUp", "currentTarget", "focusAttributes", "onKeyUp"]
|
7
|
-
}
|