kirbyuse
Version:
Collection of Vue Composition utilities for Kirby CMS
327 lines (312 loc) • 9.32 kB
JavaScript
const globalVue = window.Vue;
function usePanel() {
return window.panel;
}
function useApi() {
return usePanel().api;
}
function useApp() {
return usePanel().app;
}
function useBlock(props, emit) {
const field = (name, fallback = null) => {
let field2 = null;
for (const tab of Object.values(
props.fieldset.tabs ?? {}
)) {
if (tab.fields[name]) {
field2 = tab.fields[name];
}
}
return field2 ?? fallback;
};
const open = () => {
emit?.("open");
};
const update = (content) => {
emit?.("update", {
...props.content,
...content
});
};
return {
field,
open,
update
};
}
const isKirby5 = () => window.panel.plugins.viewButtons !== void 0;
const isKirby4 = () => !isKirby5();
function useStore() {
if (isKirby5()) {
return new Proxy({}, {
get() {
throw new Error(
"Vuex store is not available. Are you using Kirby 5? Use the `useContent` composable instead."
);
}
});
}
const store = usePanel().app.$store;
return store;
}
function useContent() {
const panel = usePanel();
const store = useStore();
const _isKirby5 = isKirby5();
const currentContent = _isKirby5 ? computed(() => panel.view.props.content) : computed(() => store.getters["content/values"]());
const contentChanges = _isKirby5 ? computed(() => panel.content.changes()) : computed(() => store.getters["content/changes"]());
const hasChanges = _isKirby5 ? computed(() => Object.keys(contentChanges.value).length > 0) : computed(() => store.getters["content/hasChanges"]());
const content = _isKirby5 ? panel.content : new Proxy({}, {
get() {
return () => {
};
}
});
const update = async (values, save = true) => {
if (!_isKirby5 && values) {
for (const [key, value] of Object.entries(values)) {
store.dispatch("content/update", [key, value]);
}
}
const viewContent = content.merge(values);
if (save) {
await content.save(viewContent);
}
};
return {
// Properties
content,
// Reactive getters
currentContent,
contentChanges,
hasChanges,
// Methods
update
};
}
function useDialog() {
function openTextDialog(text) {
let result = false;
return new Promise((resolve) => {
const panel = usePanel();
panel.dialog.open({
component: "k-text-dialog",
props: { text },
on: {
// Close event will always be triggered, even on submit
close: () => {
setTimeout(() => {
resolve(result);
}, 25);
},
submit: () => {
result = true;
panel.dialog.close();
}
}
});
});
}
function openFieldsDialog(props) {
let result;
return new Promise((resolve) => {
const panel = usePanel();
panel.dialog.open({
component: "k-form-dialog",
props,
on: {
// Close event will always be triggered, even on submit
close: () => {
setTimeout(() => {
resolve(result);
}, 25);
},
submit: (event) => {
result = event;
panel.dialog.close();
}
}
});
});
}
return {
openTextDialog,
openFieldsDialog
};
}
function useI18n() {
const panel = usePanel();
function t(value) {
if (!value || typeof value === "string") return value;
return value[panel.translation.code] ?? Object.values(value)[0];
}
return {
t
};
}
function useSection() {
const api = useApi();
const load = ({ parent, name }) => api.get(`${parent}/sections/${name}`);
return {
load
};
}
const LOG_LEVELS = {
error: 0,
warn: 1,
log: 2,
info: 3,
success: 3
};
function createLogger(tag) {
const reporter = new BrowserReporter();
return new Proxy({}, {
get(target, prop) {
return (...args) => {
reporter.log({
level: LOG_LEVELS[prop],
type: prop,
tag,
args
});
};
}
});
}
class BrowserReporter {
defaultColor = "#7f8c8d";
// Gray
levelColorMap = {
0: "#c0392b",
// Red
1: "#f39c12",
// Yellow
3: "#00BCD4"
// Cyan
};
typeColorMap = {
success: "#2ecc71"
// Green
};
constructor() {
}
log(logEvent) {
const consoleLogFn = resolveLogFn(logEvent.level);
const type = logEvent.type === "log" ? "" : logEvent.type;
const tag = logEvent.tag || "";
const color = this.typeColorMap[logEvent.type] || this.levelColorMap[logEvent.level] || this.defaultColor;
const style = `
background: ${color};
border-radius: 0.5em;
color: white;
font-weight: bold;
padding: 2px 0.5em;
`.trimStart();
const badge = `%c${[tag, type].filter(Boolean).join(":")}`;
if (typeof logEvent.args[0] === "string") {
consoleLogFn(
`${badge}%c ${logEvent.args[0]}`,
style,
// Empty string as style resets to default console style
"",
...logEvent.args.slice(1)
);
} else {
consoleLogFn(badge, style, ...logEvent.args);
}
}
}
function resolveLogFn(level) {
if (level < 1) return console.error;
return console.log;
}
const registeredAssets = [];
const moduleCache = /* @__PURE__ */ new Map();
async function registerPluginAssets(assets) {
if (!Array.isArray(assets)) {
throw new TypeError(`Expected an array, got ${typeof assets}`);
}
for (const asset of assets) {
if (!registeredAssets.some((existing) => existing.filename === asset.filename)) {
registeredAssets.push(asset);
}
}
}
function resolvePluginAsset(filename) {
if (registeredAssets.length === 0) {
throw new Error("Plugin assets not registered");
}
const asset = registeredAssets.find((asset2) => asset2.filename === filename);
if (!asset) {
throw new Error(`Plugin asset "${filename}" not found`);
}
return asset;
}
async function loadPluginModule(filename) {
if (!filename.endsWith(".js")) {
filename += ".js";
}
if (moduleCache.has(filename)) {
return moduleCache.get(filename);
}
const asset = resolvePluginAsset(filename);
const mod = await import(
/* @vite-ignore */
asset.url
);
moduleCache.set(filename, mod);
return mod;
}
const computed = globalVue.computed;
const customRef = globalVue.customRef;
const defineAsyncComponent = globalVue.defineAsyncComponent;
const defineComponent = globalVue.defineComponent;
const effectScope = globalVue.effectScope;
const getCurrentInstance = globalVue.getCurrentInstance;
const getCurrentScope = globalVue.getCurrentScope;
const h = globalVue.h;
const inject = globalVue.inject;
const isProxy = globalVue.isProxy;
const isReactive = globalVue.isReactive;
const isReadonly = globalVue.isReadonly;
const isRef = globalVue.isRef;
const isShallow = globalVue.isShallow;
const markRaw = globalVue.markRaw;
const nextTick = globalVue.nextTick;
const onActivated = globalVue.onActivated;
const onBeforeMount = globalVue.onBeforeMount;
const onBeforeUnmount = globalVue.onBeforeUnmount;
const onBeforeUpdate = globalVue.onBeforeUpdate;
const onDeactivated = globalVue.onDeactivated;
const onErrorCaptured = globalVue.onErrorCaptured;
const onMounted = globalVue.onMounted;
const onRenderTracked = globalVue.onRenderTracked;
const onRenderTriggered = globalVue.onRenderTriggered;
const onScopeDispose = globalVue.onScopeDispose;
const onServerPrefetch = globalVue.onServerPrefetch;
const onUnmounted = globalVue.onUnmounted;
const onUpdated = globalVue.onUpdated;
const provide = globalVue.provide;
const proxyRefs = globalVue.proxyRefs;
const reactive = globalVue.reactive;
const readonly = globalVue.readonly;
const ref = globalVue.ref;
const shallowReactive = globalVue.shallowReactive;
const shallowReadonly = globalVue.shallowReadonly;
const shallowRef = globalVue.shallowRef;
const toRaw = globalVue.toRaw;
const toRef = globalVue.toRef;
const toRefs = globalVue.toRefs;
const triggerRef = globalVue.triggerRef;
const unref = globalVue.unref;
const useAttrs = globalVue.useAttrs;
const useCssModule = globalVue.useCssModule;
const useCssVars = globalVue.useCssVars;
const useListeners = globalVue.useListeners;
const useSlots = globalVue.useSlots;
const watch = globalVue.watch;
const watchEffect = globalVue.watchEffect;
const watchPostEffect = globalVue.watchPostEffect;
const watchSyncEffect = globalVue.watchSyncEffect;
export { computed, createLogger, customRef, defineAsyncComponent, defineComponent, effectScope, getCurrentInstance, getCurrentScope, globalVue, h, inject, isKirby4, isKirby5, isProxy, isReactive, isReadonly, isRef, isShallow, loadPluginModule, markRaw, nextTick, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, provide, proxyRefs, reactive, readonly, ref, registerPluginAssets, resolvePluginAsset, shallowReactive, shallowReadonly, shallowRef, toRaw, toRef, toRefs, triggerRef, unref, useApi, useApp, useAttrs, useBlock, useContent, useCssModule, useCssVars, useDialog, useI18n, useListeners, usePanel, useSection, useSlots, useStore, watch, watchEffect, watchPostEffect, watchSyncEffect };