@fastkit/vui 0.7.59 → 0.7.61

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.
@@ -0,0 +1,262 @@
1
+ import './Linter.scss';
2
+
3
+ import { Extension } from '@tiptap/core';
4
+ import { Decoration, DecorationSet } from 'prosemirror-view';
5
+ import { Plugin, PluginKey, TextSelection } from 'prosemirror-state';
6
+ import { Node as ProsemirrorNode } from 'prosemirror-model';
7
+ import { LinterPlugin, LinterResult as Issue } from './LinterPlugin';
8
+ import { debounce } from '@fastkit/helpers';
9
+ import { EditorView } from 'prosemirror-view';
10
+
11
+ const PROBLEM_CLASS_NAME = 'v-linter__problem';
12
+ const ISSUE_ICON_CLASS_NAME = 'v-linter__issue-icon';
13
+ const ISSUE_MENU_CLASS_NAME = 'v-linter__issue-menu';
14
+
15
+ interface IssueElement extends HTMLDivElement {
16
+ issue?: Issue;
17
+ }
18
+
19
+ function renderIcon(view: EditorView<any>, issue: Issue) {
20
+ const { level = 'warning' } = issue;
21
+ const icon: IssueElement = document.createElement('div');
22
+
23
+ icon.className = `${ISSUE_ICON_CLASS_NAME} ${level}-scope`;
24
+ icon.title = issue.message;
25
+ icon.issue = issue;
26
+
27
+ return icon;
28
+ }
29
+
30
+ function renderMenu(view: EditorView<any>, issue: Issue) {
31
+ const menuWrapper = document.createElement('div');
32
+ menuWrapper.className = 'v-linter__issue-menu-wrapper';
33
+ const menu: IssueElement = document.createElement('div');
34
+
35
+ menu.className = `${ISSUE_MENU_CLASS_NAME} elevation-3`;
36
+ menu.innerText = issue.message;
37
+
38
+ const { fix, fixMessage } = issue;
39
+
40
+ if (fix && fixMessage) {
41
+ const $fix = document.createElement('button');
42
+ $fix.type = 'button';
43
+ $fix.innerHTML = fixMessage;
44
+ $fix.addEventListener('click', () => {
45
+ fix(view, issue);
46
+ });
47
+ $fix.className = `v-linter__issue-menu__fix`;
48
+ menu.appendChild($fix);
49
+ }
50
+
51
+ menu.issue = issue;
52
+
53
+ menuWrapper.appendChild(menu);
54
+ return menuWrapper;
55
+ }
56
+
57
+ function getIssueElement(
58
+ source: HTMLElement | EventTarget | null,
59
+ className: string,
60
+ ): IssueElement | undefined {
61
+ if (!source || !(source instanceof HTMLElement)) {
62
+ return;
63
+ }
64
+ if (source.classList.contains(className)) {
65
+ return source as IssueElement;
66
+ }
67
+ const el = source.closest(`.${className}`);
68
+ if (el) {
69
+ return el as IssueElement;
70
+ }
71
+ }
72
+
73
+ function getIconElement(
74
+ source: HTMLElement | EventTarget | null,
75
+ ): IssueElement | undefined {
76
+ return getIssueElement(source, ISSUE_ICON_CLASS_NAME);
77
+ }
78
+
79
+ function getMenuElement(
80
+ source: HTMLElement | EventTarget | null,
81
+ ): IssueElement | undefined {
82
+ return getIssueElement(source, ISSUE_MENU_CLASS_NAME);
83
+ }
84
+
85
+ function getProblemElement(
86
+ source: HTMLElement | EventTarget | null,
87
+ ): IssueElement | undefined {
88
+ return getIssueElement(source, PROBLEM_CLASS_NAME);
89
+ }
90
+
91
+ function runAllLinterPlugins(
92
+ doc: ProsemirrorNode,
93
+ plugins: Array<typeof LinterPlugin>,
94
+ ) {
95
+ const decorations: [any?] = [];
96
+
97
+ const results = plugins
98
+ .map((RegisteredLinterPlugin) => {
99
+ return new RegisteredLinterPlugin(doc).scan().getResults();
100
+ })
101
+ .flat();
102
+
103
+ results.forEach((issue) => {
104
+ const { level = 'warning' } = issue;
105
+ decorations.push(
106
+ Decoration.inline(issue.from, issue.to, {
107
+ class: `${PROBLEM_CLASS_NAME} ${level}-scope`,
108
+ 'data-issue': JSON.stringify(issue),
109
+ title: issue.message,
110
+ }),
111
+ Decoration.widget(issue.from, (view) => renderIcon(view, issue)),
112
+ Decoration.widget(issue.from, (view) => renderMenu(view, issue)),
113
+ );
114
+ });
115
+
116
+ return DecorationSet.create(doc, decorations);
117
+ }
118
+
119
+ export interface LinterOptions {
120
+ plugins: Array<typeof LinterPlugin>;
121
+ }
122
+
123
+ function updateMenusPosition(editorElement: Element) {
124
+ const { left, right } = editorElement.getBoundingClientRect();
125
+ const menus = Array.from(
126
+ editorElement.querySelectorAll(`.${ISSUE_MENU_CLASS_NAME}`),
127
+ );
128
+ menus.forEach((menu) => {
129
+ const { left: menuLeft, right: menuRight } = menu.getBoundingClientRect();
130
+ const overflow = menuRight - right;
131
+ let offset = 0;
132
+ if (overflow > 0) {
133
+ offset = -overflow;
134
+
135
+ if (menuLeft + offset < left) {
136
+ offset = 0;
137
+ }
138
+ }
139
+ (menu as HTMLElement).style.transform = `translateX(${offset}px)`;
140
+ });
141
+ }
142
+
143
+ const debouncedUpdateMenusPosition = debounce(updateMenusPosition, 250);
144
+
145
+ export const Linter = Extension.create<LinterOptions>({
146
+ name: 'linter',
147
+
148
+ addOptions() {
149
+ return {
150
+ plugins: [],
151
+ };
152
+ },
153
+
154
+ onCreate() {
155
+ const { dom } = this.editor.view;
156
+ debouncedUpdateMenusPosition(dom);
157
+ },
158
+
159
+ onUpdate() {
160
+ const { dom } = this.editor.view;
161
+ debouncedUpdateMenusPosition(dom);
162
+ },
163
+
164
+ addProseMirrorPlugins() {
165
+ const { plugins } = this.options;
166
+
167
+ return [
168
+ new Plugin({
169
+ key: new PluginKey('linter'),
170
+ state: {
171
+ init(_, { doc }) {
172
+ return runAllLinterPlugins(doc, plugins);
173
+ },
174
+ apply(transaction, oldState) {
175
+ return transaction.docChanged
176
+ ? runAllLinterPlugins(transaction.doc, plugins)
177
+ : oldState;
178
+ },
179
+ },
180
+ props: {
181
+ decorations(state) {
182
+ return this.getState(state);
183
+ },
184
+ handleClick(view, _, event) {
185
+ const activeMenus = Array.from(
186
+ view.dom.querySelectorAll(`.${ISSUE_MENU_CLASS_NAME}--active`),
187
+ );
188
+
189
+ activeMenus.forEach((menu) =>
190
+ menu.classList.remove(`${ISSUE_MENU_CLASS_NAME}--active`),
191
+ );
192
+
193
+ const problem = getProblemElement(event.target);
194
+
195
+ const issueString = problem && problem.dataset['issue'];
196
+
197
+ const issue = issueString && JSON.parse(issueString);
198
+ if (issue) {
199
+ const menuWrapper = problem.previousElementSibling;
200
+ const menu =
201
+ menuWrapper &&
202
+ menuWrapper.querySelector(`.${ISSUE_MENU_CLASS_NAME}`);
203
+ menu && menu.classList.add(`${ISSUE_MENU_CLASS_NAME}--active`);
204
+
205
+ const { from, to } = issue;
206
+ view.dispatch(
207
+ view.state.tr
208
+ .setSelection(TextSelection.create(view.state.doc, from, to))
209
+ .scrollIntoView(),
210
+ );
211
+
212
+ return true;
213
+ }
214
+
215
+ const menu = getMenuElement(event.target);
216
+
217
+ if (menu) {
218
+ menu.classList.add(`${ISSUE_MENU_CLASS_NAME}--active`);
219
+ }
220
+
221
+ const target = getIconElement(event.target);
222
+
223
+ if (target && target.issue) {
224
+ const menuWrapper = target.nextElementSibling;
225
+ const menu =
226
+ menuWrapper &&
227
+ menuWrapper.querySelector(`.${ISSUE_MENU_CLASS_NAME}`);
228
+ menu && menu.classList.add(`${ISSUE_MENU_CLASS_NAME}--active`);
229
+
230
+ const { from, to } = target.issue;
231
+
232
+ view.dispatch(
233
+ view.state.tr
234
+ .setSelection(TextSelection.create(view.state.doc, from, to))
235
+ .scrollIntoView(),
236
+ );
237
+
238
+ return true;
239
+ }
240
+
241
+ return false;
242
+ },
243
+ handleDoubleClick(view, _, event) {
244
+ const target = getIconElement(event.target);
245
+
246
+ if (target && target.issue) {
247
+ const prob = target.issue;
248
+
249
+ if (prob.fix) {
250
+ prob.fix(view, prob);
251
+ view.focus();
252
+ return true;
253
+ }
254
+ }
255
+
256
+ return false;
257
+ },
258
+ },
259
+ }),
260
+ ];
261
+ },
262
+ });
@@ -0,0 +1,44 @@
1
+ import { Node as ProsemirrorNode } from 'prosemirror-model';
2
+ import { EditorView } from 'prosemirror-view';
3
+
4
+ export type FixFn = (view: EditorView, issue: LinterResult) => any;
5
+
6
+ export type LinterResultLevel = 'warning' | 'error';
7
+
8
+ export interface LinterResult {
9
+ level: LinterResultLevel;
10
+ message: string;
11
+ from: number;
12
+ to: number;
13
+ fix?: FixFn;
14
+ fixMessage?: string;
15
+ }
16
+
17
+ export interface RawLinterResult extends Omit<LinterResult, 'level'> {
18
+ level?: LinterResultLevel;
19
+ }
20
+
21
+ export class LinterPlugin {
22
+ protected doc: ProsemirrorNode;
23
+
24
+ private results: Array<LinterResult> = [];
25
+
26
+ constructor(doc: ProsemirrorNode) {
27
+ this.doc = doc;
28
+ }
29
+
30
+ record(result: RawLinterResult) {
31
+ this.results.push({
32
+ level: 'error',
33
+ ...result,
34
+ });
35
+ }
36
+
37
+ scan() {
38
+ return this;
39
+ }
40
+
41
+ getResults() {
42
+ return this.results;
43
+ }
44
+ }
@@ -0,0 +1,5 @@
1
+ export { Linter } from './Linter';
2
+ export { LinterPlugin } from './LinterPlugin';
3
+ export type { LinterOptions } from './Linter';
4
+
5
+ export * from './plugins';
@@ -0,0 +1,34 @@
1
+ import { LinterPlugin } from '../LinterPlugin';
2
+
3
+ export function BadWords(words: string[]): typeof LinterPlugin {
4
+ const regex = new RegExp(`\\b(${words.join('|')})\\b`);
5
+
6
+ return class BadWords extends LinterPlugin {
7
+ scan() {
8
+ this.doc.descendants((node: any, position: number) => {
9
+ if (!node.isText) {
10
+ return;
11
+ }
12
+
13
+ const matches = regex.exec(node.text);
14
+
15
+ if (matches) {
16
+ const fixValue = matches[0] + '!!!!!';
17
+
18
+ this.record({
19
+ level: 'warning',
20
+ message: `Try not to say '${matches[0]}'`,
21
+ from: position + matches.index,
22
+ to: position + matches.index + matches[0].length,
23
+ fix: () => {
24
+ console.log('hoge');
25
+ },
26
+ fixMessage: `「${fixValue}」に修正する。`,
27
+ });
28
+ }
29
+ });
30
+
31
+ return this;
32
+ }
33
+ };
34
+ }
@@ -0,0 +1,33 @@
1
+ import { EditorView } from 'prosemirror-view';
2
+ import { LinterPlugin, LinterResult as Issue } from '../LinterPlugin';
3
+
4
+ export class HeadingLevel extends LinterPlugin {
5
+ fixHeader(level: number) {
6
+ return function ({ state, dispatch }: EditorView, issue: Issue) {
7
+ dispatch(state.tr.setNodeMarkup(issue.from - 1, undefined, { level }));
8
+ };
9
+ }
10
+
11
+ scan() {
12
+ let lastHeadLevel: number | null = null;
13
+
14
+ this.doc.descendants((node, position) => {
15
+ if (node.type.name === 'heading') {
16
+ // Check whether heading levels fit under the current level
17
+ const { level } = node.attrs;
18
+
19
+ if (lastHeadLevel != null && level > lastHeadLevel + 1) {
20
+ this.record({
21
+ message: `Heading too small (${level} under ${lastHeadLevel})`,
22
+ from: position + 1,
23
+ to: position + 1 + node.content.size,
24
+ fix: this.fixHeader(lastHeadLevel + 1),
25
+ });
26
+ }
27
+ lastHeadLevel = level;
28
+ }
29
+ });
30
+
31
+ return this;
32
+ }
33
+ }
@@ -0,0 +1,43 @@
1
+ import { EditorView } from 'prosemirror-view';
2
+ import { LinterPlugin, LinterResult as Issue } from '../LinterPlugin';
3
+
4
+ export class Punctuation extends LinterPlugin {
5
+ public regex = / ([,.!?:]) ?/g;
6
+
7
+ fix(replacement: any) {
8
+ return function ({ state, dispatch }: EditorView, issue: Issue) {
9
+ dispatch(
10
+ state.tr.replaceWith(
11
+ issue.from,
12
+ issue.to,
13
+ state.schema.text(replacement),
14
+ ),
15
+ );
16
+ };
17
+ }
18
+
19
+ scan() {
20
+ this.doc.descendants((node, position) => {
21
+ if (!node.isText) {
22
+ return;
23
+ }
24
+
25
+ if (!node.text) {
26
+ return;
27
+ }
28
+
29
+ const matches = this.regex.exec(node.text);
30
+
31
+ if (matches) {
32
+ this.record({
33
+ message: 'Suspicious spacing around punctuation',
34
+ from: position + matches.index,
35
+ to: position + matches.index + matches[0].length,
36
+ fix: this.fix(`${matches[1]} `),
37
+ });
38
+ }
39
+ });
40
+
41
+ return this;
42
+ }
43
+ }
@@ -0,0 +1,3 @@
1
+ export { BadWords } from './BadWords';
2
+ export { HeadingLevel } from './HeadingLevel';
3
+ export { Punctuation } from './Punctuation';
@@ -1,3 +1,4 @@
1
1
  export * from './VWysiwygEditor';
