alinea
Version:
[](https://npmjs.org/package/alinea) [](https://packagephobia.com/result?p=alinea)
89 lines (85 loc) • 2.87 kB
JavaScript
import "../../chunks/chunk-U5RRZUYZ.js";
// src/input/json/JsonField.browser.tsx
import { Field } from "alinea/core";
import { useField } from "alinea/dashboard/editor/UseField";
import { InputLabel } from "alinea/dashboard/view/InputLabel";
import { HStack, fromModule } from "alinea/ui";
import { IcRoundTextFields } from "alinea/ui/icons/IcRoundTextFields";
import { TextareaAutosize } from "alinea/ui/util/TextareaAutosize";
import { useEffect, useState } from "react";
import { json as createJson } from "./JsonField.js";
// src/input/json/JsonInput.module.scss
var JsonInput_module_default = {
"root-input": "alinea-JsonInput-input",
"rootInput": "alinea-JsonInput-input",
"is-valid": "alinea-JsonInput-is-valid",
"isValid": "alinea-JsonInput-is-valid"
};
// src/input/json/JsonField.browser.tsx
export * from "./JsonField.js";
import { jsx } from "react/jsx-runtime";
var json = Field.provideView(JsonInput, createJson);
var styles = fromModule(JsonInput_module_default);
function JsonInput({ field }) {
const { options, value, mutator, label } = useField(field);
const [text, setText] = useState(JSON.stringify(value, null, 2));
const [valid, setValid] = useState(true);
const [focus, setFocus] = useState(false);
const { inline, autoFocus } = options;
const placeholder = inline ? String(label) : "";
const empty = value === "";
useEffect(() => {
try {
const newValue = JSON.parse(text);
mutator(newValue);
setValid(true);
} catch (e) {
setValid(text ? false : true);
}
}, [text]);
return /* @__PURE__ */ jsx(
InputLabel,
{
asLabel: true,
...options,
focused: focus,
icon: IcRoundTextFields,
empty,
children: /* @__PURE__ */ jsx(HStack, { center: true, gap: 8, children: /* @__PURE__ */ jsx(
TextareaAutosize,
{
className: styles.root.input({ valid }),
type: "text",
value: text || "",
onChange: (e) => setText(e.currentTarget.value),
onFocus: () => setFocus(true),
onKeyDown: (e) => {
if (e.key == "Tab") {
const target = e.target;
var start = target.selectionStart;
var end = target.selectionEnd;
const value2 = target.value;
if (end !== value2.length) {
e.preventDefault();
target.value = value2.substring(0, start) + " " + value2.substring(end);
target.selectionStart = target.selectionEnd = start + 2;
}
}
},
onBlur: () => {
setFocus(false);
if (valid) {
setText(JSON.stringify(value, null, 2));
}
},
placeholder,
autoFocus,
disabled: options.readOnly
}
) })
}
);
}
export {
json
};