Current section

Files

Jump to
ckeditor5_phoenix dist index.mjs
Raw

dist/index.mjs

class F {
/**
* 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, r) {
const i = this.items.get(t), n = this.initializationErrors.get(t);
return n ? (r?.(n), Promise.reject(n)) : i ? Promise.resolve(e(i)) : new Promise((s, c) => {
const o = this.getPendingCallbacks(t);
o.success.push(async (u) => {
s(await e(u));
}), r ? o.error.push(r) : o.error.push(c);
});
}
/**
* 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 r = this.pendingCallbacks.get(t);
r && (r.success.forEach((i) => i(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 r = this.pendingCallbacks.get(t);
r && (r.error.forEach((i) => i(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, r) => {
this.execute(t, e, r);
});
}
/**
* 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 Z(a) {
return a.replace(/[-_\s]+(.)?/g, (t, e) => e ? e.toUpperCase() : "").replace(/^./, (t) => t.toLowerCase());
}
function P(a, t) {
let e = null;
return (...r) => {
e && clearTimeout(e), e = setTimeout(() => {
t(...r);
}, a);
};
}
function tt(a) {
if (Object.prototype.toString.call(a) !== "[object Object]")
return !1;
const t = Object.getPrototypeOf(a);
return t === Object.prototype || t === null;
}
function C(a) {
if (Array.isArray(a))
return a.map(C);
if (tt(a)) {
const t = /* @__PURE__ */ Object.create(null);
for (const [e, r] of Object.entries(a))
t[Z(e)] = C(r);
return t;
}
return a;
}
function et(a, t) {
const e = Object.entries(a).filter(([r, i]) => t(i, r));
return Object.fromEntries(e);
}
function rt() {
const a = document.querySelector('meta[name="csrf-token"]');
if (a)
return a.getAttribute("content");
const t = document.cookie.match(/(?:^|; )_csrf_token=([^;]*)/);
return t ? decodeURIComponent(t[1]) : null;
}
class I {
/**
* 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;
/**
* Callbacks to run before the hook is destroyed.
*/
_beforeDestroyCallbacks = [];
/**
* Registers a callback to be called before the hook is destroyed.
* Callbacks are called in LIFO order (last registered, first called).
*/
onBeforeDestroy(t) {
this._beforeDestroyCallbacks.push(t);
}
/**
* 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;
/**
* Called when the hook has been mounted to the DOM.
* This is the ideal place for initialization code.
*/
mounted() {
}
/**
* Called when the element has been removed from the DOM.
* Perfect for cleanup tasks.
*/
destroyed() {
}
/**
* Called when the element has been updated by a LiveView patch.
*/
updated() {
}
/**
* Checks if the hook is in the process of being destroyed.
*/
isBeingDestroyed() {
return this.state === "destroyed" || this.state === "destroying";
}
/**
* Runs all registered before-destroy callbacks and clears the list.
* Called internally by makeHook before destroyed().
*/
_runBeforeDestroyCallbacks() {
for (const t of this._beforeDestroyCallbacks.reverse())
t();
this._beforeDestroyCallbacks = [];
}
}
function x(a) {
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 a();
this.el.instance = t, t.el = this.el, t.pushEvent = (r, i, n) => this.pushEvent?.(r, i, n), t.pushEventTo = (r, i, n, s) => this.pushEventTo?.(r, i, n, s), t.handleEvent = (r, i) => this.handleEvent?.(r, i), 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", t._runBeforeDestroyCallbacks(), 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?.();
},
/**
* The updated lifecycle callback that delegates to the hook instance.
*/
updated() {
this.el.instance.updated?.();
}
};
}
function W(a) {
return Object.keys(a).length === 0 && a.constructor === Object;
}
function at(a) {
return a == null;
}
function V(a, t) {
const e = Object.entries(a).map(([r, i]) => [r, t(i, r)]);
return Object.fromEntries(e);
}
function z(a) {
if (a === null)
return null;
const t = Number.parseInt(a, 10);
return Number.isNaN(t) ? null : t;
}
function it(a) {
return a == null || a.trim() === "" ? null : JSON.parse(a);
}
function nt(a, t) {
if (a === t)
return !0;
const e = Object.keys(a), r = Object.keys(t);
if (e.length !== r.length)
return !1;
for (const i of e)
if (a[i] !== t[i] || !Object.prototype.hasOwnProperty.call(t, i))
return !1;
return !0;
}
function st() {
return Math.random().toString(36).substring(2);
}
function ot(a, {
timeOutAfter: t = 500,
retryAfter: e = 100
} = {}) {
return new Promise((r, i) => {
const n = Date.now();
let s = null;
const c = setTimeout(() => {
i(s ?? new Error("Timeout"));
}, t), o = async () => {
try {
const u = await a();
clearTimeout(c), r(u);
} catch (u) {
s = u, Date.now() - n > t ? i(u) : setTimeout(o, e);
}
};
o();
});
}
const S = /* @__PURE__ */ Symbol.for("context-editor-watchdog");
async function ct({ element: a, context: t, creator: e, config: r }) {
const i = st();
await t.add({
creator: (o, u) => e.create(o, u),
id: i,
sourceElementOrData: a,
type: "editor",
config: r
});
const n = t.getItem(i), s = {
state: "available",
editorContextId: i,
context: t
};
n[S] = s;
const c = t.destroy.bind(t);
return t.destroy = async () => (s.state = "unavailable", c()), {
...s,
editor: n
};
}
function ut(a) {
return S in a ? a[S] : null;
}
function lt(a) {
return ["multiroot", "decoupled"].includes(a);
}
function v(a) {
return ["inline", "classic", "balloon", "decoupled"].includes(a);
}
async function dt(a) {
const t = await import("ckeditor5"), r = {
inline: t.InlineEditor,
balloon: t.BalloonEditor,
classic: t.ClassicEditor,
decoupled: t.DecoupledEditor,
multiroot: t.MultiRootEditor
}[a];
if (!r)
throw new Error(`Unsupported editor type: ${a}`);
return r;
}
class $ {
static the = new $();
/**
* 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 B(a) {
const t = await import("ckeditor5");
let e = null;
const r = a.map(async (i) => {
const n = await $.the.get(i);
if (n)
return n;
const { [i]: s } = t;
if (s)
return s;
if (!e)
try {
e = await import("ckeditor5-premium-features");
} catch (o) {
console.error(`Failed to load premium package: ${o}`);
}
const { [i]: c } = e || {};
if (c)
return c;
throw new Error(`Plugin "${i}" not found in base or premium packages.`);
});
return {
loadedPlugins: await Promise.all(r),
hasPremium: !!e
};
}
async function L(a, t) {
const e = [a.ui, a.content];
return await Promise.all(
[
H("ckeditor5", e),
/* v8 ignore next */
t && H("ckeditor5-premium-features", e)
].filter((i) => !!i)
).then((i) => i.flat());
}
async function H(a, t) {
return await Promise.all(
t.filter((e) => e !== "en").map(async (e) => {
const r = await ht(a, e);
return r?.default ?? r;
}).filter(Boolean)
);
}
async function ht(a, t) {
try {
if (a === "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 ${a}/${t}:`, e), null;
}
}
function K(a) {
return V(a, (t) => ({
dictionary: t
}));
}
function Y(a) {
const t = J(a);
return V(t, ({ content: e }) => e);
}
function _(a) {
const t = J(a), e = V(t, ({ initialValue: r }) => r);
return et(e, (r) => typeof r == "string");
}
function J(a) {
const t = document.querySelectorAll(
[
`[data-cke-editor-id="${a}"][data-cke-editable-root-name]`,
"[data-cke-editable-root-name]:not([data-cke-editor-id])"
].join(", ")
), e = Array.from(t).reduce((c, o) => {
const u = o.getAttribute("data-cke-editable-root-name"), l = o.getAttribute("data-cke-editable-initial-value") || "", d = o.querySelector("[data-cke-editable-content]");
return !u || !d ? c : {
...c,
[u]: {
content: d,
initialValue: l
}
};
}, /* @__PURE__ */ Object.create({})), r = document.querySelector(`[phx-hook="CKEditor5"][id="${a}"]`);
if (!r)
return e;
const i = r.getAttribute("data-cke-initial-value") || "", n = r.querySelector(`#${a}_editor `), s = e.main;
return s ? {
...e,
main: {
...s,
initialValue: s.initialValue || i
}
} : n ? {
...e,
main: {
content: n,
initialValue: i
}
} : e;
}
const q = ["inline", "classic", "balloon", "decoupled", "multiroot"];
function mt(a) {
const t = a.getAttribute("data-cke-preset");
if (!t)
throw new Error('CKEditor5 hook requires a "cke-preset" attribute on the element.');
const { type: e, config: r, license: i, ...n } = JSON.parse(t);
if (!e || !r || !i)
throw new Error('CKEditor5 hook configuration must include "editor", "config", and "license" properties.');
if (!q.includes(e))
throw new Error(`Invalid editor type: ${e}. Must be one of: ${q.join(", ")}.`);
return {
type: e,
license: i,
config: C(r),
customTranslations: n.customTranslations || n.custom_translations
};
}
function A(a) {
if (!a || typeof a != "object")
return a;
if (Array.isArray(a))
return a.map((r) => A(r));
const t = a;
if (t.$element && typeof t.$element == "string") {
const r = document.querySelector(t.$element);
return r || console.warn(`Element not found for selector: ${t.$element}`), r || null;
}
const e = /* @__PURE__ */ Object.create(null);
for (const [r, i] of Object.entries(a))
e[r] = A(i);
return e;
}
function T(a, t, e) {
if (!e || typeof e != "object")
return e;
if (Array.isArray(e))
return e.map((n) => T(a, t, n));
const r = e;
if (r.$translation && typeof r.$translation == "string") {
const n = r.$translation, s = pt(a, n, t);
return s === void 0 && console.warn(`Translation not found for key: ${n}`), s !== void 0 ? s : null;
}
const i = /* @__PURE__ */ Object.create(null);
for (const [n, s] of Object.entries(e))
i[n] = T(a, t, s);
return i;
}
function pt(a, t, e) {
for (const r of a) {
const i = r[e];
if (i?.dictionary && t in i.dictionary)
return i.dictionary[t];
}
}
function ft(a, t) {
const { editing: e } = a;
e.view.change((r) => {
r.setStyle("height", `${t}px`, e.view.document.getRoot());
});
}
const N = /* @__PURE__ */ Symbol.for("elixir-editor-watchdog");
async function wt(a) {
const { EditorWatchdog: t } = await import("ckeditor5"), e = new t(a);
return e.setCreator(async (...r) => {
const i = await a.create(...r);
return i[N] = e, i;
}), {
watchdog: e,
Constructor: {
create: async (...r) => (await e.create(...r), e.editor)
}
};
}
function gt(a) {
return N in a ? a[N] : null;
}
class g extends F {
static the = new g();
}
function yt(a) {
const t = a.getAttribute("data-cke-context");
if (!t)
throw new Error('CKEditor5 hook requires a "data-cke-context" attribute on the element.');
const { config: e, ...r } = JSON.parse(t);
return {
config: C(e),
customTranslations: r.customTranslations || r.custom_translations,
watchdogConfig: r.watchdogConfig || r.watchdog_config
};
}
class bt extends I {
/**
* The promise that resolves to the context instance.
*/
contextPromise = null;
/**
* Attributes for the context instance.
*/
get attrs() {
const t = (r) => this.el.getAttribute(r) || null, e = {
id: this.el.id,
config: yt(this.el),
language: {
ui: t("data-cke-language") || "en",
content: t("data-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: r, watchdogConfig: i, config: { plugins: n, ...s } } = this.attrs.config, { loadedPlugins: c, hasPremium: o } = await B(n ?? []), l = [
...await L(e, o),
K(r?.dictionary || {})
].filter((m) => !W(m));
let d = A(s);
d = T([...l].reverse(), e.ui, d), this.contextPromise = (async () => {
const { ContextWatchdog: m, Context: y } = await import("ckeditor5"), w = new m(y, {
crashNumberLimit: 10,
...i
});
return await w.create({
...d,
language: e,
plugins: c,
...l.length && {
translations: l
}
}), w.on("itemError", (...k) => {
console.error("Context item error:", ...k);
}), w;
})();
const f = await this.contextPromise;
this.isBeingDestroyed() || g.the.register(t, f);
}
/**
* 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, g.the.hasItem(t) && g.the.unregister(t);
}
}
}
function kt(a) {
return a.hasAttribute("data-cke-context");
}
function Et(a) {
let t = a;
for (; t; ) {
if (kt(t))
return t;
t = t.parentElement;
}
return null;
}
async function vt(a) {
const t = Et(a);
return t ? g.the.waitFor(t.id) : null;
}
const Pt = x(bt);
class p extends F {
static the = new p();
}
function Ct(a, t) {
const e = /* @__PURE__ */ new Set();
return (r) => {
let i = !1;
return a.model.enqueueChange({ isUndoable: !1 }, (n) => {
const s = a.model.document.getRoot(t);
if (s) {
for (const c of e)
r && c in r || (n.removeAttribute(c, s), e.delete(c), i = !0);
for (const [c, o] of Object.entries(r ?? {}))
n.setAttribute(c, o, s), e.add(c), i = !0;
}
}), i;
};
}
async function At() {
const { Plugin: a, FileRepository: t } = await import("ckeditor5");
return class extends a {
/**
* The name of the plugin.
*/
static get pluginName() {
return "PhoenixUploadAdapter";
}
static get requires() {
return [t];
}
/**
* Initializes the plugin.
*/
init() {
const { editor: r } = this, { plugins: i, config: n } = r, s = n.get("phoenixUpload.url");
if (!s || i.has("SimpleUploadAdapter") || i.has("Base64UploadAdapter") || i.has("CKFinderUploadAdapter"))
return;
const c = i.get(t);
c.createUploadAdapter = (o) => new Tt(o, s);
}
};
}
class Tt {
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 r = {}, i = rt();
i && (r["X-CSRF-Token"] = i);
try {
const n = await fetch(this.uploadUrl, {
method: "POST",
headers: r,
body: e,
signal: this.abortController.signal
});
if (!n.ok) {
let c = "Couldn't upload file!";
try {
const o = await n.json();
o?.error?.message && (c = o.error.message);
} catch {
}
throw new Error(c);
}
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 It({
editorId: a,
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: i } = this;
this.input = document.getElementById(`${a}_input`), this.input && (i.model.document.on("change:data", P(t, () => this.sync())), i.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 i = this.editor.getData();
this.input.value = i, 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;
}
};
}
const U = /* @__PURE__ */ Symbol("suppress-phoenix-sync");
async function xt(a) {
const { Plugin: t } = await import("ckeditor5"), { editorId: e, saveDebounceMs: r, events: i, pushEvent: n, handleEvent: s } = a;
return class extends t {
/**
* The name of the plugin.
*/
static get pluginName() {
return "SyncEditorWithPhoenix";
}
/**
* Initializes the plugin.
*/
init() {
const { editor: o } = this;
i.change && this.setupTypingContentPush(), i.blur && this.setupEventPush("blur"), i.focus && this.setupEventPush("focus"), i.ready && this.editor.once("ready", () => {
n("ckeditor5:ready", {
editorId: e,
data: D(o)
});
}), s("ckeditor5:set-data", ({ editorId: u, data: l }) => {
(at(u) || u === e) && o.setData(l);
});
}
/**
* Setups the content push event for the editor.
*/
setupTypingContentPush() {
const { editor: o } = this;
let u = null, l = !1;
const d = () => {
if (l)
return;
const m = D(o);
(!u || !nt(u, m)) && (n(
"ckeditor5:change",
{
editorId: e,
data: m
}
), u = m);
}, f = P(r, d);
o.model.document.on("change:data", P(10, (m) => {
if (Ot(m)) {
u = null;
return;
}
o.ui.focusTracker.isFocused ? f() : d();
})), o.once("ready", d), o.once("destroy", () => {
l = !0;
});
}
/**
* Setups the event push for the editor.
*/
setupEventPush(o) {
const { editor: u } = this, l = () => {
const { isFocused: d } = u.ui.focusTracker;
(d ? "focus" : "blur") === o && n(
`ckeditor5:${o}`,
{
editorId: e,
data: D(u)
}
);
};
u.ui.focusTracker.on("change:isFocused", l);
}
};
}
function D(a) {
return a.model.document.getRootNames().reduce((e, r) => (e[r] = a.getData({ rootName: r }), e), /* @__PURE__ */ Object.create({}));
}
function Ot(a) {
const t = a[U];
return delete a[U], !!t;
}
function Dt(a) {
let t = !1;
const e = (r) => {
t || (r[U] = !0);
};
return a.model.document.once("change:data", e, { priority: "highest" }), () => {
t = !0, a.model.document.off("change:data", e);
};
}
class G {
/**
* The DOM element being observed for attribute changes.
*/
el;
/**
* The unique identifier of the editor instance this sentinel is attached to.
*/
editorId;
/**
* The name of the specific root in a multi-root editor setup.
*/
rootName;
/**
* The name of the HTML attribute storing the value.
*/
valueAttrName;
/**
* The name of the HTML attribute storing the root attributes.
*/
rootAttrsAttrName;
/**
* The MutationObserver instance responsible for watching attribute changes on the element.
*/
observer = null;
/**
* A flag indicating whether the sentinel has been destroyed, used to prevent operations after cleanup.
*/
isDestroyed = !1;
/**
* Cleanup callbacks to be executed when the sentinel is destroyed.
*/
cleanupCallbacks = [];
/**
* The promise that resolves to the editor instance once it's registered.
* It can be either a MultiRootEditor or a DecoupledEditor, depending on the type of editor being used.
* It will be null if the editor is not registered yet or if the hook is being destroyed before the editor is registered.
*/
editorPromise = null;
/**
* When the editor is focused and the value attribute changes, we want to wait until it blurs to
* avoid disrupting the user while typing. This variable holds the pending value that should be applied
* once the editor blurs. It is set to null when there is no pending value or when the user makes changes in the editor,
* indicating that the pending value should be discarded.
*/
pendingValue = null;
/**
* Cache the previous value to avoid reacting to attribute changes that don't actually change the value.
* This can happen when the parent LiveView re-renders and sets the same value again, which would otherwise cause an
* unnecessary update in the editor.
*/
previousValue = null;
/**
* Updater created once the editor is ready. Tracks which root attributes
* were applied by this sentinel so it can clean them up independently of
* other consumers.
*/
attrsUpdater = null;
/**
* When the hook is mounted, we will wait for the editor to be registered and then set the initial value of the root.
* Accepts an options object to configure element, identifiers, and custom attribute names.
*/
constructor({
el: t,
editorId: e,
rootName: r,
valueAttrName: i = "data-cke-value",
rootAttrsAttrName: n = "data-cke-root-attrs"
}) {
this.el = t, this.editorId = e, this.rootName = r, this.valueAttrName = i, this.rootAttrsAttrName = n;
const { value: s } = this.attrs;
this.previousValue = s, this.editorPromise = p.the.execute(this.editorId, (c) => this.isDestroyed ? null : (this.setupSyncHandlers(c, this.rootName), c)), this.setupObserver();
}
/**
* Helper to read and parse attributes from the element.
* It uses dynamically provided attribute names.
*/
get attrs() {
return {
rootAttributes: it(this.el.getAttribute(this.rootAttrsAttrName)),
value: this.el.getAttribute(this.valueAttrName)
};
}
/**
* Sets up a MutationObserver to listen for attribute changes on the element.
*/
setupObserver() {
this.observer = new MutationObserver((t) => {
for (const e of t)
if (e.type === "attributes") {
this.handleUpdate();
break;
}
}), this.observer.observe(this.el, {
attributes: !0,
attributeFilter: [
this.valueAttrName,
this.rootAttrsAttrName
]
});
}
/**
* When the value attribute changes, we want to update the editor root value.
* However, if the editor is focused, we want to wait until it blurs to avoid disrupting the user while typing.
*/
async handleUpdate() {
const { value: t, rootAttributes: e } = this.attrs, r = await this.editorPromise;
if (!r || r.state === "destroyed" || this.isDestroyed)
return;
let i = () => {
};
r.model.enqueueChange({ isUndoable: !1 }, () => {
let n = this.attrsUpdater?.(e);
t !== this.previousValue && (this.previousValue = t, r.ui.focusTracker.isFocused ? this.pendingValue = t : (this.setRootValue(r, this.rootName, t), n = !0)), n && (i = Dt(r));
}), i();
}
/**
* Sets up focus-aware sync handlers on the editor.
* Registers cleanup via onBeforeDestroy.
*/
setupSyncHandlers(t, e) {
this.attrsUpdater = Ct(t, e), this.attrsUpdater(this.attrs.rootAttributes);
const r = () => {
this.pendingValue = null;
}, i = () => {
!t.ui.focusTracker.isFocused && this.pendingValue !== null && (this.setRootValue(t, e, this.pendingValue), this.pendingValue = null);
};
t.model.document.on("change:data", r), t.ui.focusTracker.on("change:isFocused", i), this.cleanupCallbacks.push(() => {
t.model.document.off("change:data", r), t.ui.focusTracker.off("change:isFocused", i);
});
}
/**
* Sets the value of a specific root in the editor.
*/
setRootValue(t, e, r) {
t.getData({ rootName: e }) !== r && t.setData({ [e]: r });
}
/**
* Disconnects the observer and cleans up editor event listeners.
* This should be called manually when the element is removed from the DOM.
*/
destroy() {
this.isDestroyed = !0, this.observer?.disconnect(), this.cleanupCallbacks.forEach((t) => t()), this.cleanupCallbacks = [];
}
}
class St extends I {
/**
* The promise that resolves to the editor instance once it's registered.
*/
editorPromise = null;
/**
* The sentinel instance responsible for tracking and updating root values and attributes.
*/
sentinel = 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: r, initialValue: i } = this.attrs, n = this.el.querySelector(`#${t}_input`);
this.sentinel = new G({
el: this.el,
valueAttrName: "data-cke-editable-initial-value",
rootAttrsAttrName: "data-cke-editable-root-attrs",
editorId: e,
rootName: r
}), this.editorPromise = p.the.execute(e, (s) => {
if (this.isBeingDestroyed())
return null;
const { ui: c, editing: o, model: u } = s;
if (u.document.getRoot(r))
return s;
s.addRoot(r, {
isUndoable: !1,
data: i
});
const l = this.el.querySelector("[data-cke-editable-content]"), d = c.view.createEditable(r, l);
if (c.addEditable(d), o.view.forceRender(), n) {
const f = Ut(n, s, r);
this.onBeforeDestroy(f);
}
return s;
});
}
/**
* Destroys the editable component. Unmounts root from the editor.
*/
async destroyed() {
const { rootName: t } = this.attrs;
this.el.style.display = "none", this.sentinel?.destroy(), this.sentinel = null;
const e = await this.editorPromise;
if (this.editorPromise = null, e && e.state !== "destroyed") {
const r = e.model.document.getRoot(t);
r && "detachEditable" in e && (e.ui.view.editables[t] && e.detachEditable(r), r.isAttached() && e.detachRoot(t, !1));
}
}
}
const Nt = x(St);
function Ut(a, t, e) {
const r = () => {
a.value = t.getData({ rootName: e });
}, i = P(200, r);
return t.model.document.on("change:data", i), r(), () => {
t.model.document.off("change:data", i);
};
}
class Vt extends I {
/**
* The promise that resolves to the editor instance.
*/
editorPromise = null;
/**
* The sentinel instance responsible for tracking and updating root values and attributes
* for single-root editors.
*/
sentinel = null;
/**
* Attributes for the editor instance.
*/
get attrs() {
const { el: t } = this, e = t.getAttribute.bind(t), r = t.hasAttribute.bind(t), i = {
editorId: e("id"),
contextId: e("data-cke-context-id"),
preset: mt(t),
editableHeight: z(e("data-cke-editable-height")),
watchdog: r("data-cke-watchdog"),
events: {
change: r("data-cke-change-event"),
blur: r("data-cke-blur-event"),
focus: r("data-cke-focus-event"),
ready: r("data-cke-ready-event")
},
saveDebounceMs: z(e("data-cke-save-debounce-ms")) ?? 400,
language: {
ui: e("data-cke-language") || "en",
content: e("data-cke-content-language") || "en"
}
};
return Object.defineProperty(this, "attrs", {
value: i,
writable: !1,
configurable: !1,
enumerable: !0
}), i;
}
/**
* Mounts the editor component.
*/
async mounted() {
const { editorId: t, preset: e } = this.attrs;
p.the.resetErrors(t), lt(e.type) || (this.sentinel = new G({
editorId: t,
el: this.el,
rootName: "main",
valueAttrName: "data-cke-initial-value",
rootAttrsAttrName: "data-cke-root-attrs"
}));
try {
this.editorPromise = this.createEditor();
const r = await this.editorPromise;
this.isBeingDestroyed() || (p.the.register(t, r), r.once("destroy", () => {
p.the.hasItem(t) && p.the.unregister(t);
}));
} catch (r) {
this.editorPromise = null, p.the.error(t, r);
}
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", this.sentinel?.destroy(), this.sentinel = null;
try {
const t = await this.editorPromise;
if (!t)
return;
const e = ut(t), r = gt(t);
e ? e.state !== "unavailable" && await e.context.remove(e.editorContextId) : r ? await r.destroy() : await t.destroy();
} finally {
this.editorPromise = null;
}
}
/**
* Creates the CKEditor instance.
*/
async createEditor() {
const { preset: t, editorId: e, contextId: r, editableHeight: i, events: n, saveDebounceMs: s, language: c, watchdog: o } = this.attrs, { customTranslations: u, type: l, license: d, config: { plugins: f, ...m } } = t;
let y = await dt(l);
const w = await (r ? g.the.waitFor(r) : vt(this.el));
if (o && !w) {
const h = await wt(y);
({ Constructor: y } = h), h.watchdog.on("restart", () => {
const b = h.watchdog.editor;
this.editorPromise = Promise.resolve(b), p.the.register(e, b);
});
}
const { loadedPlugins: k, hasPremium: Q } = await B(f);
v(l) && k.push(
await It({
editorId: e,
saveDebounceMs: s
})
), k.push(
...await Promise.all([
xt(
{
editorId: e,
saveDebounceMs: s,
events: n,
pushEvent: this.pushEvent.bind(this),
handleEvent: this.handleEvent.bind(this)
}
),
At()
])
);
const O = [
...await L(c, Q),
K(u?.dictionary || {})
].filter((h) => !W(h));
let E = _(e);
v(l) && (E = E.main || "");
const R = await (async () => {
let h = Y(e);
if (!(h instanceof HTMLElement) && !("main" in h)) {
const j = l === "decoupled" ? ["main"] : Object.keys(E);
X(h, j) || (h = await $t(e, j), E = _(e));
}
v(l) && "main" in h && (h = h.main);
let b = A(m);
b = T([...O].reverse(), c.ui, b);
const M = {
...b,
initialData: E,
licenseKey: d.key,
plugins: k,
language: c,
...O.length && {
translations: O
}
};
return !w || !(h instanceof HTMLElement) ? y.create(h, M) : (await ct({
context: w,
element: h,
creator: y,
config: M
})).editor;
})();
return v(l) && i && ft(R, i), R;
}
}
function X(a, t) {
return t.every((e) => a[e]);
}
async function $t(a, t) {
return ot(
() => {
const e = Y(a);
if (!X(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((r) => !e[r]).join(", ")}.`
);
return e;
},
{ timeOutAfter: 2e3, retryAfter: 100 }
);
}
const Rt = x(Vt);
class Mt extends I {
/**
* 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 = p.the.execute(t, (r) => {
if (this.isBeingDestroyed())
return;
const { ui: i } = r, n = jt(e), s = i.view[n];
if (!s) {
console.error(`Unknown UI part name: "${e}". Supported names are "toolbar" and "menubar".`);
return;
}
this.el.appendChild(s.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 jt(a) {
switch (a) {
case "toolbar":
return "toolbar";
case "menubar":
return "menuBarView";
default:
return null;
}
}
const zt = x(Mt), Bt = {
CKEditor5: Rt,
CKEditable: Nt,
CKUIPart: zt,
CKContext: Pt
};
export {
g as ContextsRegistry,
$ as CustomEditorPluginsRegistry,
p as EditorsRegistry,
Bt as Hooks,
ut as unwrapEditorContext,
gt as unwrapEditorWatchdog
};
//# sourceMappingURL=index.mjs.map