Current section

Files

Jump to
ckeditor5_phoenix dist index.mjs
Raw

dist/index.mjs

class W {
/**
* Map of registered items.
*/
items = /* @__PURE__ */ new Map();
/**
* Map of initialization errors for items that failed to register.
*/
initializationErrors = /* @__PURE__ */ new Map();
/**
* Map of pending callbacks waiting for items to be registered or fail.
*/
pendingCallbacks = /* @__PURE__ */ new Map();
/**
* Set of watchers that observe changes to the registry.
*/
watchers = /* @__PURE__ */ new Set();
/**
* Executes a function on an item.
* If the item is not yet registered, it will wait for it to be registered.
*
* @param id The ID of the item.
* @param onSuccess The function to execute.
* @param onError Optional error callback.
* @returns A promise that resolves with the result of the function.
*/
execute(t, e, i) {
const a = this.items.get(t), n = this.initializationErrors.get(t);
return n ? (i?.(n), Promise.reject(n)) : a ? Promise.resolve(e(a)) : new Promise((o, u) => {
const s = this.getPendingCallbacks(t);
s.success.push(async (c) => {
o(await e(c));
}), i ? s.error.push(i) : s.error.push(u);
});
}
/**
* Registers an item.
*
* @param id The ID of the item.
* @param item The item instance.
*/
register(t, e) {
if (this.items.has(t))
throw new Error(`Item with ID "${t}" is already registered.`);
this.resetErrors(t), this.items.set(t, e);
const i = this.pendingCallbacks.get(t);
i && (i.success.forEach((a) => a(e)), this.pendingCallbacks.delete(t)), this.registerAsDefault(t, e), this.notifyWatchers();
}
/**
* Registers an error for an item.
*
* @param id The ID of the item.
* @param error The error to register.
*/
error(t, e) {
this.items.delete(t), this.initializationErrors.set(t, e);
const i = this.pendingCallbacks.get(t);
i && (i.error.forEach((a) => a(e)), this.pendingCallbacks.delete(t)), this.initializationErrors.size === 1 && !this.items.size && this.error(null, e), this.notifyWatchers();
}
/**
* Resets errors for an item.
*
* @param id The ID of the item.
*/
resetErrors(t) {
const { initializationErrors: e } = this;
e.has(null) && e.get(null) === e.get(t) && e.delete(null), e.delete(t);
}
/**
* Un-registers an item.
*
* @param id The ID of the item.
*/
unregister(t) {
if (!this.items.has(t))
throw new Error(`Item with ID "${t}" is not registered.`);
t && this.items.get(null) === this.items.get(t) && this.unregister(null), this.items.delete(t), this.pendingCallbacks.delete(t), this.notifyWatchers();
}
/**
* Gets all registered items.
*
* @returns An array of all registered items.
*/
getItems() {
return Array.from(this.items.values());
}
/**
* Checks if an item with the given ID is registered.
*
* @param id The ID of the item.
* @returns `true` if the item is registered, `false` otherwise.
*/
hasItem(t) {
return this.items.has(t);
}
/**
* Gets a promise that resolves with the item instance for the given ID.
* If the item is not registered yet, it will wait for it to be registered.
*
* @param id The ID of the item.
* @returns A promise that resolves with the item instance.
*/
waitFor(t) {
return new Promise((e, i) => {
this.execute(t, e, i);
});
}
/**
* Destroys all registered items and clears the registry.
* This will call the `destroy` method on each item.
*/
async destroyAll() {
const t = Array.from(new Set(this.items.values())).map((e) => e.destroy());
this.items.clear(), this.pendingCallbacks.clear(), await Promise.all(t), this.notifyWatchers();
}
/**
* Registers a watcher that will be called whenever the registry changes.
*
* @param watcher The watcher function to register.
* @returns A function to unregister the watcher.
*/
watch(t) {
return this.watchers.add(t), t(
new Map(this.items),
new Map(this.initializationErrors)
), this.unwatch.bind(this, t);
}
/**
* Un-registers a watcher.
*
* @param watcher The watcher function to unregister.
*/
unwatch(t) {
this.watchers.delete(t);
}
/**
* Notifies all watchers about changes to the registry.
*/
notifyWatchers() {
this.watchers.forEach(
(t) => t(
new Map(this.items),
new Map(this.initializationErrors)
)
);
}
/**
* Gets or creates pending callbacks for a specific ID.
*
* @param id The ID of the item.
* @returns The pending callbacks structure.
*/
getPendingCallbacks(t) {
let e = this.pendingCallbacks.get(t);
return e || (e = { success: [], error: [] }, this.pendingCallbacks.set(t, e)), e;
}
/**
* Registers an item as the default (null ID) item if it's the first one.
*
* @param id The ID of the item being registered.
* @param item The item instance.
*/
registerAsDefault(t, e) {
this.items.size === 1 && t !== null && this.register(null, e);
}
}
function Y(r) {
return r.replace(/[-_\s]+(.)?/g, (t, e) => e ? e.toUpperCase() : "").replace(/^./, (t) => t.toLowerCase());
}
function O(r, t) {
let e = null;
return (...i) => {
e && clearTimeout(e), e = setTimeout(() => {
t(...i);
}, r);
};
}
function J(r) {
if (Object.prototype.toString.call(r) !== "[object Object]")
return !1;
const t = Object.getPrototypeOf(r);
return t === Object.prototype || t === null;
}
function k(r) {
if (Array.isArray(r))
return r.map(k);
if (J(r)) {
const t = /* @__PURE__ */ Object.create(null);
for (const [e, i] of Object.entries(r))
t[Y(e)] = k(i);
return t;
}
return r;
}
function X(r, t) {
const e = Object.entries(r).filter(([i, a]) => t(a, i));
return Object.fromEntries(e);
}
function Q() {
const r = document.querySelector('meta[name="csrf-token"]');
if (r)
return r.getAttribute("content");
const t = document.cookie.match(/(?:^|; )_csrf_token=([^;]*)/);
return t ? decodeURIComponent(t[1]) : null;
}
class P {
/**
* The current state of the hook.
*/
state = "mounting";
/**
* The DOM element the hook is attached to.
* It includes an `instance` property to hold the hook instance.
*/
el;
/**
* The LiveView socket instance, providing connection to the server.
*/
liveSocket;
/**
* Pushes an event from the client to the LiveView server process.
* @param _event The name of the event.
* @param _payload The data to send with the event.
* @param _callback An optional function to be called with the server's reply.
*/
pushEvent;
/**
* Pushes an event to another hook on the page.
* @param _selector The CSS selector of the target element with the hook.
* @param _event The name of the event.
* @param _payload The data to send with the event.
* @param _callback An optional function to be called with the reply.
*/
pushEventTo;
/**
* Registers a handler for an event pushed from the server.
* @param _event The name of the event to handle.
* @param _callback The function to execute when the event is received.
*/
handleEvent;
/**
* Checks if the hook is in the process of being destroyed.
*/
isBeingDestroyed() {
return this.state === "destroyed" || this.state === "destroying";
}
}
function C(r) {
return {
/**
* The mounted lifecycle callback for the LiveView hook object.
* It creates an instance of the user-defined hook class and sets up the necessary properties and methods.
*/
async mounted() {
const t = new r();
this.el.instance = t, t.el = this.el, t.liveSocket = this.liveSocket, t.pushEvent = (i, a, n) => this.pushEvent?.(i, a, n), t.pushEventTo = (i, a, n, o) => this.pushEventTo?.(i, a, n, o), t.handleEvent = (i, a) => this.handleEvent?.(i, a), t.state = "mounting";
const e = await t.mounted?.();
return t.state = "mounted", e;
},
/**
* The beforeUpdate lifecycle callback that delegates to the hook instance.
*/
beforeUpdate() {
this.el.instance.beforeUpdate?.();
},
/**
* The destroyed lifecycle callback that delegates to the hook instance.
*/
async destroyed() {
const { instance: t } = this.el;
t.state = "destroying", await t.destroyed?.(), t.state = "destroyed";
},
/**
* The disconnected lifecycle callback that delegates to the hook instance.
*/
disconnected() {
this.el.instance.disconnected?.();
},
/**
* The reconnected lifecycle callback that delegates to the hook instance.
*/
reconnected() {
this.el.instance.reconnected?.();
}
};
}
function q(r) {
return Object.keys(r).length === 0 && r.constructor === Object;
}
function Z(r) {
return r == null;
}
function S(r, t) {
const e = Object.entries(r).map(([i, a]) => [i, t(a, i)]);
return Object.fromEntries(e);
}
function z(r) {
if (r === null)
return null;
const t = Number.parseInt(r, 10);
return Number.isNaN(t) ? null : t;
}
function tt() {
return Math.random().toString(36).substring(2);
}
function et(r, {
timeOutAfter: t = 500,
retryAfter: e = 100
} = {}) {
return new Promise((i, a) => {
const n = Date.now();
let o = null;
const u = setTimeout(() => {
a(o ?? new Error("Timeout"));
}, t), s = async () => {
try {
const c = await r();
clearTimeout(u), i(c);
} catch (c) {
o = c, Date.now() - n > t ? a(c) : setTimeout(s, e);
}
};
s();
});
}
const I = Symbol.for("context-editor-watchdog");
async function rt({ element: r, context: t, creator: e, config: i }) {
const a = tt();
await t.add({
creator: (s, c) => e.create(s, c),
id: a,
sourceElementOrData: r,
type: "editor",
config: i
});
const n = t.getItem(a), o = {
state: "available",
editorContextId: a,
context: t
};
n[I] = o;
const u = t.destroy.bind(t);
return t.destroy = async () => (o.state = "unavailable", u()), {
...o,
editor: n
};
}
function it(r) {
return I in r ? r[I] : null;
}
function E(r) {
return ["inline", "classic", "balloon", "decoupled"].includes(r);
}
async function at(r) {
const t = await import("ckeditor5"), i = {
inline: t.InlineEditor,
balloon: t.BalloonEditor,
classic: t.ClassicEditor,
decoupled: t.DecoupledEditor,
multiroot: t.MultiRootEditor
}[r];
if (!i)
throw new Error(`Unsupported editor type: ${r}`);
return i;
}
class D {
static the = new D();
/**
* Map of registered custom plugins.
*/
plugins = /* @__PURE__ */ new Map();
/**
* Private constructor to enforce singleton pattern.
*/
constructor() {
}
/**
* Registers a custom plugin for the CKEditor.
*
* @param name The name of the plugin.
* @param reader The plugin reader function that returns the plugin constructor.
* @returns A function to unregister the plugin.
*/
register(t, e) {
if (this.plugins.has(t))
throw new Error(`Plugin with name "${t}" is already registered.`);
return this.plugins.set(t, e), this.unregister.bind(this, t);
}
/**
* Removes a custom plugin by its name.
*
* @param name The name of the plugin to unregister.
* @throws Will throw an error if the plugin is not registered.
*/
unregister(t) {
if (!this.plugins.has(t))
throw new Error(`Plugin with name "${t}" is not registered.`);
this.plugins.delete(t);
}
/**
* Removes all custom editor plugins.
* This is useful for cleanup in tests or when reloading plugins.
*/
unregisterAll() {
this.plugins.clear();
}
/**
* Retrieves a custom plugin by its name.
*
* @param name The name of the plugin.
* @returns The plugin constructor or undefined if not found.
*/
async get(t) {
return this.plugins.get(t)?.();
}
/**
* Checks if a plugin with the given name is registered.
*
* @param name The name of the plugin.
* @returns `true` if the plugin is registered, `false` otherwise.
*/
has(t) {
return this.plugins.has(t);
}
}
async function V(r) {
const t = await import("ckeditor5");
let e = null;
const i = r.map(async (a) => {
const n = await D.the.get(a);
if (n)
return n;
const { [a]: o } = t;
if (o)
return o;
if (!e)
try {
e = await import("ckeditor5-premium-features");
} catch (s) {
console.error(`Failed to load premium package: ${s}`);
}
const { [a]: u } = e || {};
if (u)
return u;
throw new Error(`Plugin "${a}" not found in base or premium packages.`);
});
return {
loadedPlugins: await Promise.all(i),
hasPremium: !!e
};
}
async function B(r, t) {
const e = [r.ui, r.content];
return await Promise.all(
[
U("ckeditor5", e),
/* v8 ignore next */
t && U("ckeditor5-premium-features", e)
].filter((a) => !!a)
).then((a) => a.flat());
}
async function U(r, t) {
return await Promise.all(
t.filter((e) => e !== "en").map(async (e) => {
const i = await nt(r, e);
return i?.default ?? i;
}).filter(Boolean)
);
}
async function nt(r, t) {
try {
if (r === "ckeditor5")
switch (t) {
case "af":
return await import("ckeditor5/translations/af.js");
case "ar":
return await import("ckeditor5/translations/ar.js");
case "ast":
return await import("ckeditor5/translations/ast.js");
case "az":
return await import("ckeditor5/translations/az.js");
case "bg":
return await import("ckeditor5/translations/bg.js");
case "bn":
return await import("ckeditor5/translations/bn.js");
case "bs":
return await import("ckeditor5/translations/bs.js");
case "ca":
return await import("ckeditor5/translations/ca.js");
case "cs":
return await import("ckeditor5/translations/cs.js");
case "da":
return await import("ckeditor5/translations/da.js");
case "de":
return await import("ckeditor5/translations/de.js");
case "de-ch":
return await import("ckeditor5/translations/de-ch.js");
case "el":
return await import("ckeditor5/translations/el.js");
case "en":
return await import("ckeditor5/translations/en.js");
case "en-au":
return await import("ckeditor5/translations/en-au.js");
case "en-gb":
return await import("ckeditor5/translations/en-gb.js");
case "eo":
return await import("ckeditor5/translations/eo.js");
case "es":
return await import("ckeditor5/translations/es.js");
case "es-co":
return await import("ckeditor5/translations/es-co.js");
case "et":
return await import("ckeditor5/translations/et.js");
case "eu":
return await import("ckeditor5/translations/eu.js");
case "fa":
return await import("ckeditor5/translations/fa.js");
case "fi":
return await import("ckeditor5/translations/fi.js");
case "fr":
return await import("ckeditor5/translations/fr.js");
case "gl":
return await import("ckeditor5/translations/gl.js");
case "gu":
return await import("ckeditor5/translations/gu.js");
case "he":
return await import("ckeditor5/translations/he.js");
case "hi":
return await import("ckeditor5/translations/hi.js");
case "hr":
return await import("ckeditor5/translations/hr.js");
case "hu":
return await import("ckeditor5/translations/hu.js");
case "hy":
return await import("ckeditor5/translations/hy.js");
case "id":
return await import("ckeditor5/translations/id.js");
case "it":
return await import("ckeditor5/translations/it.js");
case "ja":
return await import("ckeditor5/translations/ja.js");
case "jv":
return await import("ckeditor5/translations/jv.js");
case "kk":
return await import("ckeditor5/translations/kk.js");
case "km":
return await import("ckeditor5/translations/km.js");
case "kn":
return await import("ckeditor5/translations/kn.js");
case "ko":
return await import("ckeditor5/translations/ko.js");
case "ku":
return await import("ckeditor5/translations/ku.js");
case "lt":
return await import("ckeditor5/translations/lt.js");
case "lv":
return await import("ckeditor5/translations/lv.js");
case "ms":
return await import("ckeditor5/translations/ms.js");
case "nb":
return await import("ckeditor5/translations/nb.js");
case "ne":
return await import("ckeditor5/translations/ne.js");
case "nl":
return await import("ckeditor5/translations/nl.js");
case "no":
return await import("ckeditor5/translations/no.js");
case "oc":
return await import("ckeditor5/translations/oc.js");
case "pl":
return await import("ckeditor5/translations/pl.js");
case "pt":
return await import("ckeditor5/translations/pt.js");
case "pt-br":
return await import("ckeditor5/translations/pt-br.js");
case "ro":
return await import("ckeditor5/translations/ro.js");
case "ru":
return await import("ckeditor5/translations/ru.js");
case "si":
return await import("ckeditor5/translations/si.js");
case "sk":
return await import("ckeditor5/translations/sk.js");
case "sl":
return await import("ckeditor5/translations/sl.js");
case "sq":
return await import("ckeditor5/translations/sq.js");
case "sr":
return await import("ckeditor5/translations/sr.js");
case "sr-latn":
return await import("ckeditor5/translations/sr-latn.js");
case "sv":
return await import("ckeditor5/translations/sv.js");
case "th":
return await import("ckeditor5/translations/th.js");
case "tk":
return await import("ckeditor5/translations/tk.js");
case "tr":
return await import("ckeditor5/translations/tr.js");
case "tt":
return await import("ckeditor5/translations/tt.js");
case "ug":
return await import("ckeditor5/translations/ug.js");
case "uk":
return await import("ckeditor5/translations/uk.js");
case "ur":
return await import("ckeditor5/translations/ur.js");
case "uz":
return await import("ckeditor5/translations/uz.js");
case "vi":
return await import("ckeditor5/translations/vi.js");
case "zh":
return await import("ckeditor5/translations/zh.js");
case "zh-cn":
return await import("ckeditor5/translations/zh-cn.js");
default:
return console.warn(`Language ${t} not found in ckeditor5 translations`), null;
}
else
switch (t) {
case "af":
return await import("ckeditor5-premium-features/translations/af.js");
case "ar":
return await import("ckeditor5-premium-features/translations/ar.js");
case "ast":
return await import("ckeditor5-premium-features/translations/ast.js");
case "az":
return await import("ckeditor5-premium-features/translations/az.js");
case "bg":
return await import("ckeditor5-premium-features/translations/bg.js");
case "bn":
return await import("ckeditor5-premium-features/translations/bn.js");
case "bs":
return await import("ckeditor5-premium-features/translations/bs.js");
case "ca":
return await import("ckeditor5-premium-features/translations/ca.js");
case "cs":
return await import("ckeditor5-premium-features/translations/cs.js");
case "da":
return await import("ckeditor5-premium-features/translations/da.js");
case "de":
return await import("ckeditor5-premium-features/translations/de.js");
case "de-ch":
return await import("ckeditor5-premium-features/translations/de-ch.js");
case "el":
return await import("ckeditor5-premium-features/translations/el.js");
case "en":
return await import("ckeditor5-premium-features/translations/en.js");
case "en-au":
return await import("ckeditor5-premium-features/translations/en-au.js");
case "en-gb":
return await import("ckeditor5-premium-features/translations/en-gb.js");
case "eo":
return await import("ckeditor5-premium-features/translations/eo.js");
case "es":
return await import("ckeditor5-premium-features/translations/es.js");
case "es-co":
return await import("ckeditor5-premium-features/translations/es-co.js");
case "et":
return await import("ckeditor5-premium-features/translations/et.js");
case "eu":
return await import("ckeditor5-premium-features/translations/eu.js");
case "fa":
return await import("ckeditor5-premium-features/translations/fa.js");
case "fi":
return await import("ckeditor5-premium-features/translations/fi.js");
case "fr":
return await import("ckeditor5-premium-features/translations/fr.js");
case "gl":
return await import("ckeditor5-premium-features/translations/gl.js");
case "gu":
return await import("ckeditor5-premium-features/translations/gu.js");
case "he":
return await import("ckeditor5-premium-features/translations/he.js");
case "hi":
return await import("ckeditor5-premium-features/translations/hi.js");
case "hr":
return await import("ckeditor5-premium-features/translations/hr.js");
case "hu":
return await import("ckeditor5-premium-features/translations/hu.js");
case "hy":
return await import("ckeditor5-premium-features/translations/hy.js");
case "id":
return await import("ckeditor5-premium-features/translations/id.js");
case "it":
return await import("ckeditor5-premium-features/translations/it.js");
case "ja":
return await import("ckeditor5-premium-features/translations/ja.js");
case "jv":
return await import("ckeditor5-premium-features/translations/jv.js");
case "kk":
return await import("ckeditor5-premium-features/translations/kk.js");
case "km":
return await import("ckeditor5-premium-features/translations/km.js");
case "kn":
return await import("ckeditor5-premium-features/translations/kn.js");
case "ko":
return await import("ckeditor5-premium-features/translations/ko.js");
case "ku":
return await import("ckeditor5-premium-features/translations/ku.js");
case "lt":
return await import("ckeditor5-premium-features/translations/lt.js");
case "lv":
return await import("ckeditor5-premium-features/translations/lv.js");
case "ms":
return await import("ckeditor5-premium-features/translations/ms.js");
case "nb":
return await import("ckeditor5-premium-features/translations/nb.js");
case "ne":
return await import("ckeditor5-premium-features/translations/ne.js");
case "nl":
return await import("ckeditor5-premium-features/translations/nl.js");
case "no":
return await import("ckeditor5-premium-features/translations/no.js");
case "oc":
return await import("ckeditor5-premium-features/translations/oc.js");
case "pl":
return await import("ckeditor5-premium-features/translations/pl.js");
case "pt":
return await import("ckeditor5-premium-features/translations/pt.js");
case "pt-br":
return await import("ckeditor5-premium-features/translations/pt-br.js");
case "ro":
return await import("ckeditor5-premium-features/translations/ro.js");
case "ru":
return await import("ckeditor5-premium-features/translations/ru.js");
case "si":
return await import("ckeditor5-premium-features/translations/si.js");
case "sk":
return await import("ckeditor5-premium-features/translations/sk.js");
case "sl":
return await import("ckeditor5-premium-features/translations/sl.js");
case "sq":
return await import("ckeditor5-premium-features/translations/sq.js");
case "sr":
return await import("ckeditor5-premium-features/translations/sr.js");
case "sr-latn":
return await import("ckeditor5-premium-features/translations/sr-latn.js");
case "sv":
return await import("ckeditor5-premium-features/translations/sv.js");
case "th":
return await import("ckeditor5-premium-features/translations/th.js");
case "tk":
return await import("ckeditor5-premium-features/translations/tk.js");
case "tr":
return await import("ckeditor5-premium-features/translations/tr.js");
case "tt":
return await import("ckeditor5-premium-features/translations/tt.js");
case "ug":
return await import("ckeditor5-premium-features/translations/ug.js");
case "uk":
return await import("ckeditor5-premium-features/translations/uk.js");
case "ur":
return await import("ckeditor5-premium-features/translations/ur.js");
case "uz":
return await import("ckeditor5-premium-features/translations/uz.js");
case "vi":
return await import("ckeditor5-premium-features/translations/vi.js");
case "zh":
return await import("ckeditor5-premium-features/translations/zh.js");
case "zh-cn":
return await import("ckeditor5-premium-features/translations/zh-cn.js");
default:
return console.warn(`Language ${t} not found in premium translations`), await import("ckeditor5-premium-features/translations/en.js");
}
} catch (e) {
return console.error(`Failed to load translation for ${r}/${t}:`, e), null;
}
}
function F(r) {
return S(r, (t) => ({
dictionary: t
}));
}
function _(r) {
const t = K(r);
return S(t, ({ content: e }) => e);
}
function R(r) {
const t = K(r), e = S(t, ({ initialValue: i }) => i);
return X(e, (i) => typeof i == "string");
}
function K(r) {
const t = document.querySelectorAll(
[
`[data-cke-editor-id="${r}"][data-cke-editable-root-name]`,
"[data-cke-editable-root-name]:not([data-cke-editor-id])"
].join(", ")
), e = Array.from(t).reduce((u, s) => {
const c = s.getAttribute("data-cke-editable-root-name"), l = s.getAttribute("data-cke-editable-initial-value") || "", m = s.querySelector("[data-cke-editable-content]");
return !c || !m ? u : {
...u,
[c]: {
content: m,
initialValue: l
}
};
}, /* @__PURE__ */ Object.create({})), i = document.querySelector(`[phx-hook="CKEditor5"][id="${r}"]`);
if (!i)
return e;
const a = i.getAttribute("cke-initial-value") || "", n = i.querySelector(`#${r}_editor `), o = e.main;
return o ? {
...e,
main: {
...o,
initialValue: o.initialValue || a
}
} : n ? {
...e,
main: {
content: n,
initialValue: a
}
} : e;
}
const H = ["inline", "classic", "balloon", "decoupled", "multiroot"];
function ot(r) {
const t = r.getAttribute("cke-preset");
if (!t)
throw new Error('CKEditor5 hook requires a "cke-preset" attribute on the element.');
const { type: e, config: i, license: a, ...n } = JSON.parse(t);
if (!e || !i || !a)
throw new Error('CKEditor5 hook configuration must include "editor", "config", and "license" properties.');
if (!H.includes(e))
throw new Error(`Invalid editor type: ${e}. Must be one of: ${H.join(", ")}.`);
return {
type: e,
license: a,
config: k(i),
customTranslations: n.customTranslations || n.custom_translations
};
}
function x(r) {
if (!r || typeof r != "object")
return r;
if (Array.isArray(r))
return r.map((i) => x(i));
const t = r;
if (t.$element && typeof t.$element == "string") {
const i = document.querySelector(t.$element);
return i || console.warn(`Element not found for selector: ${t.$element}`), i || null;
}
const e = /* @__PURE__ */ Object.create(null);
for (const [i, a] of Object.entries(r))
e[i] = x(a);
return e;
}
function st(r, t) {
const { editing: e } = r;
e.view.change((i) => {
i.setStyle("height", `${t}px`, e.view.document.getRoot());
});
}
const A = Symbol.for("elixir-editor-watchdog");
async function ct(r) {
const { EditorWatchdog: t } = await import("ckeditor5"), e = new t(r);
return e.setCreator(async (...i) => {
const a = await r.create(...i);
return a[A] = e, a;
}), {
watchdog: e,
Constructor: {
create: async (...i) => (await e.create(...i), e.editor)
}
};
}
function ut(r) {
return A in r ? r[A] : null;
}
class w extends W {
static the = new w();
}
function lt(r) {
const t = r.getAttribute("cke-context");
if (!t)
throw new Error('CKEditor5 hook requires a "cke-context" attribute on the element.');
const { config: e, ...i } = JSON.parse(t);
return {
config: k(e),
customTranslations: i.customTranslations || i.custom_translations,
watchdogConfig: i.watchdogConfig || i.watchdog_config
};
}
class dt extends P {
/**
* The promise that resolves to the context instance.
*/
contextPromise = null;
/**
* Attributes for the context instance.
*/
get attrs() {
const t = (i) => this.el.getAttribute(i) || null, e = {
id: this.el.id,
config: lt(this.el),
language: {
ui: t("cke-language") || "en",
content: t("cke-content-language") || "en"
}
};
return Object.defineProperty(this, "attrs", {
value: e,
writable: !1,
configurable: !1,
enumerable: !0
}), e;
}
/**
* Mounts the context component.
*/
async mounted() {
const { id: t, language: e } = this.attrs, { customTranslations: i, watchdogConfig: a, config: { plugins: n, ...o } } = this.attrs.config, { loadedPlugins: u, hasPremium: s } = await V(n ?? []), l = [
...await B(e, s),
F(i?.dictionary || {})
].filter((f) => !q(f));
this.contextPromise = (async () => {
const { ContextWatchdog: f, Context: v } = await import("ckeditor5"), p = new f(v, {
crashNumberLimit: 10,
...a
});
return await p.create({
...o,
language: e,
plugins: u,
...l.length && {
translations: l
}
}), p.on("itemError", (...g) => {
console.error("Context item error:", ...g);
}), p;
})();
const m = await this.contextPromise;
this.isBeingDestroyed() || w.the.register(t, m);
}
/**
* Destroys the context component. Unmounts root from the editor.
*/
async destroyed() {
const { id: t } = this.attrs;
this.el.style.display = "none";
try {
await (await this.contextPromise)?.destroy();
} finally {
this.contextPromise = null, w.the.hasItem(t) && w.the.unregister(t);
}
}
}
function mt(r) {
return r.hasAttribute("cke-context");
}
function ht(r) {
let t = r;
for (; t; ) {
if (mt(t))
return t;
t = t.parentElement;
}
return null;
}
async function pt(r) {
const t = ht(r);
return t ? w.the.waitFor(t.id) : null;
}
const wt = C(dt);
class h extends W {
static the = new h();
}
class ft extends P {
/**
* The name of the hook.
*/
editorPromise = null;
/**
* Attributes for the editable instance.
*/
get attrs() {
const t = {
editableId: this.el.getAttribute("id"),
editorId: this.el.getAttribute("data-cke-editor-id") || null,
rootName: this.el.getAttribute("data-cke-editable-root-name"),
initialValue: this.el.getAttribute("data-cke-editable-initial-value") || ""
};
return Object.defineProperty(this, "attrs", {
value: t,
writable: !1,
configurable: !1,
enumerable: !0
}), t;
}
/**
* Mounts the editable component.
*/
async mounted() {
const { editableId: t, editorId: e, rootName: i, initialValue: a } = this.attrs, n = this.el.querySelector(`#${t}_input`);
this.editorPromise = h.the.execute(e, (o) => {
if (this.isBeingDestroyed())
return null;
const { ui: u, editing: s, model: c } = o;
if (c.document.getRoot(i))
return o;
o.addRoot(i, {
isUndoable: !1,
data: a
});
const l = this.el.querySelector("[data-cke-editable-content]"), m = u.view.createEditable(i, l);
return u.addEditable(m), s.view.forceRender(), n && yt(n, o, i), o;
});
}
/**
* Destroys the editable component. Unmounts root from the editor.
*/
async destroyed() {
const { rootName: t } = this.attrs;
this.el.style.display = "none";
const e = await this.editorPromise;
if (this.editorPromise = null, e && e.state !== "destroyed") {
const i = e.model.document.getRoot(t);
i && "detachEditable" in e && (e.detachEditable(i), e.detachRoot(t, !1));
}
}
}
const gt = C(ft);
function yt(r, t, e) {
const i = () => {
r.value = t.getData({ rootName: e });
};
t.model.document.on("change:data", O(100, i)), i();
}
async function bt() {
const { Plugin: r, FileRepository: t } = await import("ckeditor5");
return class extends r {
/**
* The name of the plugin.
*/
static get pluginName() {
return "PhoenixUploadAdapter";
}
static get requires() {
return [t];
}
/**
* Initializes the plugin.
*/
init() {
const { editor: i } = this, { plugins: a, config: n } = i, o = n.get("phoenixUpload.url");
if (!o || a.has("SimpleUploadAdapter") || a.has("Base64UploadAdapter") || a.has("CKFinderUploadAdapter"))
return;
const u = a.get(t);
u.createUploadAdapter = (s) => new Et(s, o);
}
};
}
class Et {
loader;
uploadUrl;
abortController = null;
constructor(t, e) {
this.loader = t, this.uploadUrl = e;
}
/**
* Starts the upload process.
*/
async upload() {
const t = await this.loader.file;
this.abortController = new AbortController();
const e = new FormData();
e.append("file", t), t.size && (this.loader.uploadTotal = t.size, this.loader.uploaded = 0);
const i = {}, a = Q();
a && (i["X-CSRF-Token"] = a);
try {
const n = await fetch(this.uploadUrl, {
method: "POST",
headers: i,
body: e,
signal: this.abortController.signal
});
if (!n.ok) {
let u = "Couldn't upload file!";
try {
const s = await n.json();
s?.error?.message && (u = s.error.message);
} catch {
}
throw new Error(u);
}
return this.loader.uploaded = this.loader.uploadTotal, {
default: (await n.json()).url
};
} catch (n) {
throw n.name === "AbortError" ? n : n.message || "Couldn't upload file!";
}
}
/**
* Aborts the upload process.
*/
/* v8 ignore next 4 */
abort() {
this.abortController?.abort(), this.abortController = null;
}
}
async function kt({
editorId: r,
saveDebounceMs: t
}) {
const { Plugin: e } = await import("ckeditor5");
return class extends e {
/**
* The input element to synchronize with.
*/
input = null;
/**
* The form element reference for cleanup.
*/
form = null;
/**
* The name of the plugin.
*/
static get pluginName() {
return "SyncEditorWithInput";
}
/**
* Initializes the plugin.
*/
afterInit() {
const { editor: a } = this;
this.input = document.getElementById(`${r}_input`), this.input && (a.model.document.on("change:data", O(t, () => this.sync())), a.once("ready", this.sync), this.form = this.input.closest("form"), this.form?.addEventListener("submit", this.sync));
}
/**
* Synchronizes the editor's content with the input field.
*/
sync = () => {
const a = this.editor.getData();
this.input.value = a, this.input.dispatchEvent(new Event("input", { bubbles: !0 }));
};
/**
* Destroys the plugin.
*/
destroy() {
this.form && this.form.removeEventListener("submit", this.sync), this.input = null, this.form = null;
}
};
}
async function Pt(r) {
const { Plugin: t } = await import("ckeditor5"), { editorId: e, saveDebounceMs: i, events: a, pushEvent: n, handleEvent: o } = r;
return class extends t {
/**
* The name of the plugin.
*/
static get pluginName() {
return "SyncEditorWithPhoenix";
}
/**
* Initializes the plugin.
*/
init() {
const { editor: s } = this;
a.change && this.setupTypingContentPush(), a.blur && this.setupEventPush("blur"), a.focus && this.setupEventPush("focus"), o("ckeditor5:set-data", ({ editorId: c, data: l }) => {
(Z(c) || c === e) && s.setData(l);
});
}
/**
* Setups the content push event for the editor.
*/
setupTypingContentPush() {
const { editor: s } = this, c = () => {
n(
"ckeditor5:change",
{
editorId: e,
data: N(this.editor)
}
);
};
s.model.document.on("change:data", O(i, c)), s.once("ready", c);
}
/**
* Setups the event push for the editor.
*/
setupEventPush(s) {
const { editor: c } = this, l = () => {
const { isFocused: m } = c.ui.focusTracker;
(m ? "focus" : "blur") === s && n(
`ckeditor5:${s}`,
{
editorId: e,
data: N(c)
}
);
};
c.ui.focusTracker.on("change:isFocused", l);
}
};
}
function N(r) {
return r.model.document.getRootNames().reduce((e, i) => (e[i] = r.getData({ rootName: i }), e), /* @__PURE__ */ Object.create({}));
}
class Ct extends P {
/**
* The promise that resolves to the editor instance.
*/
editorPromise = null;
/**
* Attributes for the editor instance.
*/
get attrs() {
const { el: t } = this, e = t.getAttribute.bind(t), i = t.hasAttribute.bind(t), a = {
editorId: e("id"),
contextId: e("cke-context-id"),
preset: ot(t),
editableHeight: z(e("cke-editable-height")),
watchdog: i("cke-watchdog"),
events: {
change: i("cke-change-event"),
blur: i("cke-blur-event"),
focus: i("cke-focus-event")
},
saveDebounceMs: z(e("cke-save-debounce-ms")) ?? 400,
language: {
ui: e("cke-language") || "en",
content: e("cke-content-language") || "en"
}
};
return Object.defineProperty(this, "attrs", {
value: a,
writable: !1,
configurable: !1,
enumerable: !0
}), a;
}
/**
* Mounts the editor component.
*/
async mounted() {
const { editorId: t } = this.attrs;
h.the.resetErrors(t);
try {
this.editorPromise = this.createEditor();
const e = await this.editorPromise;
this.isBeingDestroyed() || (h.the.register(t, e), e.once("destroy", () => {
h.the.hasItem(t) && h.the.unregister(t);
}));
} catch (e) {
this.editorPromise = null, h.the.error(t, e);
}
return this;
}
/**
* Destroys the editor instance when the component is destroyed.
* This is important to prevent memory leaks and ensure that the editor is properly cleaned up.
*/
async destroyed() {
this.el.style.display = "none";
try {
const t = await this.editorPromise;
if (!t)
return;
const e = it(t), i = ut(t);
e ? e.state !== "unavailable" && await e.context.remove(e.editorContextId) : i ? await i.destroy() : await t.destroy();
} finally {
this.editorPromise = null;
}
}
/**
* Creates the CKEditor instance.
*/
async createEditor() {
const { preset: t, editorId: e, contextId: i, editableHeight: a, events: n, saveDebounceMs: o, language: u, watchdog: s } = this.attrs, { customTranslations: c, type: l, license: m, config: { plugins: f, ...v } } = t;
let p = await at(l);
const g = await (i ? w.the.waitFor(i) : pt(this.el));
if (s && !g) {
const d = await ct(p);
({ Constructor: p } = d), d.watchdog.on("restart", () => {
const b = d.watchdog.editor;
this.editorPromise = Promise.resolve(b), h.the.register(e, b);
});
}
const { loadedPlugins: T, hasPremium: G } = await V(f);
E(l) && T.push(
await kt({
editorId: e,
saveDebounceMs: o
})
), T.push(
...await Promise.all([
Pt({
editorId: e,
saveDebounceMs: o,
events: n,
pushEvent: this.pushEvent.bind(this),
handleEvent: this.handleEvent.bind(this)
}),
bt()
])
);
const j = [
...await B(u, G),
F(c?.dictionary || {})
].filter((d) => !q(d));
let y = R(e);
E(l) && (y = y.main || "");
const $ = await (async () => {
let d = _(e);
if (!(d instanceof HTMLElement) && !("main" in d)) {
const M = l === "decoupled" ? ["main"] : Object.keys(y);
L(d, M) || (d = await vt(e, M), y = R(e));
}
E(l) && "main" in d && (d = d.main);
const b = {
...x(v),
initialData: y,
licenseKey: m.key,
plugins: T,
language: u,
...j.length && {
translations: j
}
};
return !g || !(d instanceof HTMLElement) ? p.create(d, b) : (await rt({
context: g,
element: d,
creator: p,
config: b
})).editor;
})();
return E(l) && a && st($, a), $;
}
}
function L(r, t) {
return t.every((e) => r[e]);
}
async function vt(r, t) {
return et(
() => {
const e = _(r);
if (!L(e, t))
throw new Error(
`It looks like not all required root elements are present yet.
* If you want to wait for them, ensure they are registered before editor initialization.
* If you want lazy initialize roots, consider removing root values from the \`initialData\` config and assign initial data in editable components.
Missing roots: ${t.filter((i) => !e[i]).join(", ")}.`
);
return e;
},
{ timeOutAfter: 2e3, retryAfter: 100 }
);
}
const Tt = C(Ct);
class It extends P {
/**
* The name of the hook.
*/
mountedPromise = null;
/**
* Attributes for the editable instance.
*/
get attrs() {
const t = {
editorId: this.el.getAttribute("data-cke-editor-id") || null,
name: this.el.getAttribute("data-cke-ui-part-name")
};
return Object.defineProperty(this, "attrs", {
value: t,
writable: !1,
configurable: !1,
enumerable: !0
}), t;
}
/**
* Mounts the editable component.
*/
async mounted() {
const { editorId: t, name: e } = this.attrs;
this.mountedPromise = h.the.execute(t, (i) => {
if (this.isBeingDestroyed())
return;
const { ui: a } = i, n = xt(e), o = a.view[n];
if (!o) {
console.error(`Unknown UI part name: "${e}". Supported names are "toolbar" and "menubar".`);
return;
}
this.el.appendChild(o.element);
});
}
/**
* Destroys the editable component. Unmounts root from the editor.
*/
async destroyed() {
this.el.style.display = "none", await this.mountedPromise, this.mountedPromise = null, this.el.innerHTML = "";
}
}
function xt(r) {
switch (r) {
case "toolbar":
return "toolbar";
case "menubar":
return "menuBarView";
default:
return null;
}
}
const At = C(It), Mt = {
CKEditor5: Tt,
CKEditable: gt,
CKUIPart: At,
CKContext: wt
};
export {
w as ContextsRegistry,
D as CustomEditorPluginsRegistry,
h as EditorsRegistry,
Mt as Hooks,
it as unwrapEditorContext,
ut as unwrapEditorWatchdog
};
//# sourceMappingURL=index.mjs.map