File size: 7,220 Bytes
08610a7 8ad2be8 08610a7 1721caf 08610a7 1721caf 7f934d6 8ad2be8 08610a7 1721caf 08610a7 1721caf 7f934d6 1721caf 7f934d6 1721caf 08610a7 8ad2be8 08610a7 e46ff97 08610a7 8ad2be8 08610a7 5d4928f 44632df 5d4928f 44632df 5d4928f 8ad2be8 e46ff97 5d4928f 8c89ee8 5d4928f 8c89ee8 5d4928f 8c89ee8 e46ff97 7f934d6 5d4928f 8c89ee8 5d4928f 8c89ee8 5d4928f 8ad2be8 5d4928f 44632df 8ad2be8 08610a7 e46ff97 08610a7 e46ff97 8ad2be8 08610a7 5d4928f 8ad2be8 5d4928f 8ad2be8 5d4928f 44632df 5d4928f 44632df 8ad2be8 5d4928f 8ad2be8 08610a7 |
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 222 223 224 225 226 227 228 229 230 231 232 233 234 |
// @ts-check
function chat5() {
function initHTML() {
const ui = document.createElement('div');
ui.innerHTML = `
<div class=chat-log>Loading...</div>
<div class=chat-input>[Input]</div>
<style>
body {
position: absolute;
left: 0; top: 0;
width: 100%; height: 100%;
margin: 0;
padding: 0;
border: none;
display: grid;
grid-template: 1fr auto / 1fr;
}
.chat-log {
display: grid;
grid-template: 1fr / 1fr;
}
.chat-input {
border-top: solid 1px black;
display: grid;
grid-template: 1fr auto / 1fr;
}
.prose-mirror {
overflow-y: auto;
}
.milkdown {
display: grid;
grid-template: 1fr / 1fr;
}
.milkdown .ProseMirror {
min-height: 2em;
padding: 0.6em;
font-family: inherit;
white-space: pre-wrap;
}
</style>
`;
if (!document.body) {
document.documentElement.appendChild(document.createElement('body'));
} else {
cleanBody();
}
for (const elem of [...ui.children]) {
document.body.appendChild(elem);
}
const chatLog = /** @type {HTMLElement|null} */ (document.querySelector('.chat-log'));
const chatInput = /** @type {HTMLElement|null} */ (document.querySelector('.chat-input'));
return { chatLog, chatInput };
}
function cleanBody() {
for (const elem of [...document.body.childNodes]) {
if ((/** @type {HTMLElement} */ (elem).tagName || '').toLowerCase() === 'script') continue;
elem.remove();
}
}
async function initMilkdown({ chatLog, chatInput }) {
if (chatLog) chatLog.textContent = 'Loading Milkdown...';
try {
// Import all necessary Milkdown modules with the same version
const version = '7.15.3';
const [
kitCore,
kitCommonmark,
milkdownCore,
milkdownPresetCommonmark,
milkdownProse,
prosemirrorKeymap,
prosemirrorState
] = await Promise.all([
import(`https://esm.sh/@milkdown/kit@${version}/core`),
import(`https://esm.sh/@milkdown/kit@${version}/preset/commonmark`),
import(`https://esm.sh/@milkdown/core@${version}`),
import(`https://esm.sh/@milkdown/preset-commonmark@${version}`),
import(`https://esm.sh/@milkdown/prose@${version}`),
import('https://esm.sh/prosemirror-keymap@1.2.0'),
import('https://esm.sh/prosemirror-state@1.3.4')
]);
if (chatLog) chatLog.innerHTML = '';
if (chatInput) chatInput.innerHTML = '';
// Use context keys from milkdownCore only
const { rootCtx, defaultValueCtx, editorViewOptionsCtx } = milkdownCore;
// Create read-only editor in .chat-log
const chatLogEditor = await milkdownCore.Editor.make()
.config((ctx) => {
ctx.set(rootCtx, chatLog);
ctx.set(defaultValueCtx, 'Loaded.');
ctx.set(editorViewOptionsCtx, { editable: () => false });
})
.use(kitCommonmark.commonmark)
.create();
// Create editable editor in .chat-input, no placeholder, starts empty
const chatInputEditor = await milkdownCore.Editor.make()
.config((ctx) => {
ctx.set(rootCtx, chatInput);
ctx.set(defaultValueCtx, '');
})
.use(kitCommonmark.commonmark)
.create();
return {
kitCore,
kitCommonmark,
milkdownCore,
milkdownPresetCommonmark,
milkdownProse,
prosemirrorKeymap,
prosemirrorState,
chatLogEditor,
chatInputEditor
};
} catch (error) {
console.log(error);
const errorElem = document.createElement('pre');
errorElem.innerText = error.stack || 'ERR ' + error.message;
errorElem.style.whiteSpace = 'pre-wrap';
(chatLog || document.body).appendChild(errorElem);
}
}
async function outputMessage(chatLogEditor, milkdownCore, msg) {
await chatLogEditor.action((ctx) => {
const view = ctx.get(milkdownCore.editorViewCtx);
const parser = ctx.get(milkdownCore.parserCtx);
const serializer = ctx.get(milkdownCore.serializerCtx);
const state = view.state;
// Get current markdown, append new message, and parse
const currentMarkdown = serializer(state.doc);
const newMarkdown = currentMarkdown ? (currentMarkdown + '\n' + msg) : msg;
const doc = parser(newMarkdown);
// Use replaceWith and doc.content to avoid TransformError
const tr = state.tr.replaceWith(0, state.doc.content.size, doc.content);
view.dispatch(tr);
});
// Scroll chat log to bottom (smooth if possible)
const chatLogElem = document.querySelector('.chat-log');
if (chatLogElem) {
if ('scrollTo' in chatLogElem) {
chatLogElem.scrollTo({ top: chatLogElem.scrollHeight, behavior: 'smooth' });
} else {
chatLogElem.scrollTop = chatLogElem.scrollHeight;
}
}
}
async function runBrowser() {
window.onerror = (...args) => {
alert(args.map(String).join('\n'));
};
const { kitCore, kitCommonmark, chatLog, chatInput } = initHTML();
const milkdownResult = await initMilkdown({ chatLog, chatInput });
if (!milkdownResult) return;
const { chatLogEditor, chatInputEditor, milkdownCore, prosemirrorKeymap, prosemirrorState } = milkdownResult;
outputMessage(chatLogEditor, milkdownCore, 'Milkdown editor component is loaded correctly. Please try typing...');
// Add a ProseMirror plugin to handle Enter key in chat input editor
await chatInputEditor.action((ctx) => {
const serializer = ctx.get(milkdownCore.serializerCtx);
const view = ctx.get(milkdownCore.editorViewCtx);
const { Plugin } = prosemirrorState;
// Add a keymap plugin for Enter
const enterPlugin = new Plugin({
props: {
handleKeyDown(view, event) {
if (
event.key === 'Enter' &&
!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey
) {
event.preventDefault();
const inputMarkdown = serializer(view.state.doc).trim();
if (inputMarkdown) {
const msg = `user typed:\n> ${inputMarkdown.replace(/\n/g, '\n> ')}`;
outputMessage(chatLogEditor, milkdownCore, msg);
// Clear input
const tr = view.state.tr.replaceWith(
0,
view.state.doc.content.size,
view.state.schema.nodes.doc.createAndFill().content
);
view.dispatch(tr);
}
return true;
}
return false;
},
},
});
view.state = view.state.reconfigure({
plugins: [...view.state.plugins, enterPlugin],
});
view.updateState(view.state);
});
window.onerror = (...args) => {
try {
outputMessage(chatLogEditor, milkdownCore, args.map(String).join('\n'));
} catch (errorNext) {
alert(args.map(String).join('\n') + '\n\n' + errorNext.stack);
}
};
}
if (typeof window !== 'undefined' && typeof window?.alert === 'function'
&& typeof document !== 'undefined' && typeof document?.createElement === 'function') {
runBrowser();
}
}
chat5();
|