2
+ export * from './extensions';
2
3
  export * from './tools';
3
4
  export * from './schemes';
@@ -1,12 +1,116 @@
1
1
  import { type VuiService } from '../../service';
2
- import { type Editor, type Extensions } from '@tiptap/vue-3';
2
+ import {
3
+ type Editor,
4
+ type Extensions,
5
+ type AnyExtension,
6
+ type EditorOptions,
7
+ } from '@tiptap/vue-3';
3
8
  import { type IconName } from '../VIcon';
4
9
 
10
+ const EDITOR_EVENTS = [
11
+ 'beforeCreate',
12
+ 'create',
13
+ 'update',
14
+ 'selectionUpdate',
15
+ 'transaction',
16
+ 'focus',
17
+ 'blur',
18
+ 'destroy',
19
+ ] as const;
20
+
21
+ type PrefixedEventName<S extends string> = `on${Capitalize<S>}`;
22
+
23
+ const prefixedEventName = <S extends string>(
24
+ source: S,
25
+ ): PrefixedEventName<S> => {
26
+ return `on${source.charAt(0).toUpperCase()}${source.slice(1)}` as any;
27
+ };
28
+
29
+ export type WysiwygEditorEvent = typeof EDITOR_EVENTS[number];
30
+
31
+ export type WysiwygEditorPrefixedEvent = PrefixedEventName<WysiwygEditorEvent>;
32
+
33
+ // eslint-disable-next-line @typescript-eslint/no-empty-interface
34
+ export interface WysiwygEditorEventsOptions
35
+ extends Partial<Pick<EditorOptions, WysiwygEditorPrefixedEvent>> {}
36
+
37
+ export type WysiwygEditorEventsBucket = {
38
+ [EV in WysiwygEditorEvent]: NonNullable<
39
+ WysiwygEditorEventsOptions[PrefixedEventName<EV>]
40
+ >[];
41
+ };
42
+
43
+ export class WysiwygEditorInitializeContext {
44
+ readonly listeners: WysiwygEditorEventsBucket = {} as any;
45
+
46
+ constructor(opts: WysiwygEditorEventsOptions = {}) {
47
+ EDITOR_EVENTS.forEach((event) => {
48
+ this.listeners[event] = [];
49
+ const prefixed = prefixedEventName(event);
50
+ const fn = opts[prefixed];
51
+ fn && this.listeners[event].push(fn as any);
52
+ });
53
+ }
54
+
55
+ on<EV extends WysiwygEditorEvent>(
56
+ ev: EV,
57
+ handler: NonNullable<WysiwygEditorEventsOptions[PrefixedEventName<EV>]>,
58
+ ) {
59
+ this.listeners[ev].push(handler);
60
+ return () => this.off(ev, handler);
61
+ }
62
+
63
+ off<EV extends WysiwygEditorEvent>(
64
+ ev: EV,
65
+ handler: NonNullable<WysiwygEditorEventsOptions[PrefixedEventName<EV>]>,
66
+ ) {
67
+ this.listeners[ev] = this.listeners[ev].filter(
68
+ (_handler) => _handler !== handler,
69
+ ) as any;
70
+ }
71
+
72
+ editorOptions() {
73
+ const opts: WysiwygEditorEventsOptions = {};
74
+
75
+ EDITOR_EVENTS.forEach((event) => {
76
+ const prefixed = prefixedEventName(event);
77
+ opts[prefixed] = (props) => {
78
+ const handlers = this.listeners[event];
79
+ handlers.forEach((handler) => {
80
+ handler(props as any);
81
+ });
82
+ };
83
+ });
84
+
85
+ return opts;
86
+ }
87
+ }
88
+
5
89
  export interface WysiwygEditorContext {
6
90
  editor: Editor;
7
91
  vui: VuiService;
8
92
  }
