Add saved components: reusable HTML boxes, placed as copies or linked
A component (models.Component, component.graphql) is a named HTML box. "+ New box" now lists components and places a copy, as it did with the hard-coded starters; the canvas's new Components button (ComponentPanel) can also place one linked. A linked box has Box.componentId, its row's html is nil, and the resolvers fill in the component's html before answering (fillLinked), so saving the html in the box editor saves the component and every linked box on every page changes. Only the html is shared: title, geometry, frame and visibility stay each box's own. The box editor gains "Save as component" (makes one from an html box and links it) and, on a linked box, a banner with Detach (gives the box its own copy). updateBox refuses html on a linked box. Deleting a component detaches its boxes first, so no page changes. Layouts store the link and the html; loading relinks only if the component still exists. The built-in starters in templates.js are no longer listed directly: "Import built-ins" in the panel creates them as components (skipping names already taken), so they can be edited and deleted like the rest. The html helpers there are unchanged. Everything is @admin. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+16
-1
@@ -264,6 +264,21 @@ renders any page's boxes.
|
||||
page, load it on another. The copying happens on the server
|
||||
(`backend/graph/layout_helpers.go`); the browser only sees names and box
|
||||
counts. All of it is admin-only, since a layout keeps admin-only boxes.
|
||||
- **Components.** A **`Component`** (GraphQL type, `stores/components.js`) is
|
||||
a named HTML box. "+ New box" lists them and places a copy, an ordinary box.
|
||||
The "Components" button (`ComponentPanel.vue`) can also place one
|
||||
**linked**: the box has a `componentId`, the server answers with the
|
||||
component's html in its `html` (`fillLinked` in
|
||||
`backend/graph/component_helpers.go`), and saving the html in `BoxEditor`
|
||||
saves the component, so every linked box on every page changes. Only the
|
||||
html is shared; title, geometry, frame and visibility stay each box's own.
|
||||
"Save as component" in the editor makes a component from an html box and
|
||||
links it; "Detach" gives a linked box its own copy. Deleting a component
|
||||
detaches its boxes first, so no page changes. A layout keeps both the link
|
||||
and the html, and loading it links again only if the component still
|
||||
exists. The built-in starters in `templates.js` are not listed directly:
|
||||
"Import built-ins" in the panel makes them components, after which they can
|
||||
be edited or deleted like the rest. Admin-only throughout.
|
||||
- **Admin only.** A box or a page can be marked admin-only. The server never
|
||||
sends those to anyone else, so they are fit for private notes; admins see
|
||||
such boxes outlined, with a 🔒 in edit mode. The "Note" template starts
|
||||
@@ -301,7 +316,7 @@ renders any page's boxes.
|
||||
file through `@/uploads` (see "Uploading files") and puts an `<img>`/`<video>`
|
||||
tag for it at the cursor; "Choose upload" does the same with a file already
|
||||
stored, and "+ From uploads…" in the admin bar makes a box from one, as a
|
||||
drop would (`UploadPicker`). Starter HTML is in `templates.js`; links in a box
|
||||
drop would (`UploadPicker`). Built-in starter HTML is in `templates.js` (imported as components, above); links in a box
|
||||
need `target="_top"` or `_blank` (the Link templates set it), or they open
|
||||
inside the frame. A canvas given a `starter` has an import button in edit
|
||||
mode (it confirms first if the page isn't empty): only `/` has one, "Import
|
||||
|
||||
+28
-2
@@ -14,6 +14,11 @@
|
||||
* The list query returns boxes ordered by z, so a new box (given the top z)
|
||||
* belongs at the end. adminOnly boxes only come back for an admin — the
|
||||
* server filters them — so the canvas refetches when the session changes.
|
||||
*
|
||||
* A box with a `componentId` is linked to that component (stores/components.js):
|
||||
* the server answers with the component's html in `html`, and editing it goes
|
||||
* to the component. patchLinked() keeps every page already loaded in step when
|
||||
* a component changes, without refetching them.
|
||||
*/
|
||||
|
||||
import { createCrudStore } from "@/stores/createCrudStore";
|
||||
@@ -33,11 +38,15 @@ const BOX_FIELDS = `
|
||||
framed
|
||||
hideOnMobile
|
||||
adminOnly
|
||||
componentId
|
||||
`;
|
||||
|
||||
// The fields a duplicate copies. kind and widget/html are what make it the
|
||||
// same box; geometry is offset so the copy is visibly separate.
|
||||
const COPIED = ["page", "kind", "widget", "html", "title", "w", "h", "framed", "hideOnMobile", "adminOnly"];
|
||||
// same box — or componentId, which keeps a copy of a linked box linked;
|
||||
// geometry is offset so the copy is visibly separate.
|
||||
const COPIED = [
|
||||
"page", "kind", "widget", "html", "title", "w", "h", "framed", "hideOnMobile", "adminOnly", "componentId",
|
||||
];
|
||||
|
||||
const stores = new Map();
|
||||
|
||||
@@ -64,6 +73,11 @@ function defineFor(page) {
|
||||
const input = Object.fromEntries(COPIED.map((k) => [k, box[k]]));
|
||||
return create({ ...input, x: box.x + 20, y: box.y + 20, z: topZ() });
|
||||
},
|
||||
/** Swap in a box the server answered with from outside this store. */
|
||||
replaceLocal: (box) => {
|
||||
const idx = items.value.findIndex((b) => b.id === box.id);
|
||||
if (idx >= 0) items.value[idx] = box;
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -74,3 +88,15 @@ export function useBoxesStore(page) {
|
||||
if (!stores.has(page)) stores.set(page, defineFor(page));
|
||||
return stores.get(page)();
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply `patch` to every loaded box linked to component `componentId`, on
|
||||
* every page visited so far.
|
||||
*/
|
||||
export function patchLinked(componentId, patch) {
|
||||
for (const use of stores.values()) {
|
||||
for (const box of use().boxes) {
|
||||
if (box.componentId === componentId) Object.assign(box, patch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Saved components (the `Component` GraphQL type): named HTML boxes that can
|
||||
* be placed on any canvas page as a copy or linked — full CRUD, built on
|
||||
* createCrudStore(), plus the box-side actions.
|
||||
*
|
||||
* A linked box shows its component's html, so `update` is wrapped to push a
|
||||
* new html into every loaded page's boxes (stores/boxes.js patchLinked), and
|
||||
* `remove` unlinks them locally the way the server just did (each keeps the
|
||||
* html it showed). `uses` is kept roughly right locally (countUse) as this
|
||||
* tab places, detaches and deletes linked boxes, and the panel refetches the
|
||||
* list when it opens for the true figure.
|
||||
*
|
||||
* Admin only, so nothing fetches it until an admin opens the canvas's
|
||||
* Components panel or "+ New box" menu (views/home3/ComponentPanel.vue,
|
||||
* BoxCanvas.vue).
|
||||
*/
|
||||
|
||||
import { createCrudStore } from "@/stores/createCrudStore";
|
||||
import { gql } from "@/graphql";
|
||||
import { patchLinked, useBoxesStore } from "@/stores/boxes";
|
||||
import { TEMPLATES } from "@/views/home3/templates";
|
||||
|
||||
const COMPONENT_FIELDS = `
|
||||
id
|
||||
name
|
||||
title
|
||||
html
|
||||
w
|
||||
h
|
||||
framed
|
||||
adminOnly
|
||||
uses
|
||||
`;
|
||||
|
||||
// Matches BOX_FIELDS in stores/boxes.js, for the mutations that answer with
|
||||
// a box.
|
||||
const BOX_FIELDS = `
|
||||
id page kind widget html title x y w h z framed hideOnMobile adminOnly componentId
|
||||
`;
|
||||
|
||||
export const useComponentsStore = createCrudStore("components", {
|
||||
type: "Component",
|
||||
list: "components",
|
||||
fields: COMPONENT_FIELDS,
|
||||
// Created ones are put back in name order by sort() below.
|
||||
insert: "append",
|
||||
deleteReturns: "object",
|
||||
extend: ({ items, fetch, create, update, remove }) => {
|
||||
const sort = () => items.value.sort((a, b) => a.name.localeCompare(b.name));
|
||||
const countUse = (id, delta) => {
|
||||
const c = items.value.find((c) => c.id === id);
|
||||
if (c) c.uses = Math.max(0, c.uses + delta);
|
||||
};
|
||||
|
||||
return {
|
||||
countUse,
|
||||
|
||||
async create(input) {
|
||||
const created = await create(input);
|
||||
sort();
|
||||
return created;
|
||||
},
|
||||
|
||||
async update(id, input) {
|
||||
const updated = await update(id, input);
|
||||
if ("html" in input) patchLinked(id, { html: updated.html });
|
||||
sort();
|
||||
return updated;
|
||||
},
|
||||
|
||||
async remove(id) {
|
||||
await remove(id);
|
||||
patchLinked(id, { componentId: null });
|
||||
},
|
||||
|
||||
/**
|
||||
* Make html box `box` into a component named `name` and link it.
|
||||
* Throws on failure.
|
||||
*/
|
||||
async saveFromBox(box, name) {
|
||||
const data = await gql(
|
||||
`mutation SaveBoxAsComponent($id: ID!, $name: String!) {
|
||||
saveBoxAsComponent(id: $id, name: $name) { ${BOX_FIELDS} }
|
||||
}`,
|
||||
{ id: box.id, name },
|
||||
);
|
||||
useBoxesStore(box.page).replaceLocal(data.saveBoxAsComponent);
|
||||
await fetch();
|
||||
},
|
||||
|
||||
/** Give linked box `box` its own copy of the html. Throws on failure. */
|
||||
async detach(box) {
|
||||
const data = await gql(
|
||||
`mutation DetachBox($id: ID!) { detachBox(id: $id) { ${BOX_FIELDS} } }`,
|
||||
{ id: box.id },
|
||||
);
|
||||
useBoxesStore(box.page).replaceLocal(data.detachBox);
|
||||
countUse(box.componentId, -1);
|
||||
},
|
||||
|
||||
/**
|
||||
* Put `component` on page key `page` at `at` ({ x, y, z }): linked, or
|
||||
* as an ordinary box with a copy of its html. Answers with the new box.
|
||||
* Throws on failure.
|
||||
*/
|
||||
async place(component, page, at, linked) {
|
||||
const input = {
|
||||
kind: "html",
|
||||
title: component.title,
|
||||
w: component.w,
|
||||
h: component.h,
|
||||
framed: component.framed,
|
||||
adminOnly: component.adminOnly,
|
||||
...at,
|
||||
};
|
||||
if (linked) input.componentId = component.id;
|
||||
else input.html = component.html;
|
||||
const created = await useBoxesStore(page).create(input);
|
||||
if (linked) countUse(component.id, 1);
|
||||
return created;
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a component from each built-in starter in templates.js whose
|
||||
* name is free, and answer with how many were added. Deleted ones come
|
||||
* back; ones still there are left as they are. Throws on failure.
|
||||
*/
|
||||
async importBuiltins() {
|
||||
const taken = new Set(items.value.map((c) => c.name));
|
||||
let added = 0;
|
||||
for (const t of TEMPLATES) {
|
||||
if (taken.has(t.label)) continue;
|
||||
await create({
|
||||
name: t.label,
|
||||
title: t.title,
|
||||
html: t.html,
|
||||
w: t.size[0],
|
||||
h: t.size[1],
|
||||
framed: t.framed ?? true,
|
||||
adminOnly: t.adminOnly ?? false,
|
||||
});
|
||||
added++;
|
||||
}
|
||||
sort();
|
||||
return added;
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -30,14 +30,22 @@
|
||||
* The Layouts button saves the page as a named layout, or loads a saved one
|
||||
* onto it (LayoutPanel.vue, stores/layouts.js) — which is how a layout moves
|
||||
* from one page to another.
|
||||
*
|
||||
* "+ New box" offers the saved components (stores/components.js) as starters,
|
||||
* each placed as an ordinary box with a copy of its html, plus the widgets.
|
||||
* The Components button (ComponentPanel.vue) places them linked as well: a
|
||||
* linked box shows its component's html, so editing it in BoxEditor edits
|
||||
* every box linked to that component. Linked boxes are labelled with ⛓.
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { useMediaQuery } from "@vueuse/core";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useBoxesStore } from "@/stores/boxes";
|
||||
import { useBackgroundStore } from "@/stores/background";
|
||||
import { useComponentsStore } from "@/stores/components";
|
||||
import BackgroundEditor from "./BackgroundEditor.vue";
|
||||
import LayoutPanel from "./LayoutPanel.vue";
|
||||
import ComponentPanel from "./ComponentPanel.vue";
|
||||
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
|
||||
import UploadPicker from "@/components/util/UploadPicker.vue";
|
||||
import BoxFrame from "./BoxFrame.vue";
|
||||
@@ -46,7 +54,7 @@ import { panelWidth } from "./editorPrefs";
|
||||
import HtmlBox from "./HtmlBox.vue";
|
||||
import WidgetBox from "./WidgetBox.vue";
|
||||
import { WIDGETS } from "./widgetRegistry";
|
||||
import { TEMPLATES, imageHtml, videoHtml } from "./templates";
|
||||
import { imageHtml, videoHtml } from "./templates";
|
||||
import { isVideo, mediaSize, uploadFile } from "@/uploads";
|
||||
|
||||
const props = defineProps({
|
||||
@@ -72,8 +80,9 @@ store.fetch();
|
||||
const background = useBackgroundStore();
|
||||
background.show(props.page);
|
||||
onBeforeUnmount(() => background.hide(props.page));
|
||||
const backgroundOpen = ref(false);
|
||||
const layoutsOpen = ref(false);
|
||||
// Which of the left-hand panels is open: "background", "layouts",
|
||||
// "components" or null. They sit in the same place, so only one at a time.
|
||||
const panel = ref(null);
|
||||
const confirmation = ref(null);
|
||||
|
||||
const isMobile = useMediaQuery(MOBILE_QUERY);
|
||||
@@ -89,6 +98,12 @@ const editing = ref(false);
|
||||
const canEdit = computed(() => isAdmin.value && !isMobile.value);
|
||||
const inEditMode = computed(() => editing.value && canEdit.value);
|
||||
|
||||
// Admin only, so fetched on first entering edit mode, for "+ New box".
|
||||
const components = useComponentsStore();
|
||||
watch(inEditMode, (on) => {
|
||||
if (on && !components.loaded && !components.loading) components.fetch();
|
||||
});
|
||||
|
||||
const selectedId = ref(null);
|
||||
const selected = computed(() => store.boxes.find((b) => b.id === selectedId.value) ?? null);
|
||||
const preview = ref(null); // unsaved HTML for the selected box, from BoxEditor
|
||||
@@ -153,7 +168,10 @@ function onAction(box, action) {
|
||||
if (action === "front") run(() => store.bringToFront(box));
|
||||
else if (action === "back") run(() => store.sendToBack(box));
|
||||
else if (action === "duplicate") {
|
||||
run(async () => (selectedId.value = (await store.duplicate(box)).id));
|
||||
run(async () => {
|
||||
selectedId.value = (await store.duplicate(box)).id;
|
||||
if (box.componentId) components.countUse(box.componentId, 1);
|
||||
});
|
||||
} else if (action === "delete") {
|
||||
askConfirmation({
|
||||
title: "Delete box",
|
||||
@@ -162,7 +180,10 @@ function onAction(box, action) {
|
||||
}).then((confirmed) => {
|
||||
if (!confirmed) return;
|
||||
if (selectedId.value === box.id) selectedId.value = null;
|
||||
run(() => store.remove(box.id));
|
||||
run(async () => {
|
||||
await store.remove(box.id);
|
||||
if (box.componentId) components.countUse(box.componentId, -1);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -180,7 +201,8 @@ function finishConfirmation(confirmed) {
|
||||
}
|
||||
|
||||
function labelOf(box) {
|
||||
const name = box.title || (box.kind === "widget" ? box.widget : "HTML");
|
||||
let name = box.title || (box.kind === "widget" ? box.widget : "HTML");
|
||||
if (box.componentId) name = `⛓ ${name}`;
|
||||
return box.adminOnly ? `🔒 ${name}` : name;
|
||||
}
|
||||
|
||||
@@ -207,26 +229,31 @@ function addBox() {
|
||||
const choice = newChoice.value;
|
||||
newChoice.value = "";
|
||||
if (!choice) return;
|
||||
const [kind, key] = choice.split(":");
|
||||
const { x, y } = visibleOrigin();
|
||||
let input;
|
||||
if (kind === "widget") {
|
||||
const [w, h] = WIDGETS[key].size;
|
||||
input = { kind: "widget", widget: key, w, h };
|
||||
} else {
|
||||
const t = TEMPLATES[Number(key)];
|
||||
input = {
|
||||
kind: "html",
|
||||
html: t.html,
|
||||
title: t.title,
|
||||
w: t.size[0],
|
||||
h: t.size[1],
|
||||
framed: t.framed ?? true,
|
||||
adminOnly: t.adminOnly ?? false,
|
||||
};
|
||||
if (choice === "import") {
|
||||
run(() => components.importBuiltins());
|
||||
return;
|
||||
}
|
||||
const [kind, key] = choice.split(":");
|
||||
if (kind === "component") {
|
||||
const component = components.components.find((c) => c.id === key);
|
||||
if (component) placeComponent(component, false);
|
||||
return;
|
||||
}
|
||||
const { x, y } = visibleOrigin();
|
||||
const [w, h] = WIDGETS[key].size;
|
||||
run(async () => {
|
||||
const created = await store.create({ ...input, x, y, z: store.topZ() });
|
||||
const created = await store.create({ kind: "widget", widget: key, w, h, x, y, z: store.topZ() });
|
||||
selectedId.value = created.id;
|
||||
});
|
||||
}
|
||||
|
||||
// From "+ New box" (always a copy) or the Components panel (either). The
|
||||
// panel is closed, like selecting a box closes it, since the new box opens in
|
||||
// the editor and lands where the panel would cover it.
|
||||
function placeComponent(component, linked) {
|
||||
panel.value = null;
|
||||
run(async () => {
|
||||
const created = await components.place(component, props.page, { ...visibleOrigin(), z: store.topZ() }, linked);
|
||||
selectedId.value = created.id;
|
||||
});
|
||||
}
|
||||
@@ -323,27 +350,14 @@ async function placePicked(url) {
|
||||
// Leaving a box saves its unsaved HTML; BoxEditor does that itself as the
|
||||
// selection changes or it unmounts.
|
||||
function select(box) {
|
||||
backgroundOpen.value = false;
|
||||
layoutsOpen.value = false;
|
||||
panel.value = null;
|
||||
selectedId.value = box.id;
|
||||
}
|
||||
|
||||
// The background and layouts panels sit in the same place, so one closes the
|
||||
// other, and either closes the box editor.
|
||||
function toggleBackground() {
|
||||
backgroundOpen.value = !backgroundOpen.value;
|
||||
if (backgroundOpen.value) {
|
||||
layoutsOpen.value = false;
|
||||
selectedId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleLayouts() {
|
||||
layoutsOpen.value = !layoutsOpen.value;
|
||||
if (layoutsOpen.value) {
|
||||
backgroundOpen.value = false;
|
||||
selectedId.value = null;
|
||||
}
|
||||
// Opening a panel closes the others and the box editor.
|
||||
function togglePanel(name) {
|
||||
panel.value = panel.value === name ? null : name;
|
||||
if (panel.value) selectedId.value = null;
|
||||
}
|
||||
|
||||
function toggleEdit() {
|
||||
@@ -362,17 +376,22 @@ function toggleEdit() {
|
||||
<button type="button" class="bar-btn" :class="{ on: editing }" @click="toggleEdit">
|
||||
{{ editing ? "Done" : "Edit layout" }}
|
||||
</button>
|
||||
<button type="button" class="bar-btn" :class="{ on: backgroundOpen }" @click="toggleBackground">
|
||||
<button type="button" class="bar-btn" :class="{ on: panel === 'background' }" @click="togglePanel('background')">
|
||||
Background
|
||||
</button>
|
||||
<button type="button" class="bar-btn" :class="{ on: layoutsOpen }" @click="toggleLayouts">
|
||||
<button type="button" class="bar-btn" :class="{ on: panel === 'layouts' }" @click="togglePanel('layouts')">
|
||||
Layouts
|
||||
</button>
|
||||
<button type="button" class="bar-btn" :class="{ on: panel === 'components' }" @click="togglePanel('components')">
|
||||
Components
|
||||
</button>
|
||||
<template v-if="inEditMode">
|
||||
<select v-model="newChoice" class="bar-btn" @change="addBox">
|
||||
<option value="" disabled>+ New box…</option>
|
||||
<optgroup label="HTML">
|
||||
<option v-for="(t, i) in TEMPLATES" :key="t.label" :value="`html:${i}`">{{ t.label }}</option>
|
||||
<option v-if="!components.loaded" value="" disabled>Loading…</option>
|
||||
<option v-else-if="!components.components.length" value="import">Import built-in templates</option>
|
||||
<option v-for="c in components.components" :key="c.id" :value="`component:${c.id}`">{{ c.name }}</option>
|
||||
</optgroup>
|
||||
<optgroup label="Widget">
|
||||
<option v-for="name in Object.keys(WIDGETS)" :key="name" :value="`widget:${name}`">{{ name }}</option>
|
||||
@@ -454,8 +473,9 @@ function toggleEdit() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BackgroundEditor v-if="backgroundOpen && canEdit" :page="page" @close="backgroundOpen = false" />
|
||||
<LayoutPanel v-if="layoutsOpen && canEdit" :page="page" @close="layoutsOpen = false" />
|
||||
<BackgroundEditor v-if="panel === 'background' && canEdit" :page="page" @close="panel = null" />
|
||||
<LayoutPanel v-if="panel === 'layouts' && canEdit" :page="page" @close="panel = null" />
|
||||
<ComponentPanel v-if="panel === 'components' && canEdit" @close="panel = null" @place="placeComponent" />
|
||||
|
||||
<BoxEditor
|
||||
v-if="inEditMode && selected"
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
* the panel. Saving every keystroke would push half-written markup to
|
||||
* every visitor; leaving is the point it is finished.
|
||||
*
|
||||
* A box linked to a component (stores/components.js) edits the component: its
|
||||
* html is saved there, and so changes on every box linked to it. Detach gives
|
||||
* the box its own copy — an unsaved draft is kept, and then saves to this box
|
||||
* alone. An unlinked html box can be saved as a new component, which links it.
|
||||
*
|
||||
* "Insert upload" uploads a file (@/uploads) and puts a tag for it at the
|
||||
* cursor — the way to add pictures to an existing box, e.g. a gallery.
|
||||
* "Choose upload" does the same with a file that is already uploaded.
|
||||
@@ -25,6 +30,7 @@
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useBoxesStore } from "@/stores/boxes";
|
||||
import { useComponentsStore } from "@/stores/components";
|
||||
import { ACCEPT, tagFor, uploadFile } from "@/uploads";
|
||||
import CodeEditor from "./CodeEditor.vue";
|
||||
import { FONT_SIZE, PANEL_WIDTH, fontSize, panelWidth, setPanelWidth, zoom } from "./editorPrefs";
|
||||
@@ -49,13 +55,26 @@ const draftHtml = ref(props.box.html ?? "");
|
||||
const saving = ref(false);
|
||||
const dirty = computed(() => props.box.kind === "html" && draftHtml.value !== (props.box.html ?? ""));
|
||||
|
||||
const components = useComponentsStore();
|
||||
if (!components.loaded && !components.loading) components.fetch();
|
||||
const component = computed(() =>
|
||||
props.box.componentId ? components.components.find((c) => c.id === props.box.componentId) ?? null : null,
|
||||
);
|
||||
const savingAs = ref(false); // the "Save as component" name field is showing
|
||||
const componentName = ref("");
|
||||
|
||||
// Where a box's html is saved: its component if it is linked, else itself.
|
||||
function storeHtml(box, html) {
|
||||
return box.componentId ? components.update(box.componentId, { html }) : store.update(box.id, { html });
|
||||
}
|
||||
|
||||
// Save the draft of box `id` if it differs from what is stored. Fire and
|
||||
// forget: it runs as the editor moves on or unmounts, with nothing left to
|
||||
// show progress in, so a failure is only reported through `error`.
|
||||
function flush(id) {
|
||||
const box = store.boxes.find((b) => b.id === id);
|
||||
if (!box || box.kind !== "html" || draftHtml.value === (box.html ?? "")) return;
|
||||
store.update(id, { html: draftHtml.value }).catch((err) => emit("error", err));
|
||||
storeHtml(box, draftHtml.value).catch((err) => emit("error", err));
|
||||
}
|
||||
|
||||
// Switching to another box: save the old one's draft, drop its preview, start
|
||||
@@ -66,6 +85,7 @@ watch(
|
||||
flush(oldId);
|
||||
emit("preview", null);
|
||||
draftHtml.value = props.box.html ?? "";
|
||||
savingAs.value = false;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -94,7 +114,7 @@ async function saveHtml() {
|
||||
if (!dirty.value || saving.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
await store.update(props.box.id, { html: draftHtml.value });
|
||||
await storeHtml(props.box, draftHtml.value);
|
||||
emit("preview", null);
|
||||
} catch (err) {
|
||||
emit("error", err);
|
||||
@@ -103,6 +123,30 @@ async function saveHtml() {
|
||||
}
|
||||
}
|
||||
|
||||
// The draft is saved to the box first, so the component starts from what is
|
||||
// on screen.
|
||||
async function saveAsComponent() {
|
||||
const name = componentName.value.trim();
|
||||
if (!name) return;
|
||||
try {
|
||||
if (dirty.value) await store.update(props.box.id, { html: draftHtml.value });
|
||||
await components.saveFromBox(props.box, name);
|
||||
emit("preview", null);
|
||||
savingAs.value = false;
|
||||
componentName.value = "";
|
||||
} catch (err) {
|
||||
emit("error", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function detach() {
|
||||
try {
|
||||
await components.detach(props.box);
|
||||
} catch (err) {
|
||||
emit("error", err);
|
||||
}
|
||||
}
|
||||
|
||||
function saveNumber(field, event) {
|
||||
const value = Math.round(Number(event.target.value));
|
||||
if (!Number.isFinite(value) || value === props.box[field]) {
|
||||
@@ -208,6 +252,22 @@ function resizeByKey(event) {
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div v-if="box.componentId" class="linked">
|
||||
<span>
|
||||
Linked to <b>{{ component?.name ?? "a component" }}</b>
|
||||
<template v-if="component"> · {{ component.uses }} box{{ component.uses === 1 ? "" : "es" }}</template>
|
||||
— saving the html changes every linked box.
|
||||
</span>
|
||||
<button type="button" class="save small" title="Give this box its own copy of the html" @click="detach">
|
||||
Detach
|
||||
</button>
|
||||
</div>
|
||||
<form v-else-if="box.kind === 'html' && savingAs" class="linked" @submit.prevent="saveAsComponent">
|
||||
<input v-model="componentName" type="text" placeholder="Component name" required class="flex-1" />
|
||||
<button type="submit" class="save small">Save</button>
|
||||
<button type="button" class="save small" @click="savingAs = false">Cancel</button>
|
||||
</form>
|
||||
|
||||
<label v-if="box.kind === 'widget'" class="field">
|
||||
<span>Widget</span>
|
||||
<select :value="box.widget" @change="save({ widget: $event.target.value })">
|
||||
@@ -284,6 +344,15 @@ function resizeByKey(event) {
|
||||
>
|
||||
Choose upload
|
||||
</button>
|
||||
<button
|
||||
v-if="!box.componentId"
|
||||
type="button"
|
||||
class="save"
|
||||
title="Save this box as a reusable component, and link it"
|
||||
@click="savingAs = true"
|
||||
>
|
||||
Save as component
|
||||
</button>
|
||||
<button type="button" class="save" :disabled="!dirty || saving" @click="saveHtml">
|
||||
{{ saving ? "Saving…" : dirty ? "Save" : "Saved" }}
|
||||
</button>
|
||||
@@ -422,4 +491,24 @@ function resizeByKey(event) {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.save.small {
|
||||
padding: 0.1rem 0.6rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.linked {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.4rem 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
border: 1px dashed var(--color-primary);
|
||||
}
|
||||
.linked input {
|
||||
min-width: 0;
|
||||
padding: 3px 5px;
|
||||
color: var(--color-secondary);
|
||||
background: var(--color-surface-deep);
|
||||
border: 1px solid var(--color-quaternary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The admin's components panel, opened from BoxCanvas's "Components" button:
|
||||
* place a saved component on this page, linked or as a copy, and rename or
|
||||
* delete them (stores/components.js).
|
||||
*
|
||||
* Placing is BoxCanvas's job (it knows where the admin is looking), so this
|
||||
* only emits `place`. A component is made by "Save as component" in the box
|
||||
* editor, or by "Import built-ins", which turns the starters in templates.js
|
||||
* into components. Its html is edited through any box linked to it.
|
||||
*
|
||||
* The list is refetched on opening, because `uses` changes whenever a linked
|
||||
* box is placed or deleted, on any page.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import { useComponentsStore } from "@/stores/components";
|
||||
import OverlayShell from "@/components/util/OverlayShell.vue";
|
||||
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
|
||||
|
||||
const emit = defineEmits(["close", "place"]);
|
||||
const open = ref(true);
|
||||
|
||||
const components = useComponentsStore();
|
||||
components.fetch();
|
||||
|
||||
const busy = ref(false);
|
||||
const error = ref("");
|
||||
const notice = ref("");
|
||||
const deleteTarget = ref(null);
|
||||
const renaming = ref(null); // id of the component whose name is being edited
|
||||
const renameDraft = ref("");
|
||||
|
||||
function close() {
|
||||
open.value = false;
|
||||
emit("close");
|
||||
}
|
||||
|
||||
async function act(action, failure) {
|
||||
error.value = "";
|
||||
notice.value = "";
|
||||
busy.value = true;
|
||||
try {
|
||||
await action();
|
||||
return true;
|
||||
} catch (err) {
|
||||
error.value = err?.message || failure;
|
||||
return false;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startRename(component) {
|
||||
renaming.value = component.id;
|
||||
renameDraft.value = component.name;
|
||||
}
|
||||
|
||||
async function rename(component) {
|
||||
const ok = await act(
|
||||
() => components.update(component.id, { name: renameDraft.value.trim() }),
|
||||
"Failed to rename",
|
||||
);
|
||||
if (ok) renaming.value = null;
|
||||
}
|
||||
|
||||
function confirmDelete() {
|
||||
const component = deleteTarget.value;
|
||||
deleteTarget.value = null;
|
||||
act(() => components.remove(component.id), "Failed to delete");
|
||||
}
|
||||
|
||||
function importBuiltins() {
|
||||
act(async () => {
|
||||
const added = await components.importBuiltins();
|
||||
notice.value = added ? `Imported ${added}.` : "All the built-ins are already here.";
|
||||
}, "Failed to import");
|
||||
}
|
||||
|
||||
function describe(component) {
|
||||
const parts = [`${component.w}×${component.h}`];
|
||||
parts.push(component.uses ? `${component.uses} linked box${component.uses === 1 ? "" : "es"}` : "not linked anywhere");
|
||||
if (component.adminOnly) parts.push("admin only");
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
function deleteMessage(component) {
|
||||
const base = `Delete the component “${component.name}”?`;
|
||||
if (!component.uses) return base;
|
||||
return `${base} Boxes linked to it (${component.uses}) keep its html as their own copy, so no page changes.`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<OverlayShell v-model="open" title="Components" @close="close">
|
||||
<div class="component-panel bdr-2 bg-surface">
|
||||
<h3>Components</h3>
|
||||
<p class="hint">
|
||||
Linked boxes share the component's html: editing one edits them all. A copy is an ordinary box.
|
||||
Save a box as a component from the box editor.
|
||||
</p>
|
||||
|
||||
<p v-if="components.error" class="text-tertiary">Couldn't load the components.</p>
|
||||
<p v-else-if="components.loaded && !components.components.length" class="hint">
|
||||
No components yet. Import the built-in starters, or save a box from the box editor.
|
||||
</p>
|
||||
<ul v-else class="list">
|
||||
<li v-for="component in components.components" :key="component.id">
|
||||
<form v-if="renaming === component.id" class="row" @submit.prevent="rename(component)">
|
||||
<input v-model="renameDraft" type="text" required class="flex-1" />
|
||||
<button type="submit" class="bar-btn small" :disabled="busy">Save</button>
|
||||
<button type="button" class="bar-btn small" @click="renaming = null">Cancel</button>
|
||||
</form>
|
||||
<template v-else>
|
||||
<span class="name">{{ component.name }}</span>
|
||||
<span class="hint">{{ describe(component) }}</span>
|
||||
<span class="row">
|
||||
<button type="button" class="bar-btn small" @click="emit('place', component, true)">Place linked</button>
|
||||
<button type="button" class="bar-btn small" @click="emit('place', component, false)">Place copy</button>
|
||||
<button type="button" class="bar-btn small" @click="startRename(component)">Rename</button>
|
||||
<button type="button" class="bar-btn small danger" @click="deleteTarget = component">Delete</button>
|
||||
</span>
|
||||
</template>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="row">
|
||||
<button type="button" class="bar-btn" @click="close">Close</button>
|
||||
<button
|
||||
type="button"
|
||||
class="bar-btn"
|
||||
:disabled="busy || !components.loaded"
|
||||
title="Add the starters from templates.js that aren't here yet"
|
||||
@click="importBuiltins"
|
||||
>
|
||||
Import built-ins
|
||||
</button>
|
||||
<span v-if="busy" class="hint">Working…</span>
|
||||
<span v-else-if="notice" class="hint">{{ notice }}</span>
|
||||
</div>
|
||||
<p v-if="error" class="text-tertiary">{{ error }}</p>
|
||||
</div>
|
||||
</OverlayShell>
|
||||
|
||||
<ConfirmDialog
|
||||
v-if="deleteTarget"
|
||||
:model-value="true"
|
||||
title="Delete component"
|
||||
:message="deleteMessage(deleteTarget)"
|
||||
confirm-label="Delete"
|
||||
@confirm="confirmDelete"
|
||||
@cancel="deleteTarget = null"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.component-panel {
|
||||
position: fixed;
|
||||
top: 80px;
|
||||
left: 16px;
|
||||
z-index: 65;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
width: min(420px, calc(100vw - 32px));
|
||||
max-height: calc(100vh - 100px);
|
||||
overflow-y: auto;
|
||||
padding: 0.75rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.list li {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid var(--color-quaternary);
|
||||
}
|
||||
.name {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.bar-btn {
|
||||
padding: 0.25rem 0.75rem;
|
||||
color: var(--color-primary);
|
||||
background: var(--color-link-bg);
|
||||
border: 2px solid var(--color-quaternary);
|
||||
font-family: var(--font-heading);
|
||||
font-size: 1.1rem;
|
||||
letter-spacing: 0.025em;
|
||||
cursor: pointer;
|
||||
}
|
||||
.bar-btn:hover {
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
.bar-btn:disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
.bar-btn.small {
|
||||
padding: 0.1rem 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.bar-btn.danger:hover {
|
||||
border-color: var(--color-tertiary);
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,16 @@
|
||||
/**
|
||||
* Starter HTML for the "New box" menu. Each runs inside the sandboxed iframe
|
||||
* (see HtmlBox.vue), so scripts work but can only reach APIs that allow
|
||||
* cross-origin requests from an opaque origin — i.e. that answer with
|
||||
* `Access-Control-Allow-Origin: *` and need no key. Open-Meteo is one.
|
||||
* The built-in starter HTML. The "+ New box" menu no longer reads TEMPLATES
|
||||
* directly: it lists saved components, and TEMPLATES is what the Components
|
||||
* panel's "Import built-ins" turns into components (stores/components.js), so
|
||||
* they can be edited and deleted like any other. Changing an entry here only
|
||||
* reaches a site whose admin imports it again (after deleting the old one).
|
||||
* The helpers at the bottom are still used directly, by dropped uploads and
|
||||
* the starter layouts.
|
||||
*
|
||||
* Each runs inside the sandboxed iframe (see HtmlBox.vue), so scripts work but
|
||||
* can only reach APIs that allow cross-origin requests from an opaque origin —
|
||||
* i.e. that answer with `Access-Control-Allow-Origin: *` and need no key.
|
||||
* Open-Meteo is one.
|
||||
*
|
||||
* The site's colour and font tokens are already defined in the frame
|
||||
* (frameStyles.js), so templates use var(--color-…) freely.
|
||||
@@ -158,8 +166,9 @@ const videoHtml = (src) => `<style>
|
||||
<video src="${src}" controls loop muted></video>`;
|
||||
|
||||
/**
|
||||
* Menu entries; `size` is [w, h] in canvas px. `adminOnly` sets the new
|
||||
* box's flag, which can be changed afterwards in the editor.
|
||||
* Built-in starters; `label` becomes the component's name and `size` ([w, h]
|
||||
* in canvas px) its default size. `adminOnly` sets a new box's flag, which can
|
||||
* be changed afterwards in the editor.
|
||||
*/
|
||||
export const TEMPLATES = [
|
||||
{ label: "Note (admin only)", title: "Note", html: NOTE, size: [260, 200], framed: false, adminOnly: true },
|
||||
|
||||
Reference in New Issue
Block a user