Page Menu
Home
Sealhub
Search
Configure Global Search
Log In
Files
F22417456
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Flag For Later
Award Token
Authored By
Unknown
Size
36 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/src/component-preview-actions.ts b/src/component-preview-actions.ts
index db91bca..c0622de 100644
--- a/src/component-preview-actions.ts
+++ b/src/component-preview-actions.ts
@@ -1,588 +1,587 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable @typescript-eslint/consistent-type-assertions */
import type { Registry, TableData } from "@sealcode/jdd";
import {
List,
makeSimpleEnglishJDDContext,
NestedComponentValue,
Table,
} from "@sealcode/jdd";
import { isTableData, isTableRegularRow } from "@sealcode/jdd";
import objectPath from "object-path";
import type { JDDPageState } from "./jdd-page.js";
import type {
StatefulPageAction,
StatefulPageActionArgument,
} from "@sealcode/sealgen";
import type JDDPage from "./jdd-page.js";
import { makeJSONDialogTextareaName } from "./inputs/component-input-component.js";
function moveElement<T>(
array: Array<T>,
fromIndex: number,
toIndex: number
): Array<T> {
const element = array.splice(fromIndex, 1)[0];
array.splice(toIndex, 0, element as T);
return array;
}
export function getComponentData(
state: JDDPageState,
arg_path: string[],
registry: Registry
) {
const index_arg = arg_path[1];
if (!index_arg) {
throw new Error("Missing component index in arg path");
}
const component_index = parseInt(index_arg);
const component_args = state.components[component_index]?.args || {};
const component_name =
state.components[component_index]?.component_name || "";
const component = registry.get(component_name);
const arg_path_within_component = arg_path.slice(3); // remove "components" and the index of the component and "args"
const [argument, , argument_value] = component?.getArgumentAtPath(
makeSimpleEnglishJDDContext({ registry }),
arg_path_within_component,
component_args
) || [null, null, null];
return {
component_index,
component_args,
component_name,
component,
argument,
argument_value,
arg_path_within_component,
};
}
export const ComponentPreviewActions = (<const>{
add_array_item: async ({
ctx,
state,
args: [arg_path],
page,
}: StatefulPageActionArgument<JDDPageState, [string[]]>) => {
const {
component_name,
component,
argument,
arg_path_within_component,
argument_value,
} = getComponentData(state, arg_path, (page as JDDPage).registry);
if (!component) {
console.error("unknown component: ", component_name);
return state;
}
if (!argument) {
console.error(
"Didn't find a list argument at this path",
arg_path_within_component
);
console.debug("Found this instead:", argument);
return state;
}
if (!(argument instanceof List)) {
throw new Error(
`Expected argument in path ${arg_path.join(
"."
)} to be an instance of List`
);
}
objectPath.insert(
state,
arg_path,
await argument.item_type.getFreshValue(
(page as JDDPage).makeJDDContext(ctx)
),
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
Array.isArray(argument_value) ? argument_value.length : 0
);
return state;
},
remove_array_item: ({
state,
args: [arg_path, index_to_remove],
}: StatefulPageActionArgument<
JDDPageState,
[string[], number]
>): JDDPageState => {
objectPath.del(state, [...arg_path, index_to_remove]);
return state;
},
move_array_item_up: async ({
state,
args: [arg_path, element_index],
}: StatefulPageActionArgument<
JDDPageState,
[string[], number]
>): Promise<JDDPageState> => {
const array_values = objectPath.get(state, arg_path) as unknown[];
const curr = array_values[element_index];
const prev = array_values[element_index - 1];
if (!prev || !curr) {
throw new Error("No element at such index or cannot move it up");
}
[array_values[element_index - 1], array_values[element_index]] = [
curr,
prev,
];
return state;
},
move_array_item_down: async ({
state,
args: [arg_path, element_index],
}: StatefulPageActionArgument<
JDDPageState,
[string[], number]
>): Promise<JDDPageState> => {
const array_values = objectPath.get(state, arg_path) as unknown[];
const curr = array_values[element_index];
const next = array_values[element_index + 1];
if (!next || !curr) {
throw new Error("No element at such index or cannot move it up");
}
[array_values[element_index], array_values[element_index + 1]] = [
next,
curr,
];
return state;
},
change_component: async ({
ctx,
inputs,
state,
page,
}: StatefulPageActionArgument<JDDPageState, []>): Promise<JDDPageState> => {
const component_name = inputs.component;
if (!component_name || typeof component_name !== "string") {
throw new Error(
"Missing input: 'component' for action change_component. It should contain the name of the new component type"
);
}
const component = (page as JDDPage).registry.get(component_name);
if (!component) {
throw new Error(
`Unknown or disallowed component name: ${component_name}`
);
}
return {
...state,
components: [
{
component_name: component_name,
args:
(await component?.getFreshValues(
(page as JDDPage).makeJDDContext(ctx)
)) || {},
},
],
};
},
randomize_args: async ({
ctx,
state,
page,
args: [component_index_str],
}: StatefulPageActionArgument<
JDDPageState,
[string]
>): Promise<JDDPageState> => {
const { component_index, component } = getComponentData(
state,
["components", component_index_str],
(page as JDDPage).registry
);
const component_data = state.components[component_index];
if (!component_data) {
throw new Error("Missing component data");
}
component_data.args =
(await component?.getExampleValues(
(page as JDDPage).makeJDDContext(ctx)
)) || {};
return {
...state,
};
},
add_table_row: async ({
ctx,
state,
page,
args: [arg_path, columns, type = "row"],
}: StatefulPageActionArgument<
JDDPageState,
[string[], number, "header" | "row" | undefined]
>) => {
const jdd_context = (page as JDDPage).makeJDDContext(ctx);
const { argument } = getComponentData(
state,
arg_path,
(page as JDDPage).registry
);
let row;
if (!argument) {
console.error("Unknown component at path", arg_path);
return state;
}
if (!(argument instanceof Table)) {
throw new Error(
`Expected argument at path ${arg_path.join(
"."
)} to be of type Table`
);
}
if (type == "header") {
row = {
type: "header",
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
header_content:
await argument.header_type.getFreshValue(jdd_context),
};
} else {
const cells = [];
for (let i = 0; i < columns; i++) {
cells.push(
// eslint-disable-next-line no-await-in-loop
await argument.cell_type.getFreshValue(jdd_context)
);
}
row = { type: "row", cells };
}
objectPath.push(state, [...arg_path, "rows"], row);
return state;
},
add_table_column: async ({
ctx,
state,
page,
args: [arg_path],
}: StatefulPageActionArgument<JDDPageState, [string[]]>) => {
const { argument } = getComponentData(
state,
arg_path,
(page as JDDPage).registry
) as unknown as {
argument: Table<unknown, unknown>;
};
if (!argument) {
console.error("Unknown component at path", arg_path);
return state;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const tableData: TableData<unknown, unknown> = objectPath.get(
state,
arg_path
);
if (!isTableData(tableData)) {
throw new Error("wrong table data");
}
// eslint-disable-next-line @typescript-eslint/no-for-in-array
for (const i in tableData.rows) {
const row = tableData.rows[i];
if (isTableRegularRow(row)) {
row.cells.push(
// eslint-disable-next-line no-await-in-loop
await argument.cell_type.getFreshValue(
(page as JDDPage).makeJDDContext(ctx)
)
);
}
}
objectPath.set(state, arg_path, tableData);
return state;
},
remove_table_column: ({
state,
args: [arg_path, column_index_to_remove],
}: StatefulPageActionArgument<
JDDPageState,
[string[], number]
>): JDDPageState => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const tableData: TableData<unknown, unknown> = objectPath.get(
state,
arg_path
);
if (!isTableData(tableData)) {
throw new Error("wrong table data");
}
// eslint-disable-next-line @typescript-eslint/no-for-in-array
for (const i in tableData.rows) {
const row = tableData.rows[i];
if (isTableRegularRow(row)) {
row.cells = row.cells.filter(
(_, i) => i != column_index_to_remove
);
}
}
objectPath.set(state, arg_path, tableData);
return state;
},
remove_table_row: ({
state,
args: [arg_path, row_index],
}: StatefulPageActionArgument<
JDDPageState,
[string[], number]
>): JDDPageState => {
objectPath.del(state, [...arg_path, "rows", row_index]);
return state;
},
move_table_column_right: ({
state,
page,
args: [arg_path, column_index],
}: StatefulPageActionArgument<JDDPageState, [string[], number]>) => {
const { component_args } = getComponentData(
state,
arg_path,
(page as JDDPage).registry
);
const last_path_element = arg_path.at(-1);
if (!last_path_element) {
throw new Error("arg path is empty");
}
const data = objectPath.get<unknown>(
component_args,
last_path_element,
""
);
if (!isTableData(data)) {
throw new Error(
"Expected arg value for a table to be properly shaped"
);
}
for (const row of data.rows) {
if (row.type == "row") {
moveElement(row.cells, column_index, column_index + 1);
}
}
objectPath.set(state, [...arg_path, "rows"], data.rows);
return state;
},
move_table_row_down: ({
state,
page,
args: [arg_path, row_index],
}: StatefulPageActionArgument<JDDPageState, [string[], number]>) => {
const { component_args } = getComponentData(
state,
arg_path,
(page as JDDPage).registry
);
const last_path_element = arg_path.at(-1);
if (!last_path_element) {
throw new Error("arg path is empty");
}
const data = objectPath.get<unknown>(
component_args,
last_path_element,
""
);
if (!isTableData(data)) {
throw new Error(
"Expected arg value for a table to be properly shaped"
);
}
moveElement(data.rows, row_index, row_index + 1);
objectPath.set(state, [...arg_path, "rows"], data.rows);
return state;
},
change_size: ({
state,
inputs,
}: StatefulPageActionArgument<JDDPageState>) => {
return {
...state,
preview_size: inputs.size,
};
},
add_component: async ({
ctx,
state,
inputs,
page,
}: StatefulPageActionArgument<JDDPageState, []>): Promise<JDDPageState> => {
const component_name = inputs.component;
if (!component_name) {
throw new Error("Missing component name");
}
const component = (page as JDDPage).registry.get(component_name);
return {
...state,
components: [
...state.components,
{
component_name: component_name,
args:
(await component?.getFreshValues(
(page as JDDPage).makeJDDContext(ctx)
)) || {},
},
],
};
},
remove_component: async ({
state,
args: [component_index],
}: StatefulPageActionArgument<
JDDPageState,
[number]
>): Promise<JDDPageState> => {
const newComponentState = [...state.components];
newComponentState.splice(component_index, 1);
return {
...state,
components: newComponentState,
};
},
move_component_up: async ({
state,
args: [component_index],
}: StatefulPageActionArgument<
JDDPageState,
[number]
>): Promise<JDDPageState> => {
const newComps = [...state.components];
const prev = newComps[component_index - 1];
const curr = newComps[component_index];
if (!prev || !curr) {
throw new Error("No component at such index or cannot move it up");
}
[newComps[component_index], newComps[component_index - 1]] = [
prev,
curr,
];
return { ...state, components: newComps };
},
move_component_down: async ({
state,
args: [component_index],
}: StatefulPageActionArgument<
JDDPageState,
[number]
>): Promise<JDDPageState> => {
const newComps = [...state.components];
const next = newComps[component_index + 1];
const curr = newComps[component_index];
if (!next || !curr) {
throw new Error("No component at such index or cannot move it up");
}
[newComps[component_index], newComps[component_index + 1]] = [
next,
curr,
];
return { ...state, components: newComps };
},
remove_file: async ({
state,
args: [arg_path],
}: StatefulPageActionArgument<
JDDPageState,
[string[]]
>): Promise<JDDPageState> => {
objectPath.set(state, arg_path, null);
return state;
},
replace_state: async ({
ctx,
state,
inputs,
page,
}: StatefulPageActionArgument<JDDPageState>): Promise<JDDPageState> => {
const new_state = (await (page as JDDPage).deserializeState(
ctx,
inputs["state_override"] || "{}"
)) as JDDPageState;
return {
...new_state,
preview_size: state.preview_size,
};
},
replace_component_with_json: async ({
ctx,
state,
inputs,
page,
args: [target_arg_path],
}: StatefulPageActionArgument<
JDDPageState,
[string[]]
>): Promise<JDDPageState> => {
- console.log("Action replacing at", target_arg_path);
const new_state = (await (page as JDDPage).deserializeState(
ctx,
inputs["state_override"] || "{}"
)) as JDDPageState;
const json = inputs[makeJSONDialogTextareaName(target_arg_path)];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const storage = JSON.parse(json || "{}");
const registry = (page as JDDPage).registry;
let new_args: Record<string, unknown> | NestedComponentValue = {};
const jdd_context = makeSimpleEnglishJDDContext({
registry,
file_manager: ctx.$context.app.fileManager,
});
if (target_arg_path.length > 2) {
// we're in nested component territory
new_args = await NestedComponentValue.fromStorage(
jdd_context,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
storage
);
} else {
const component = registry.get(storage.component_name);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const component_name = storage.component_name;
if (typeof component_name != "string") {
throw new Error("Component name should be a string");
}
if (!component) {
throw new Error("Unknown component: " + component_name);
}
new_args = {
component_name: storage.component_name,
args: await component?.convertStorageToParsed(
jdd_context,
storage.args
),
};
}
objectPath.set(new_state, target_arg_path, new_args);
return {
...new_state,
preview_size: state.preview_size,
};
},
}) as Record<string, StatefulPageAction<JDDPageState, any>>;
diff --git a/src/controllers/markdown-input.stimulus.ts b/src/controllers/markdown-input.stimulus.ts
index e2f7fc4..e73fceb 100644
--- a/src/controllers/markdown-input.stimulus.ts
+++ b/src/controllers/markdown-input.stimulus.ts
@@ -1,528 +1,523 @@
import { Controller } from "@hotwired/stimulus";
import MarkdownHighlighter from "./markdown-highlighter.js";
import * as prettier from "prettier";
import * as prettierPluginMarkdown from "prettier/plugins/markdown";
import TurndownService from "turndown";
import { gfm } from "@truto/turndown-plugin-gfm";
const turndown = new TurndownService({
headingStyle: "atx",
bulletListMarker: "-",
codeBlockStyle: "fenced",
fence: "```",
emDelimiter: "*",
strongDelimiter: "**",
linkStyle: "inlined",
});
turndown.use(gfm);
const duration = 300;
export default class extends Controller<HTMLElement> {
static targets = ["input", "editor", "toolbar", "ui", "fullscreen"];
declare readonly inputTarget: HTMLTextAreaElement;
declare readonly editorTarget: HTMLElement;
declare readonly toolbarTarget: HTMLElement;
declare readonly uiTarget: HTMLElement;
declare readonly fullscreenTarget: HTMLDivElement;
private highlighter?: MarkdownHighlighter;
private last_rect!: DOMRect;
private rect_placeholder: HTMLDivElement | null = null;
private backdrop: HTMLDivElement | null = null;
private minheightFrameID: ReturnType<
typeof window.requestAnimationFrame
> | null = null; // used to debounse updates of minheight inside the textarea
private resizeObserver!: ResizeObserver;
connect(): void {
if (!this.supported()) {
return;
}
this.activate();
this.inputTarget.addEventListener(
"selectionchange",
this.handleSelection
);
this.resizeObserver = new ResizeObserver(() => {
this.updateMinHeight();
});
this.resizeObserver.observe(this.inputTarget);
}
handleSelection = () => {
this.updateSelectionHighlight(
this.inputTarget.selectionStart,
this.inputTarget.selectionEnd
);
};
handleKeydown(event: KeyboardEvent) {
- console.log(event);
if (
(event.metaKey || event.ctrlKey) &&
event.key.toLowerCase() === "b"
) {
event.preventDefault();
this.bold();
return;
}
if (
(event.metaKey || event.ctrlKey) &&
event.key.toLowerCase() === "i"
) {
event.preventDefault();
this.italic();
return;
}
if (event.altKey && event.key.toLowerCase() === "f") {
event.preventDefault();
this.fullscreen();
return;
}
}
updateSelectionHighlight(start: number, end: number) {
this.highlighter?.setSelection(start, end);
this.render();
}
disconnect(): void {
this.highlighter?.disconnect();
this.inputTarget.removeEventListener(
"selectionchange",
this.handleSelection
);
this.resizeObserver.unobserve(this.inputTarget);
}
input(): void {
this.updateMinHeight();
this.syncInput();
this.render();
}
updateMinHeight() {
if (this.minheightFrameID) {
cancelAnimationFrame(this.minheightFrameID);
}
this.minheightFrameID = requestAnimationFrame(() => {
this.inputTarget.style.minHeight = "0px";
this.inputTarget.style.minHeight = `${this.inputTarget.scrollHeight + 4}px`;
});
}
selectionchange(): void {
// Useful if toolbar state is added later.
}
formdata(event: Event): void {
this.syncInput();
const formDataEvent = event as FormDataEvent;
formDataEvent.formData.set(
this.inputTarget.name,
this.inputTarget.value
);
}
bold(): void {
this.wrapSelection("**", "**");
}
italic(): void {
this.wrapSelection("*", "*");
}
code(): void {
this.wrapSelection("`", "`");
}
heading(): void {
this.transformLines((line) => {
if (/^ {0,3}#{1,6}\s/.test(line)) {
return line.replace(/^( {0,3})#{1,6}\s/, "$1");
}
return `# ${line}`;
});
}
quote(): void {
this.transformLines((line) => {
if (/^ {0,3}>\s?/.test(line)) {
return line.replace(/^( {0,3})>\s?/, "$1");
}
return `> ${line}`;
});
}
unorderedList(): void {
this.transformLines((line) => {
if (/^ {0,3}[-+*]\s/.test(line)) {
return line.replace(/^( {0,3})[-+*]\s/, "$1");
}
return `- ${line}`;
});
}
orderedList(): void {
let number = 1;
this.transformLines((line) => {
if (/^ {0,3}\d+[.)]\s/.test(line)) {
return line.replace(/^( {0,3})\d+[.)]\s/, "$1");
}
return `${number++}. ${line}`;
});
}
tab(event: KeyboardEvent): void {
if (event.key !== "Tab") {
return;
}
event.preventDefault();
this.insertText(" ");
}
private supported(): boolean {
return (
"highlights" in CSS &&
typeof Highlight !== "undefined" &&
typeof Range !== "undefined"
);
}
private activate(): void {
this.editorTarget.textContent = this.inputTarget.value;
this.highlighter = new MarkdownHighlighter(this.editorTarget);
this.render();
}
private syncInput(): void {
this.editorTarget.textContent = this.inputTarget.value;
}
private render(): void {
this.highlighter?.highlight(this.editorTarget.textContent ?? "");
}
private getSelection(): {
start: number;
end: number;
} | null {
return {
start: this.inputTarget.selectionStart,
end: this.inputTarget.selectionEnd,
};
}
private replaceRange(
start: number,
end: number,
replacement: string,
selectionStart = start + replacement.length,
selectionEnd = selectionStart
): void {
const input = this.inputTarget;
// execCommand acts on the currently focused editable element.
input.focus();
// Select the range we want to replace. This has to happen
// *after* focus, otherwise the browser may reset it.
input.setSelectionRange(start, end);
// This is the magic bit: goes through the native editing
// pipeline, so it lands on the textarea's undo stack and
// Ctrl+Z works. It replaces the current selection with
// `replacement` and fires a native `input` event.
const ok = document.execCommand("insertText", false, replacement);
// Fallback if execCommand is unavailable (rare, but be safe).
// Note: this branch is NOT undoable — that's the tradeoff.
if (!ok) {
const value = input.value ?? "";
input.value =
value.slice(0, start) + replacement + value.slice(end);
}
// Restore the desired selection. execCommand places the caret
// at the end of the inserted text, but the caller may want a
// different range (e.g. selecting the wrapped content).
input.setSelectionRange(selectionStart, selectionEnd);
// `insertText` fires a native `input` event, which should
// already trigger whatever `syncInput` does. If your
// `syncInput` is hooked to a framework that needs a manual
// nudge (e.g. you're shadowing the event), keep the call.
this.syncInput();
this.render();
input.focus();
}
private wrapSelection(before: string, after: string): void {
const selection = this.getSelection();
- console.log({ selection });
-
if (!selection) {
return;
}
const { start, end } = selection;
const value = this.inputTarget.value ?? "";
const selected = value.slice(start, end);
const alreadyWrappedInsideSelection =
selected.startsWith(before) && selected.endsWith(after);
if (alreadyWrappedInsideSelection) {
this.replaceRange(
start,
end,
selected.slice(before.length).slice(0, -1 * after.length)
);
return;
}
const wrappersOutsideSelection =
start >= before.length &&
end + after.length <= value.length &&
value.slice(start - before.length, start) === before &&
value.slice(end, end + after.length) === after;
if (wrappersOutsideSelection) {
this.replaceRange(
start - before.length,
end + after.length,
selected,
start - before.length,
start - before.length + selected.length
);
return;
}
const replacement = before + selected + after;
this.replaceRange(
start,
end,
replacement,
start + before.length,
start + before.length + selected.length
);
}
private insertText(text: string): void {
const selection = this.getSelection();
if (!selection) {
return;
}
this.replaceRange(
selection.start,
selection.end,
text,
selection.start + text.length
);
}
private transformLines(
transform: (line: string, index: number) => string
): void {
const selection = this.getSelection();
if (!selection) {
return;
}
const value = this.editorTarget.textContent ?? "";
const lineStart = value.lastIndexOf("\n", selection.start - 1) + 1;
const lineEndIndex = value.indexOf("\n", selection.end);
const lineEnd = lineEndIndex === -1 ? value.length : lineEndIndex;
const selectedBlock = value.slice(lineStart, lineEnd);
const lines = selectedBlock.split("\n");
const replacement = lines.map(transform).join("\n");
const delta = replacement.length - selectedBlock.length;
this.replaceRange(
lineStart,
lineEnd,
replacement,
selection.start + delta,
selection.end + delta
);
}
async handlePaste(event: ClipboardEvent) {
- console.log("PASTE!");
const clipboard = event.clipboardData;
if (!clipboard) return;
// Prefer HTML; fall back to letting the browser handle plain text.
const html = clipboard.getData("text/html");
if (!html) return;
event.preventDefault();
const markdown = turndown.turndown(this.cleanHtml(html));
const pretty = await prettier.format(markdown, {
parser: "markdown",
plugins: [prettierPluginMarkdown],
});
document.execCommand("insertText", false, pretty);
}
cleanHtml(html: string) {
const doc = new DOMParser().parseFromString(html, "text/html");
// Remove elements that never carry user-visible content.
doc.querySelectorAll(
"style, script, meta, link, title, head, base, noscript"
).forEach((el) => el.remove());
// Remove comments (often contain Office/Generator metadata).
const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_COMMENT);
const comments = [];
while (walker.nextNode())
comments.push(walker.currentNode as ChildNode);
comments.forEach((c) => c.remove());
return doc.body.innerHTML;
}
addRectPlaceholder() {
const div = document.createElement("div");
div.style.width = this.last_rect.width.toString() + "px";
div.style.height = this.last_rect.height.toString() + "px";
this.rect_placeholder = div;
this.element.appendChild(this.rect_placeholder);
}
removeRectPlaceholder() {
this.rect_placeholder?.remove();
this.rect_placeholder = null;
}
addBackdrop() {
const div = document.createElement("div");
div.style.width = "100vw";
div.style.height = "100vh";
div.style.position = "fixed";
div.style.top = "0px";
div.style.left = "0px";
div.style.zIndex = "666";
div.style.transition = `${duration}ms`;
div.style.backgroundColor = "#00000000";
div.addEventListener("click", () => this.fullscreen());
this.backdrop = div;
document.body.appendChild(this.backdrop);
void div.offsetWidth; // forces style flush + layout
window.requestAnimationFrame(() => {
div.style.backgroundColor = "rgba(0, 0, 0, 0.4)";
div.style.backdropFilter = "blur(5px)";
});
}
removeBackdrop() {
if (!this.backdrop) {
return;
}
this.backdrop.style.backgroundColor = "#00000000";
this.backdrop.style.backdropFilter = "";
window.setTimeout(() => {
this.backdrop?.remove();
this.backdrop = null;
}, duration);
}
fullscreen() {
const el = this.fullscreenTarget;
el.style.transition = `${duration}ms`;
if (!el.classList.contains("fullscreen--active")) {
this.last_rect = el.getBoundingClientRect();
this.inputTarget.setAttribute(
"data-autosubmit-on-keypress-disabled-value",
"true"
);
el.classList.add("fullscreen--active");
el.style.zIndex = "999";
el.style.maxWidth = `${Math.max(840 - 64, window.innerWidth)}px`;
el.style.position = "fixed";
this.addRectPlaceholder();
this.addBackdrop();
el.style.width = this.last_rect.width.toString() + "px";
el.style.height = this.last_rect.height.toString() + "px";
el.style.top = this.last_rect.y.toString() + "px";
el.style.left = this.last_rect.x.toString() + "px";
el.style.transitionTimingFunction =
"linear(0, 0.338 8.4%, 0.606 17.3%, 0.806 26.7%, 0.882 31.7%, 0.943 36.9%, 1.013 46.5%, 1.033 51.8%, 1.043 57.5%, 1.042 66.8%, 1.007 88.8%, 1)"; /* https://easingwizard.com/ - overshot, out, firm*/
void el.offsetWidth; // forces style flush + layout
window.requestAnimationFrame(() => {
el.style.width = "840px";
el.style.maxWidth = "calc(100vw - 64px)";
el.style.height = "calc(100vh - 64px)";
el.style.top = "32px";
el.style.left = "32px";
});
} else {
el.classList.remove("fullscreen--active");
this.inputTarget.setAttribute(
"data-autosubmit-on-keypress-disabled-value",
"false"
);
const current_rect = el.getBoundingClientRect();
el.style.maxWidth = `${Math.max(current_rect.width, this.last_rect.width)}px`;
- console.log(el.style.width);
void el.offsetWidth; // forces style flush + layout
window.requestAnimationFrame(() => {
el.style.width = this.last_rect.width.toString() + "px";
el.style.height = this.last_rect.height.toString() + "px";
el.style.top = this.last_rect.y.toString() + "px";
el.style.left = this.last_rect.x.toString() + "px";
this.removeBackdrop();
void el.offsetWidth; // forces style flush + layout
window.setTimeout(() => {
el.style.width = "unset";
el.style.height = "unset";
el.style.top = "unset";
el.style.left = "unset";
el.style.position = "unset";
el.classList.remove("fullscreen");
this.removeRectPlaceholder();
this.inputTarget.form?.requestSubmit();
}, duration);
});
}
}
}
diff --git a/src/controllers/refresh-on-ts-changes.stimulus.ts b/src/controllers/refresh-on-ts-changes.stimulus.ts
index b79fde8..6b3e057 100644
--- a/src/controllers/refresh-on-ts-changes.stimulus.ts
+++ b/src/controllers/refresh-on-ts-changes.stimulus.ts
@@ -1,112 +1,111 @@
import { Controller } from "stimulus";
const APP_DOWN_ERROR_MESSAGE = "App is currently down";
const sleep = (time: number) =>
new Promise((resolve) => {
setTimeout(resolve, time);
});
async function get_status(): Promise<{ started_at: number; status: string }> {
const r = await fetch("/status.json");
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return (await r.json()) as { started_at: number; status: string };
}
async function wait_for_run_id_to_change() {
let first_timestamp: number;
try {
const { started_at } = await get_status();
first_timestamp = started_at;
} catch (e) {
await wait_for_app_to_be_stable();
return;
}
if (!first_timestamp) {
throw new Error(APP_DOWN_ERROR_MESSAGE);
}
// eslint-disable-next-line no-constant-condition
while (true) {
// eslint-disable-next-line no-await-in-loop
const { started_at } = await get_status().catch(() => ({
started_at: first_timestamp,
}));
if (started_at !== first_timestamp) {
return;
}
// eslint-disable-next-line no-await-in-loop
await sleep(100);
}
}
async function wait_for_app_to_be_stable(n = 3) {
// eslint-disable-next-line no-console
console.log("Waiting for app to be stable....");
let counter = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
// eslint-disable-next-line no-await-in-loop
const { status } = await get_status().catch(() => ({
status: "down",
}));
if (status == "running") {
// eslint-disable-next-line no-console
- console.log(counter);
counter++;
} else {
counter = 0;
}
if (counter == n) {
return;
}
// eslint-disable-next-line no-await-in-loop
await sleep(100);
}
}
async function wait_for_app_restart() {
try {
await wait_for_run_id_to_change();
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if ((e as Error).message !== APP_DOWN_ERROR_MESSAGE) {
throw e;
}
}
await wait_for_app_to_be_stable();
}
export default class RefreshOnTSChanges extends Controller {
socket!: WebSocket;
async connect() {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const { port, watch } = (await fetch("/dist/notifier.json").then((r) =>
r.json()
)) as { port: number; watch: boolean };
if (!watch) {
// eslint-disable-next-line no-console
console.warn(
"Not running auto refresh on watch because the build process is not running in watch mode"
);
return;
}
const socket = new WebSocket(`ws://localhost:${port}`);
socket.onmessage = async (message) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const data = message.data as unknown;
if (typeof data === "string" && data.endsWith("-ts")) {
document.documentElement.classList.add("restarting");
await wait_for_app_restart();
document.documentElement.dispatchEvent(new Event("ts-rebuilt"));
document.documentElement.classList.remove("restarting");
}
};
}
async disconnect() {
this.socket.close();
}
}
diff --git a/src/inputs/component-input-file.ts b/src/inputs/component-input-file.ts
index f28fe41..0514a48 100644
--- a/src/inputs/component-input-file.ts
+++ b/src/inputs/component-input-file.ts
@@ -1,66 +1,64 @@
import type { Context } from "koa";
import { PathFilePointer, type FilePointer } from "@sealcode/file-manager";
import type { File, JDDContext } from "@sealcode/jdd";
import type { StatefulPage } from "@sealcode/sealgen";
import type { ComponentPreviewActions } from "../component-preview-actions.js";
import type { JDDPageState } from "../jdd-page.js";
import { tempstream } from "tempstream";
import { printArgPath } from "./print-arg-path.js";
import { htmlEscape } from "escape-goat";
export function ComponentInputFile<State extends JDDPageState>({
arg_path,
arg,
value,
ctx,
page,
state,
makeJDDContext,
}: {
state: State;
arg_path: string[];
arg: File;
value: FilePointer | null;
page: StatefulPage<JDDPageState, typeof ComponentPreviewActions>;
ctx: Context;
makeJDDContext: (ctx: Context) => JDDContext;
}): JSX.Element {
- const jdd_context = makeJDDContext(ctx);
- console.log({ value });
return tempstream /* HTML */ `<div
style="margin-bottom: 10px display: flex; align-items: center; column-gap: 10px; flex-flow: row;"
>
<label style="display: flex; flex-flow: row; column-gap: 10px;">
${arg_path.at(-1) || ""}
<span
>${value instanceof PathFilePointer
? value.original_filename
: ""}</span
>
<input
type="file"
name="${`$${printArgPath(arg_path)}.new`}"
value=""
autocomplete="off"
data-action="change->input-image-preview#handleChange"
${arg.hasParent("list") ? "multiple" : ""}
/>
</label>
<div>
<input
type="hidden"
name="${`$${printArgPath(arg_path)}.old`}"
value="${htmlEscape(value?.token || "")}"
autocomplete="off"
/>
</div>
${page.makeActionButton(
state,
{
action: "remove_file",
label: "❌",
},
arg_path
)}
</div>`;
}
diff --git a/src/inputs/component-input-markdown.ts b/src/inputs/component-input-markdown.ts
index 0e1c047..0334571 100644
--- a/src/inputs/component-input-markdown.ts
+++ b/src/inputs/component-input-markdown.ts
@@ -1,96 +1,95 @@
import { Component } from "@sealcode/jdd";
import { printArgPath } from "./print-arg-path.js";
export default function ComponentInputMarkdown({
arg_path,
value,
component,
}: {
arg_path: string[];
value: unknown;
component: Component;
}) {
- console.debug("component-input-markdown.ts:13", { value });
return /* HTML */ `<div
id="monaco__markdown__${arg_path.join("_")}__for__${component.name}"
data-controller="markdown-input"
class="markdown-editor"
>
${arg_path.at(-1) || ""}
<div class="fullscreen" data-markdown-input-target="fullscreen">
<div data-markdown-input-target="ui">
<div
data-markdown-input-target="toolbar"
role="toolbar"
class="toolbar"
>
<button
type="button"
data-action="markdown-input#bold"
style="font-weight: bold"
title="Bold (ctrl+B)"
>
B
</button>
<button
type="button"
data-action="markdown-input#italic"
style="Font-style: italic; font-family: var(--font-serif)"
title="Italic (ctrl+I)"
>
I
</button>
<button type="button" data-action="markdown-input#heading">
H1
</button>
<button type="button" data-action="markdown-input#quote">
„”
</button>
<button
type="button"
data-action="markdown-input#unorderedList"
>
• List
</button>
<button
type="button"
data-action="markdown-input#orderedList"
>
1. List
</button>
<button
type="button"
data-action="markdown-input#fullscreen"
title="Fullscreen (alt+F)"
>
⛶
</button>
</div>
</div>
<div class="textarea-wrapper">
<textarea
name="${`$${printArgPath(arg_path)}`}"
data-controller="autosubmit-on-keypress"
data-markdown-input-target="input"
data-action="keydown->markdown-input#handleKeydown
input->markdown-input#input
paste->markdown-input#handlePaste"
style="field-sizing: content"
>
${value?.toString() || ""}</textarea
>
${`<div
class="syntax-overlay"
data-markdown-input-target="editor"
style="pointer-events: none"
>${value?.toString() || ""}</div>`}
</div>
</div>
</div>`;
}
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Sat, Nov 28, 02:05 (6 h, 56 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1225348
Default Alt Text
(36 KB)
Attached To
Mode
rJDDE jdd-editor
Attached
Detach File
Event Timeline