Skip to content

some ideas for making placeholders read only #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,15 @@ const App = () => {
"description": "You can add your own variable resolutions!"
},
"Insert Multiple Tab Stops": {
"prefix": "tabstops",
"prefix": "tab",
"body": "This $1 snippet $2 contains multiple tab $3 stops"
},
"Insert Placeholders in any order": {
"prefix": "placeholders",
"body": "This \${2:snippet} \${1:contains} multiple \${3:placeholders}"
"prefix": "phs",
"body": "This \${1:snippet} \${2:contains}"
},
"Insert multiple lines": {
"prefix": "placeholders",
"prefix": "mls",
"body": ["this snippet $0", "\${1:contains} a couple", "lines of text!"]
},
"ROS": {
Expand Down
49 changes: 37 additions & 12 deletions src/SnippetSession.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Editor, Range, RangeRef, Transforms } from 'slate';
import { PlaceholderDecorationRange } from './customTypes';
import { isPointAtBlockStart } from './slateHelpers';
import {
Placeholder,
Expand Down Expand Up @@ -33,8 +34,10 @@ export class SnippetSession {
this._placeholders.sort(Placeholder.compareByIndex);
this._placeholderRanges = new Map();
this._placeholderIdx = -1;
Transforms.insertFragment(this._editor, this._snippet.toFragment(), {
const fragment = this._snippet.toFragment();
Transforms.insertFragment(this._editor, fragment, {
at: this._range.current!,
voids: true,
});

this._placeholders.forEach(placeholder => {
Expand All @@ -49,6 +52,7 @@ export class SnippetSession {
: Editor.after(this._editor, range.anchor, {
distance: placeholderStartOffset,
unit: 'character',
voids: true,
});

// this fixes a bug when the user inserts a snippet which starts with a placeholder
Expand All @@ -65,6 +69,7 @@ export class SnippetSession {
anchor = Editor.after(this._editor, anchor, {
distance: 1,
unit: 'offset',
voids: true,
});
}

Expand All @@ -74,6 +79,7 @@ export class SnippetSession {
: Editor.after(this._editor, range.anchor, {
distance: placeholderEndOffset,
unit: 'character',
voids: true,
});

if (anchor === undefined || focus === undefined) {
Expand Down Expand Up @@ -102,14 +108,10 @@ export class SnippetSession {
const nextPlaceholder = this._placeholders[this._placeholderIdx];
const nextRange = this._placeholderRanges!.get(nextPlaceholder)!.current!;

Transforms.select(this._editor, {
anchor: Editor.after(this._editor, nextRange.anchor, {
unit: 'character',
})!,
focus: Editor.before(this._editor, nextRange.focus, {
unit: 'character',
})!,
});
Transforms.select(
this._editor,
this.transformPlaceholderRangeToSelectionRange(nextRange)
);

if (nextPlaceholder.isFinalTabstop) {
this.dispose();
Expand All @@ -120,19 +122,42 @@ export class SnippetSession {
return { done: false };
}

public transformPlaceholderRangeToSelectionRange<T extends Range>(
nextRange: T
): T {
return {
...nextRange,
anchor: Editor.after(this._editor, nextRange.anchor, {
unit: 'character',
voids: true,
})!,
focus: Editor.before(this._editor, nextRange.focus, {
unit: 'character',
voids: true,
})!,
};
}

public dispose() {
for (let rangeRef of this._placeholderRanges?.values() ?? []) {
rangeRef.unref();
}
}

public get placeholderRanges() {
public get placeholderRanges(): PlaceholderDecorationRange[] {
const ranges = this._placeholders
.map(placeholder => {
const rangeRef = this._placeholderRanges!.get(placeholder);
return rangeRef;
return { rangeRef, placeholder };
})
.map(rangeRef => rangeRef!.current!);
.map(({ rangeRef, placeholder }) => {
const decorationRange: PlaceholderDecorationRange = {
...rangeRef!.current!,
type: 'PlaceholderDecorationRange',
isFinalTabStop: placeholder.isFinalTabstop,
};
return decorationRange;
});
return ranges;
}
}
42 changes: 42 additions & 0 deletions src/components/PlaceholderDecoration.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React from 'react';
import { RenderLeafProps } from 'slate-react';
import { PlaceholderDecorationText } from '../customTypes';

export const PlaceholderDecoration = ({
attributes,
children,
leaf,
text,
placeholderColor,
}: Omit<RenderLeafProps, 'leaf' | 'text'> & {
leaf: PlaceholderDecorationText;
text: PlaceholderDecorationText;
placeholderColor: string;
}) => {
if (leaf.text.replaceAll('\u200B', '').length === 0) {
return (
<span
style={{
padding: '0px 1px',
border: `2px solid ${
leaf.isFinalTabStop ? 'grey' : placeholderColor
}`,
display: 'inline-block',
minWidth: '2ch',
}}
>
{children}
</span>
);
}
return (
<span
style={{
padding: '0px 1px',
border: `2px solid ${leaf.isFinalTabStop ? 'grey' : placeholderColor}`,
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

final tab stop styling should be parameterized, also styling for empty/non empty placeholders should be parameterized

}}
>
{children}
</span>
);
};
33 changes: 33 additions & 0 deletions src/components/SnippetReadonlyText.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React from 'react';
import { RenderElementProps, useFocused, useSelected } from 'slate-react';
import { SnippetReadonlyTextElement } from '../customTypes';

export const SnippetReadonlyText = ({
attributes,
children,
element,
}: Omit<RenderElementProps, 'element'> & {
element: SnippetReadonlyTextElement;
}) => {
const selected = useSelected();
const focused = useFocused();
return (
<span
{...attributes}
contentEditable={false}
style={{
padding: '3px 3px 2px',
margin: '0 1px',
verticalAlign: 'baseline',
display: 'inline-block',
borderRadius: '4px',
backgroundColor: '#eee',
fontSize: '0.9em',
boxShadow: selected && focused ? '0 0 0 2px #B4D5FF' : 'none',
Comment on lines +18 to +26
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

styling for read only snippet should be parameterized

}}
>
{element.label}
{children}
</span>
);
};
14 changes: 13 additions & 1 deletion src/customTypes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { BaseRange, BaseText } from 'slate';
import { BaseElement, BaseRange, BaseText } from 'slate';

export type PlaceholderDecorationRange = {
type: 'PlaceholderDecorationRange';
isFinalTabStop: boolean;
} & BaseRange;

export type DefaultRange = {
Expand All @@ -10,15 +11,26 @@ export type DefaultRange = {

export type PlaceholderDecorationText = {
type: 'PlaceholderDecorationRange';
isFinalTabStop: boolean;
} & BaseText;

export type DefaultText = {
type?: undefined;
} & BaseText;

export type SnippetReadonlyTextElement = {
type: 'SnippetReadonlyText';
label: string;
} & BaseElement;

export type DefaultElement = {
type?: undefined;
} & BaseElement;

declare module 'slate' {
interface CustomTypes {
Range: PlaceholderDecorationRange | DefaultRange;
Text: PlaceholderDecorationText | DefaultText;
Element: SnippetReadonlyTextElement | DefaultElement;
}
}
8 changes: 5 additions & 3 deletions src/slateHelpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ export const isSelectionCollapsed = (s: Selection): s is Selection => {
return s !== null && Range.isCollapsed(s);
};

const getEditorText = (e: Editor, at?: Location | null) => {
export const getEditorText = (e: Editor, at?: Location | null) => {
if (at !== null && at !== undefined) {
return Editor.string(e, at);
return Editor.string(e, at, { voids: true });
}
return '';
};
Expand All @@ -53,6 +53,7 @@ export const isPointAtBlockStart = (e: Editor, point: Point) => {
const [_, path] = Editor.above(e, {
at: point,
match: n => Editor.isBlock(e, n),
voids: true,
}) ?? [undefined, undefined];
return path !== undefined && Editor.isStart(e, point, path);
};
Expand All @@ -66,7 +67,7 @@ export const matchesTriggerAndPattern = (
{ at, trigger, pattern }: { at: Point; trigger: string; pattern: string }
) => {
// Point at the start of line
const lineStart = Editor.before(editor, at, { unit: 'line' });
const lineStart = Editor.before(editor, at, { unit: 'line', voids: true });

// Range from before to start
const beforeRange = lineStart && Editor.range(editor, lineStart, at);
Expand All @@ -87,6 +88,7 @@ export const matchesTriggerAndPattern = (
? Editor.before(editor, at, {
unit: 'character',
distance: match[1].length + trigger.length,
voids: true,
})
: null;

Expand Down
60 changes: 36 additions & 24 deletions src/slateSnippetsExtension.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import isHotkey from 'is-hotkey';
import React, { useCallback, useState } from 'react';
import { Editor, Node, Range, Text, Transforms } from 'slate';
import { SlateExtension } from 'use-slate-with-extensions';
import { PlaceholderDecorationRange } from './customTypes';
import { PlaceholderDecoration } from './components/PlaceholderDecoration';
import { SnippetReadonlyText } from './components/SnippetReadonlyText';
import {
isPointAtWordEnd,
isRangeContained,
Expand Down Expand Up @@ -43,45 +44,56 @@ export const useSlateSnippetsExtension = (
}, [snippetSession]);

return {
isVoid: (element, editor, next) => {
if (element.type === 'SnippetReadonlyText') {
return true;
}

return next(element, editor);
},
isVoidDeps: [],
isInline: (element, editor, next) => {
if (element.type === 'SnippetReadonlyText') {
return true;
}
return next(element, editor);
},
isInlineDeps: [],
decorate: ([node, path], editor) => {
if (snippetSession !== undefined && Text.isText(node)) {
const [start, end] = Editor.edges(editor, path);
const nodeRange = { anchor: start, focus: end };

const placeholderRanges = snippetSession.placeholderRanges
.map(placeholderRange =>
snippetSession.transformPlaceholderRangeToSelectionRange(
placeholderRange
)
)
.filter(placeholderRange =>
isRangeContained(nodeRange, placeholderRange)
)
.map(r => {
const decorationRange: PlaceholderDecorationRange = {
...r,
type: 'PlaceholderDecorationRange',
};
return decorationRange;
});
);

return placeholderRanges;
}
return undefined;
},
decorateDeps: [snippetSession],
renderElement: props => {
const { element } = props;
if (element.type === 'SnippetReadonlyText') {
return <SnippetReadonlyText {...(props as any)} />;
}
return undefined;
},
renderElementDeps: [],
renderLeaf: props => {
if (props.leaf.type === 'PlaceholderDecorationRange') {
if (props.leaf.text.replaceAll('\u200B', '').length === 0) {
return (
<span
style={{
background: placeholderColor,
display: 'inline-block',
minWidth: '2px',
}}
>
{props.children}
</span>
);
}
return (
<span style={{ background: placeholderColor }}>{props.children}</span>
<PlaceholderDecoration
{...(props as any)}
placeholderColor={placeholderColor}
/>
);
}
return undefined;
Expand Down Expand Up @@ -167,7 +179,7 @@ export const useSlateSnippetsExtension = (
Transforms.insertText(
editor,
Node.string(node).replaceAll('\u200B', ''),
{ at: path }
{ at: path, voids: true }
);
return;
}
Expand Down
13 changes: 12 additions & 1 deletion src/snippetParser/snippetParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,18 @@ export class Text extends Marker {
const isNotLast = i < a.length - 1;
const result: (Descendant | 'line-break')[] = [];
if (v.length > 0) {
result.push({ text: v });
if (
this.parent instanceof Placeholder ||
this.parent instanceof Choice
) {
result.push({ text: v });
} else {
result.push({
children: [{ text: v }],
type: 'SnippetReadonlyText',
label: v,
});
Comment on lines +256 to +260
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should parameterize whether or not snippet text is read only

}
}
if (isNotLast) {
result.push('line-break');
Expand Down