9
93
 
94
+ export type WysiwygExtensionFactory = (
95
+ ctx: WysiwygEditorInitializeContext,
96
+ ) => AnyExtension;
97
+
98
+ export type RawWysiwygExtension = AnyExtension | WysiwygExtensionFactory;
99
+
100
+ function resolveRawWysiwygExtension(
101
+ raw: RawWysiwygExtension,
102
+ ctx: WysiwygEditorInitializeContext,
103
+ ): AnyExtension {
104
+ return typeof raw === 'function' ? raw(ctx) : raw;
105
+ }
106
+
107
+ export function resolveRawWysiwygExtensions(
108
+ raws: RawWysiwygExtension[],
109
+ ctx: WysiwygEditorInitializeContext,
110
+ ) {
111
+ return raws.map((raw) => resolveRawWysiwygExtension(raw, ctx));
112
+ }
113
+
10
114
  export interface WysiwygEditorTool {
11
115
  key: string;
12
116
  icon: IconName | ((ctx: WysiwygEditorContext) => IconName);
@@ -39,13 +143,13 @@ export interface ResolvedWysiwygEditorSettings {
39
143
  }
40
144
 
41
145
  export function resolveRawWysiwygEditorTools(
42
- raws: RawWysiwygEditorTool[],
146
+ rawTools: RawWysiwygEditorTool[],
43
147
  vui: VuiService,
44
148
  ): ResolvedWysiwygEditorSettings {
45
149
  const tools: WysiwygEditorTool[] = [];
46
150
  const extensions: Extensions = [];
47
151
 
48
- raws.forEach((raw) => {
152
+ rawTools.forEach((raw) => {
49
153
  let resolved = resolveRawWysiwygEditorTool(raw, vui);
50
154
  if (!Array.isArray(resolved)) {
51
155
  resolved = [resolved];