-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.ts
221 lines (218 loc) · 7.8 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { attachToTextArea, LintEngineAPI } from "./src";
import type { TextlintScriptMetadata } from "@textlint/script-parser";
import type { TextlintFixResult, TextlintMessage, TextlintResult } from "@textlint/types";
import { applyFixesToText } from "@textlint/source-code-fixer";
import type {
TextlintWorkerCommandFix,
TextlintWorkerCommandLint,
TextlintWorkerCommandResponse
} from "@textlint/script-compiler";
const statusElement = document.querySelector("#js-status");
const updateStatus = (status: string) => {
if (statusElement) {
statusElement.textContent = status;
}
};
const waiterForInit = (worker: Worker) => {
let _resolve: null | ((init: TextlintScriptMetadata) => void) = null;
const deferred = new Promise<TextlintScriptMetadata>((resolve) => {
_resolve = resolve;
});
worker.addEventListener(
"message",
function (event) {
const data: TextlintWorkerCommandResponse = event.data;
if (data.command === "init") {
_resolve && _resolve(data.metadata);
}
},
{
once: true
}
);
return {
ready() {
return deferred;
}
};
};
const generateMessageId = () => crypto.randomUUID();
const createTextlint = ({ worker, ext }: { worker: Worker; ext: string }) => {
const lintText: LintEngineAPI["lintText"] = async ({ text }: { text: string }): Promise<TextlintResult[]> => {
updateStatus("linting...");
const controller = new AbortController();
const lintPromise = new Promise<TextlintResult[]>((resolve, reject) => {
const id = generateMessageId();
worker.addEventListener(
"message",
(event: MessageEvent<TextlintWorkerCommandResponse>) => {
const data = event.data;
// global error or ID-specified error
if (data.command === "error" && (!("id" in data) || data.id === id)) {
reject(data.error);
} else if (data.command === "lint:result" && data.id === id) {
resolve([data.result]);
}
},
{ signal: controller.signal }
);
return worker.postMessage({
id,
command: "lint",
text,
ext: ext
} as TextlintWorkerCommandLint);
});
lintPromise
.then(() => {
updateStatus("linted");
})
.catch(() => {
updateStatus("failed to lint");
})
.finally(() => {
controller.abort();
});
return lintPromise;
};
const fixText = async ({
text,
message
}: {
text: string;
message?: TextlintMessage;
}): Promise<TextlintFixResult> => {
updateStatus("fixing...");
const controller = new AbortController();
const fixPromise = new Promise<TextlintFixResult>((resolve, reject) => {
const id = generateMessageId();
worker.addEventListener(
"message",
(event: MessageEvent<TextlintWorkerCommandResponse>) => {
const data = event.data;
// global error or ID-specified error
if (data.command === "error" && (!("id" in data) || data.id === id)) {
reject(data.error);
} else if (data.command === "fix:result" && data.id === id) {
resolve(data.result);
}
},
{ signal: controller.signal }
);
return worker.postMessage({
id,
command: "fix",
text,
ruleId: message?.ruleId,
ext: ext
} as TextlintWorkerCommandFix);
});
fixPromise
.then(() => {
updateStatus("fixed");
})
.catch(() => {
updateStatus("failed to fix");
})
.finally(() => {
controller.abort();
});
return fixPromise;
};
return {
lintText,
fixText
};
};
function escapeHTML(str: string) {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
/**
* Entry point
* @param workerUrl
*/
export async function run(workerUrl: string) {
const worker = new Worker(workerUrl);
const workerStatus = waiterForInit(worker);
const text = new URL(location.href).searchParams.get("text");
const targetElement = document.querySelectorAll("textarea");
const textlint = createTextlint({ worker, ext: ".md" });
const metadata = await workerStatus.ready();
type IgnoreTextSet = Set<string>;
const ignoreMarkMap = new Map<string, IgnoreTextSet>();
const getMatchText = (text: string, message: TextlintMessage) => {
// message.range is introduced in [email protected]
// https://github.com/textlint/textlint/releases/tag/v12.2.0
const range = message.range ?? message?.fix?.range ?? [message.index, message.index + 1];
return text.slice(range[0], range[1]);
};
const isIgnored = ({ text, message }: { text: string; message: TextlintMessage }) => {
const ignoredSet = ignoreMarkMap.get(message.ruleId);
if (!ignoredSet) {
return false;
}
return ignoredSet.has(getMatchText(text, message));
};
const lintEngine: LintEngineAPI = {
async lintText({ text }) {
const results = await textlint.lintText({ text });
return results.map((result) => {
return {
filePath: result.filePath,
messages: result.messages.filter((message) => !isIgnored({ text, message }))
};
});
},
async fixText({ text, messages }): Promise<{ output: string }> {
const fixableMessages = messages.filter((message) => !isIgnored({ text, message }));
return {
output: applyFixesToText(text, fixableMessages)
};
},
async ignoreText({ text, message }: { text: string; message: TextlintMessage }): Promise<boolean> {
const ignoreSet = ignoreMarkMap.get(message.ruleId) ?? new Set<string>();
ignoreSet.add(getMatchText(text, message));
ignoreMarkMap.set(message.ruleId, ignoreSet);
return true;
}
};
targetElement.forEach((element) => {
if (text) {
element.value = text;
}
attachToTextArea({
textAreaElement: element,
lintingDebounceMs: 200,
lintEngine
});
});
// metadata
const metadataDiv = document.createElement("div");
metadataDiv.innerHTML = `
<h3>Script metadata</h3>
<ul>
${Object.entries(metadata)
.map(([key, value]) => {
const toValue = (key: string, value: any) => {
if (key === "homepage") {
return `<a href="${escapeHTML(value)}">${escapeHTML(value)}</a>`;
}
return typeof value === "object"
? `<pre>${escapeHTML(JSON.stringify(value, null, 4))}</pre>`
: escapeHTML(value);
};
return `<dt>${escapeHTML(key)}</dt><dd>${toValue(key, value)}</dd>`;
})
.join("\n")}
</ul>`;
document.querySelector("#metadata")?.append(metadataDiv);
// install - textlint-editor extension will hook it
document.querySelector("#install")?.addEventListener("click", () => {
window.open("textlint-worker.js", "_blank");
});
}