Skip to content

Commit

Permalink
✨ Improved Formatting functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
EvanZhouDev committed Apr 7, 2024
1 parent a167808 commit 63a1c9b
Showing 1 changed file with 56 additions and 22 deletions.
78 changes: 56 additions & 22 deletions src/api/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,25 +266,59 @@ const getChanges = (changeDetails: ChangeDetails) => {
return formatInline(changeDetails)
}

export const format = ([state]: InkInternal.Store, formatType: Ink.EnumString<Ink.Values.Markup>, { selection: maybeSelection }: Ink.Instance.FormatOptions = {}) => {
const { editor } = state()
const formatDefinition = formatting[formatType]
const selection = getSelection({ editor, formatDefinition, selection: maybeSelection })
const node = getNode(editor, formatDefinition, selection)
const changeDetails: ChangeDetails = {
editor,
formatDefinition,
node,
selection,
}
const changes = getChanges(changeDetails)
const offset = changes.reduce((total, change: { from: number, insert: string, to?: number }) => {
const offset = change.insert.length - ((change.to || change.from) - change.from)

return total + offset
}, 0)

const updates = state().editor.state.update({ changes, selection: { head: selection.start, anchor: selection.end + offset } })

state().editor.dispatch(updates)
}
export const format = (
[state]: InkInternal.Store,
formatType: Ink.EnumString<Ink.Values.Markup>,
{ selection: maybeSelection }: Ink.Instance.FormatOptions = {}
) => {
const { editor } = state();
const formatDefinition = formatting[formatType];
const selection = getSelection({
editor,
formatDefinition,
selection: maybeSelection,
});

// Check if the selection is empty
if (selection.start === selection.end) {
// Insert the prefix and suffix around the cursor
const changes = [
{ from: selection.start, insert: formatDefinition.prefix },
{ from: selection.start, insert: formatDefinition.suffix },
];
const cursorPosition = selection.start + formatDefinition.prefix.length;
const updates = state().editor.state.update({
changes,
selection: { head: cursorPosition, anchor: cursorPosition },
});

state().editor.dispatch(updates);
state().editor.focus();
} else {
const node = getNode(editor, formatDefinition, selection);
const changeDetails: ChangeDetails = {
editor,
formatDefinition,
node,
selection,
};
const changes = getChanges(changeDetails);
const offset = changes.reduce(
(total, change: { from: number; insert: string; to?: number }) => {
const offset =
change.insert.length - ((change.to || change.from) - change.from);

return total + offset;
},
0
);

const updates = state().editor.state.update({
changes,
selection: { head: selection.start, anchor: selection.end + offset },
});

state().editor.dispatch(updates);
state().editor.focus();
}
};

0 comments on commit 63a1c9b

Please sign in to comment.