tinymce-solid 0.0.1

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,391 @@
1
+ import { createEffect, createSignal, on, onCleanup, onMount } from "solid-js";
2
+ import { type ScriptItem, ScriptLoader } from "../ScriptLoader2";
3
+ import { getTinymce } from "../TinyMCE";
4
+ import {
5
+ isFunction,
6
+ isTextareaOrInput,
7
+ mergePlugins,
8
+ uuid,
9
+ configHandlers,
10
+ isBeforeInputEventAvailable,
11
+ isInDoc,
12
+ setMode,
13
+ } from "../Utils";
14
+ import {
15
+ IAllProps,
16
+ Version,
17
+ EditorOptions,
18
+ InitOptions,
19
+ OmittedInitProps,
20
+ // IProps,
21
+ } from "./EditorPropTypes";
22
+ import { Bookmark, Editor as TinyMCEEditor, EditorEvent } from "tinymce";
23
+
24
+ export const SolidEditor = (props: Partial<IAllProps>) => {
25
+ const [id] = createSignal(props.id || uuid("solid-tinymce-editor"));
26
+ const initialValue = () => props.initialValue;
27
+ const value = () => props.value || "";
28
+ const skin = () => props.skin || "oxide";
29
+ const contentCss = () => props.contentCss || "default";
30
+ const [editor, setEditor] = createSignal<TinyMCEEditor>();
31
+ const [currentContent, setCurrentContent] = createSignal<string>(value());
32
+ const [rollbackTimer, setRollbackTimer] = createSignal<number>();
33
+ const [valueCursor, setValueCursor] = createSignal<Bookmark>();
34
+ const [boundHandlers, setBoundHandlers] = createSignal<
35
+ Record<string, (event: EditorEvent<unknown>) => unknown>
36
+ >({});
37
+ const view = () => props?.elementRef?.ownerDocument.defaultView ?? window;
38
+
39
+ const getInitialValue = () => {
40
+ if (typeof initialValue() === "string") {
41
+ return initialValue() as string;
42
+ } else if (typeof value() === "string") {
43
+ return value();
44
+ } else {
45
+ return "";
46
+ }
47
+ };
48
+ const getScriptSources = (): ScriptItem[] => {
49
+ const async = props.scriptLoading?.async;
50
+ const defer = props.scriptLoading?.defer;
51
+ if (props.tinymceScriptSrc !== undefined) {
52
+ if (typeof props.tinymceScriptSrc === "string") {
53
+ return [{ src: props.tinymceScriptSrc, async, defer }];
54
+ }
55
+ // multiple scripts can be specified which allows for hybrid mode
56
+ return (props.tinymceScriptSrc as string[] | ScriptItem[]).map((item) => {
57
+ if (typeof item === "string") {
58
+ // async does not make sense for multiple items unless
59
+ // they are not dependent (which will be unlikely)
60
+ return { src: item, async, defer };
61
+ } else {
62
+ return item;
63
+ }
64
+ });
65
+ }
66
+
67
+ // fallback to the cloud when the tinymceScriptSrc is not specified
68
+ const channel = (props.cloudChannel || "7") as Version; // `cloudChannel` is in `defaultProps`, so it's always defined.
69
+ const apiKey = props.apiKey ? props.apiKey : "no-api-key";
70
+ const cloudTinyJs = `https://cdn.tiny.cloud/1/${apiKey}/tinymce/${channel}/tinymce.min.js`;
71
+ return [{ src: cloudTinyJs, async, defer }];
72
+ };
73
+
74
+ const bindHandlers = (prevProps: Partial<IAllProps>) => {
75
+ if (editor() !== undefined) {
76
+ const tinyEditor = editor()!;
77
+
78
+ // typescript chokes trying to understand the type of the lookup function
79
+ configHandlers(
80
+ tinyEditor,
81
+ prevProps,
82
+ props,
83
+ boundHandlers(),
84
+ (key) => props[key],
85
+ );
86
+ // check if we should monitor editor changes
87
+ const isValueControlled = (p: Partial<IAllProps>) =>
88
+ p.onEditorChange !== undefined || p.value !== undefined;
89
+ const wasControlled = isValueControlled(prevProps);
90
+ const nowControlled = isValueControlled(props);
91
+ if (!wasControlled && nowControlled) {
92
+ tinyEditor.on(changeEvents(), handleEditorChange);
93
+ tinyEditor.on(beforeInputEvent(), handleBeforeInput);
94
+ tinyEditor.on("keydown", handleBeforeInputSpecial);
95
+ tinyEditor.on("keyup", handleEditorChangeSpecial);
96
+ tinyEditor.on("NewBlock", handleEditorChange);
97
+ } else if (wasControlled && !nowControlled) {
98
+ tinyEditor.off(changeEvents(), handleEditorChange);
99
+ tinyEditor.off(beforeInputEvent(), handleBeforeInput);
100
+ tinyEditor.off("keydown", handleBeforeInputSpecial);
101
+ tinyEditor.off("keyup", handleEditorChangeSpecial);
102
+ tinyEditor.off("NewBlock", handleEditorChange);
103
+ }
104
+ }
105
+ };
106
+
107
+ const initialise = (attempts = 0) => {
108
+ const target = props.elementRef;
109
+ if (!target) {
110
+ return; // Editor has been unmounted
111
+ }
112
+ if (!isInDoc(target)) {
113
+ // this is probably someone trying to help by rendering us offscreen
114
+ // but we can't do that because the editor iframe must be in the document
115
+ // in order to have state
116
+ if (attempts === 0) {
117
+ // we probably just need to wait for the current events to be processed
118
+ setTimeout(() => initialise(1), 1);
119
+ } else if (attempts < 100) {
120
+ // wait for ten seconds, polling every tenth of a second
121
+ setTimeout(() => initialise(attempts + 1), 100);
122
+ } else {
123
+ // give up, at this point it seems that more polling is unlikely to help
124
+ throw new Error("tinymce can only be initialised when in a document");
125
+ }
126
+ return;
127
+ }
128
+
129
+ const tinymce = getTinymce(view());
130
+ if (!tinymce) {
131
+ throw new Error("tinymce should have been loaded into global scope");
132
+ }
133
+
134
+ const finalInit: EditorOptions = {
135
+ ...(props.init as Omit<InitOptions, OmittedInitProps>),
136
+ selector: undefined,
137
+ target,
138
+ skin: skin(),
139
+ content_css: contentCss(),
140
+ readonly: props.disabled,
141
+ inline: props.inline,
142
+ plugins: mergePlugins(props.init?.plugins, props.plugins),
143
+ toolbar: props.toolbar ?? props.init?.toolbar,
144
+ ...(props.licenseKey ? { license_key: props.licenseKey } : {}),
145
+ setup: (editor) => {
146
+ setEditor(editor);
147
+ bindHandlers({});
148
+
149
+ // When running in inline mode the editor gets the initial value
150
+ // from the innerHTML of the element it is initialized on.
151
+ // However we don't want to take on the responsibility of sanitizing
152
+ // to remove XSS in the react integration so we have a chicken and egg
153
+ // problem... We avoid it by sneaking in a set content before the first
154
+ // "official" setContent and using TinyMCE to do the sanitization.
155
+ if (props.inline && !isTextareaOrInput(target)) {
156
+ editor.once("PostRender", (_evt) => {
157
+ editor.setContent(getInitialValue(), {
158
+ no_events: true,
159
+ event_name: _evt.type,
160
+ });
161
+ });
162
+ }
163
+
164
+ if (props.init && isFunction(props.init.setup)) {
165
+ props.init.setup(editor);
166
+ }
167
+ },
168
+ init_instance_callback: (editor) => {
169
+ // check for changes that happened since tinymce.init() was called
170
+ const initialValue = getInitialValue();
171
+ let newCurrentValue = currentContent() ?? editor.getContent();
172
+ if (newCurrentValue !== initialValue) {
173
+ newCurrentValue = initialValue;
174
+ // same as resetContent in TinyMCE 5
175
+ editor.setContent(initialValue);
176
+ editor.undoManager.clear();
177
+ editor.undoManager.add();
178
+ editor.setDirty(false);
179
+ }
180
+ setCurrentContent(newCurrentValue);
181
+ const disabled = props.disabled ?? false;
182
+ setMode(editor, disabled ? "readonly" : "design");
183
+ // ensure existing init_instance_callback is called
184
+ if (props.init && isFunction(props.init.init_instance_callback)) {
185
+ props.init.init_instance_callback(editor);
186
+ }
187
+ },
188
+ };
189
+ if (!props.inline) {
190
+ target.style.visibility = "";
191
+ }
192
+ if (isTextareaOrInput(target)) {
193
+ target.value = getInitialValue();
194
+ }
195
+
196
+ tinymce.init(finalInit);
197
+ };
198
+ const mountCallback = () => {
199
+ if (getTinymce(view()) !== null) {
200
+ initialise();
201
+ } else if (
202
+ Array.isArray(props.tinymceScriptSrc) &&
203
+ props.tinymceScriptSrc.length === 0
204
+ ) {
205
+ // props.onScriptsLoadError?.(
206
+ // new Error("No `tinymce` global is present but the `tinymceScriptSrc` prop was an empty array."),
207
+ // );
208
+ throw new Error(
209
+ "No `tinymce` global is present but the `tinymceScriptSrc` prop was an empty array.",
210
+ );
211
+ } else if (props?.elementRef?.ownerDocument) {
212
+ const successHandler = () => {
213
+ // console.log("loaded");
214
+ // props.onScriptsLoad?.();
215
+ initialise();
216
+ };
217
+ const errorHandler = (err: unknown) => {
218
+ // console.warn(err);
219
+ // props.onScriptsLoadError?.(err);
220
+ throw new Error(err as string);
221
+ };
222
+
223
+ ScriptLoader.loadList(
224
+ props.elementRef.ownerDocument,
225
+ getScriptSources(),
226
+ props.scriptLoading?.delay ?? 0,
227
+ successHandler,
228
+ errorHandler,
229
+ );
230
+ }
231
+ };
232
+ const cleanUpCallback = () => {
233
+ const tinyEditor = editor()!;
234
+ if (typeof tinyEditor !== "undefined") {
235
+ tinyEditor.off(changeEvents(), handleEditorChange);
236
+ tinyEditor.off(beforeInputEvent(), handleBeforeInput);
237
+ tinyEditor.off("keypress", handleEditorChangeSpecial);
238
+ tinyEditor.off("keydown", handleBeforeInputSpecial);
239
+ tinyEditor.off("NewBlock", handleEditorChange);
240
+ Object.keys(boundHandlers()).forEach((eventName) => {
241
+ tinyEditor.off(eventName, boundHandlers()[eventName]);
242
+ });
243
+ setBoundHandlers({});
244
+ tinyEditor.destroy();
245
+ tinyEditor.remove();
246
+ setEditor();
247
+ }
248
+ };
249
+
250
+ createEffect(
251
+ on(value, () => {
252
+ if (value() !== currentContent()) {
253
+ setCurrentContent(value());
254
+ editor()?.setContent(value(), { no_events: true, event_name: "input" });
255
+ }
256
+ }),
257
+ );
258
+
259
+ createEffect(
260
+ on(skin, () => {
261
+ cleanUpCallback();
262
+ setTimeout(() => {
263
+ mountCallback();
264
+ }, 34);
265
+ }),
266
+ );
267
+
268
+ onMount(mountCallback);
269
+ onCleanup(cleanUpCallback);
270
+
271
+ const changeEvents = () => {
272
+ const isIE = getTinymce(view())?.Env?.browser?.isIE();
273
+ return isIE
274
+ ? "change keyup compositionend setcontent CommentChange"
275
+ : "change input compositionend setcontent CommentChange";
276
+ };
277
+
278
+ const beforeInputEvent = () => {
279
+ return isBeforeInputEventAvailable()
280
+ ? "beforeinput SelectionChange"
281
+ : "SelectionChange";
282
+ };
283
+
284
+ const handleEditorChange = (event: EditorEvent<unknown>) => {
285
+ const tinyEditor = editor();
286
+ if (tinyEditor && tinyEditor.initialized && !event.isDefaultPrevented()) {
287
+ const newContent = tinyEditor.getContent();
288
+ if (
289
+ props.value !== undefined &&
290
+ props.value !== newContent &&
291
+ props.rollback !== false
292
+ ) {
293
+ // start a timer and revert to the value if not applied in time
294
+ if (!rollbackTimer()) {
295
+ setRollbackTimer(
296
+ window.setTimeout(
297
+ rollbackChange,
298
+ typeof props.rollback === "number" ? props.rollback : 200,
299
+ ),
300
+ );
301
+ }
302
+ }
303
+
304
+ if (newContent !== currentContent()) {
305
+ setCurrentContent(newContent);
306
+ if (isFunction(props.onEditorChange)) {
307
+ props.onEditorChange(newContent, tinyEditor);
308
+ }
309
+ }
310
+ }
311
+ };
312
+
313
+ const rollbackChange = () => {
314
+ const tinyEditor = editor();
315
+ const value = props.value;
316
+ if (tinyEditor && value && value !== currentContent()) {
317
+ tinyEditor.undoManager.ignore(() => {
318
+ tinyEditor.setContent(value);
319
+ // only restore cursor on inline editors when they are focused
320
+ // as otherwise it will cause a focus grab
321
+ if (valueCursor() && (!props.inline || tinyEditor.hasFocus())) {
322
+ try {
323
+ tinyEditor.selection.moveToBookmark(valueCursor()!);
324
+ } catch (e) {
325
+ /* ignore */
326
+ }
327
+ }
328
+ });
329
+ }
330
+ setRollbackTimer(undefined);
331
+ };
332
+
333
+ const handleBeforeInput = (event: EditorEvent<unknown>) => {
334
+ const tinyEditor = editor()!;
335
+ if (
336
+ props.value !== undefined &&
337
+ props.value === currentContent() &&
338
+ tinyEditor &&
339
+ !event.isDefaultPrevented()
340
+ ) {
341
+ if (!props.inline || tinyEditor.hasFocus()) {
342
+ try {
343
+ // getBookmark throws exceptions when the editor has not been focused
344
+ // possibly only in inline mode but I'm not taking chances
345
+ // this.valueCursor = tinyEditor.selection.getBookmark(3);
346
+ setValueCursor(tinyEditor.selection.getBookmark(3));
347
+ } catch (e) {
348
+ /* ignore */
349
+ }
350
+ }
351
+ }
352
+ };
353
+
354
+ const handleEditorChangeSpecial = (evt: EditorEvent<KeyboardEvent>) => {
355
+ if (
356
+ evt.key === "Enter" ||
357
+ evt.key === "Backspace" ||
358
+ evt.key === "Delete"
359
+ ) {
360
+ handleBeforeInput(evt);
361
+ }
362
+ };
363
+
364
+ const handleBeforeInputSpecial = (evt: EditorEvent<KeyboardEvent>) => {
365
+ if (
366
+ evt.key === "Enter" ||
367
+ evt.key === "Backspace" ||
368
+ evt.key === "Delete"
369
+ ) {
370
+ handleBeforeInput(evt);
371
+ }
372
+ };
373
+
374
+ return props.inline ? (
375
+ <div
376
+ style={{ display: editor() ? "" : "none" }}
377
+ ref={props.elementRef as HTMLDivElement}
378
+ id={id()}
379
+ data-testid={props.testid}
380
+ tabIndex={props.tabIndex}
381
+ />
382
+ ) : (
383
+ <textarea
384
+ style={{ display: editor() ? "" : "none" }}
385
+ ref={props.elementRef as HTMLTextAreaElement}
386
+ id={id()}
387
+ data-testid={props.testid}
388
+ tabIndex={props.tabIndex}
389
+ />
390
+ );
391
+ };
package/src/index.tsx ADDED
@@ -0,0 +1,6 @@
1
+ import { SolidEditor } from "./components/SolidEditor";
2
+ import { type IAllProps, EditorPropTypes } from "./components/EditorPropTypes";
3
+
4
+ export default SolidEditor;
5
+ export { type IAllProps };
6
+ export { EditorPropTypes };
@@ -0,0 +1,84 @@
1
+ /** @type {import('tailwindcss').Config} */
2
+ module.exports = {
3
+ darkMode: ["class", '[data-kb-theme="dark"]'],
4
+ content: ["src/**/*.{ts,tsx}", "demo/**/*.{ts,tsx}"],
5
+ prefix: "",
6
+ theme: {
7
+ container: {
8
+ center: true,
9
+ padding: "2rem",
10
+ screens: {
11
+ "2xl": "1400px",
12
+ },
13
+ },
14
+ extend: {
15
+ colors: {
16
+ border: "hsl(var(--border))",
17
+ input: "hsl(var(--input))",
18
+ ring: "hsl(var(--ring))",
19
+ background: "hsl(var(--background))",
20
+ foreground: "hsl(var(--foreground))",
21
+ primary: {
22
+ DEFAULT: "hsl(var(--primary))",
23
+ foreground: "hsl(var(--primary-foreground))",
24
+ },
25
+ secondary: {
26
+ DEFAULT: "hsl(var(--secondary))",
27
+ foreground: "hsl(var(--secondary-foreground))",
28
+ },
29
+ destructive: {
30
+ DEFAULT: "hsl(var(--destructive))",
31
+ foreground: "hsl(var(--destructive-foreground))",
32
+ },
33
+ muted: {
34
+ DEFAULT: "hsl(var(--muted))",
35
+ foreground: "hsl(var(--muted-foreground))",
36
+ },
37
+ accent: {
38
+ DEFAULT: "hsl(var(--accent))",
39
+ foreground: "hsl(var(--accent-foreground))",
40
+ },
41
+ popover: {
42
+ DEFAULT: "hsl(var(--popover))",
43
+ foreground: "hsl(var(--popover-foreground))",
44
+ },
45
+ card: {
46
+ DEFAULT: "hsl(var(--card))",
47
+ foreground: "hsl(var(--card-foreground))",
48
+ },
49
+ },
50
+ borderRadius: {
51
+ lg: "var(--radius)",
52
+ md: "calc(var(--radius) - 2px)",
53
+ sm: "calc(var(--radius) - 4px)",
54
+ },
55
+ keyframes: {
56
+ "accordion-down": {
57
+ from: { height: 0 },
58
+ to: { height: "var(--kb-accordion-content-height)" },
59
+ },
60
+ "accordion-up": {
61
+ from: { height: "var(--kb-accordion-content-height)" },
62
+ to: { height: 0 },
63
+ },
64
+ "collapsible-down": {
65
+ from: { height: 0 },
66
+ to: { height: "var(--kb-collapsible-content-height)" },
67
+ },
68
+ "collapsible-up": {
69
+ from: { height: "var(--kb-collapsible-content-height)" },
70
+ to: { height: 0 },
71
+ },
72
+ },
73
+ animation: {
74
+ "accordion-down": "accordion-down 0.2s ease-out",
75
+ "accordion-up": "accordion-up 0.2s ease-out",
76
+ "collapsible-down": "collapsible-down 0.2s ease-out",
77
+ "collapsible-up": "collapsible-up 0.2s ease-out",
78
+ },
79
+ },
80
+ },
81
+ plugins: [
82
+ require("tailwindcss-animate"),
83
+ ],
84
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
6
+ "moduleResolution": "bundler",
7
+ "allowSyntheticDefaultImports": true,
8
+ "allowImportingTsExtensions": true,
9
+ "esModuleInterop": true,
10
+ "jsx": "preserve",
11
+ "jsxImportSource": "solid-js",
12
+ "allowJs": true,
13
+ "strict": true,
14
+ "noEmit": true,
15
+ "types": ["vite/client", "node"],
16
+ "isolatedModules": true,
17
+ "baseUrl": ".",
18
+ "paths": {
19
+ "~/*": ["./src/*"],
20
+ }
21
+ },
22
+ "include": ["src"],
23
+ "exclude": ["node_modules", "dist", "demo", "experiments"]
24
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { defineConfig } from "tsup";
2
+ import * as preset from "tsup-preset-solid";
3
+
4
+ const preset_options: preset.PresetOptions = {
5
+ // array or single object
6
+ entries: [
7
+ // default entry (index)
8
+ {
9
+ // entries with '.tsx' extension will have `solid` export condition generated
10
+ entry: "./src/index.tsx",
11
+ // will generate a separate development entry
12
+ dev_entry: true,
13
+ },
14
+ ],
15
+ // Set to `true` to remove all `console.*` calls and `debugger` statements in prod builds
16
+ drop_console: true,
17
+ // Set to `true` to generate a CommonJS build alongside ESM
18
+ // cjs: true,
19
+ };
20
+
21
+ const CI =
22
+ process.env['CI'] === 'true' ||
23
+ process.env['GITHUB_ACTIONS'] === 'true' ||
24
+ process.env['CI'] === '"1"' ||
25
+ process.env['GITHUB_ACTIONS'] === '"1"'
26
+
27
+ export default defineConfig(config => {
28
+ const watching = !!config.watch;
29
+
30
+ const parsed_options = preset.parsePresetOptions(preset_options, watching);
31
+
32
+ // DON'T OVERRIDE MY PACKAGE.JSON PLEASE!
33
+ if (!watching && !CI) {
34
+ const package_fields = preset.generatePackageExports(parsed_options)
35
+ // console.log(`package.json: \n\n${JSON.stringify(package_fields, null, 2)}\n\n`)
36
+
37
+ // will update ./package.json with the correct export fields
38
+ preset.writePackageJson(package_fields)
39
+ }
40
+
41
+ return preset.generateTsupOptions(parsed_options);
42
+ });