Add internal mix tag input for calculator and goal tree formulas
All checks were successful
Deploy Sokko G / deploy (push) Successful in 15s

This commit is contained in:
Shinuwa 2026-08-24 13:24:44 +02:00
parent 5c8148c905
commit ae503c7260
13 changed files with 929 additions and 23 deletions

View file

@ -0,0 +1,397 @@
// Rôle : fournit un champ contentEditable mixte inspiré du mode mix Tagify.
// Affiche des tags atomiques dans le texte tout en exposant une valeur string brute.
import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { buildInsertedMixTagValue, normalizeMixTagDefinitions, normalizeMixTagText, removeMixTagAtOffset, tokenizeMixTagValue } from "../utils/mixTagsInputUtils.js";
const ZERO_WIDTH_SPACE = "\u200B";
const WORD_CHAR_PATTERN = /[\p{L}\p{N}_]/u;
function assignRef(ref, node) {
if (!ref) return;
if (typeof ref === "function") ref(node);
else ref.current = node;
}
function createInputLikeEvent(value, element = null) {
return {
target: { value },
currentTarget: { value, textContent: value, isContentEditable: true, blur: () => element?.blur?.() }
};
}
function cleanTextValue(value) {
return String(value || "").replaceAll(ZERO_WIDTH_SPACE, "");
}
function getTokenElement(node, root) {
let current = node?.nodeType === Node.ELEMENT_NODE ? node : node?.parentElement;
while (current && current !== root) {
if (current.dataset?.mixTagValue != null) return current;
current = current.parentElement;
}
return null;
}
function readNodeValue(node) {
if (!node) return "";
if (node.nodeType === Node.TEXT_NODE) return cleanTextValue(node.nodeValue);
if (node.nodeType !== Node.ELEMENT_NODE) return "";
if (node.dataset?.mixTagValue != null) return node.dataset.mixTagValue;
return Array.from(node.childNodes).map(readNodeValue).join("");
}
function valueNeedsSeparator(left, right) {
if (!left || !right) return false;
return WORD_CHAR_PATTERN.test(left[left.length - 1]) && WORD_CHAR_PATTERN.test(right[0]);
}
function readEditorValue(editor) {
let value = "";
Array.from(editor?.childNodes || []).forEach((node) => {
const nextValue = readNodeValue(node);
if (!nextValue) return;
value += `${valueNeedsSeparator(value, nextValue) ? " " : ""}${nextValue}`;
});
return value;
}
function getNodeRawLength(node) {
return readNodeValue(node).length;
}
function getOffsetFromPoint(root, targetNode, targetOffset) {
const tokenElement = getTokenElement(targetNode, root);
let offset = 0;
let found = false;
function visit(node) {
if (found) return;
if (node === targetNode) {
if (node.nodeType === Node.TEXT_NODE) {
offset += cleanTextValue((node.nodeValue || "").slice(0, targetOffset)).length;
} else {
Array.from(node.childNodes).slice(0, targetOffset).forEach((child) => {
offset += getNodeRawLength(child);
});
}
found = true;
return;
}
if (node === tokenElement) {
const tokenLength = node.dataset.mixTagValue.length;
const tokenTextLength = node.textContent?.length || 1;
const visualOffset = targetNode === node ? targetOffset : Math.min(targetOffset, tokenTextLength);
offset += visualOffset < tokenTextLength / 2 ? 0 : tokenLength;
found = true;
return;
}
if (node.nodeType === Node.TEXT_NODE || node.dataset?.mixTagValue != null) {
offset += getNodeRawLength(node);
return;
}
Array.from(node.childNodes || []).forEach(visit);
}
visit(root);
return offset;
}
function getSelectionOffsets(root) {
const selection = window.getSelection();
if (!selection?.rangeCount) return { start: 0, end: 0 };
const range = selection.getRangeAt(0);
if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) {
const length = readEditorValue(root).length;
return { start: length, end: length };
}
const start = getOffsetFromPoint(root, range.startContainer, range.startOffset);
const end = getOffsetFromPoint(root, range.endContainer, range.endOffset);
return { start: Math.min(start, end), end: Math.max(start, end) };
}
function findPointFromOffset(root, requestedOffset) {
let remaining = Math.max(0, requestedOffset);
let fallback = { node: root, offset: root.childNodes.length };
function visit(node) {
if (node.nodeType === Node.TEXT_NODE) {
const raw = cleanTextValue(node.nodeValue);
if (remaining <= raw.length) {
let domOffset = 0;
let rawOffset = 0;
const text = node.nodeValue || "";
while (domOffset < text.length && rawOffset < remaining) {
if (text[domOffset] !== ZERO_WIDTH_SPACE) rawOffset += 1;
domOffset += 1;
}
return { node, offset: domOffset };
}
remaining -= raw.length;
return null;
}
if (node.nodeType === Node.ELEMENT_NODE && node.dataset?.mixTagValue != null) {
const length = node.dataset.mixTagValue.length;
const parent = node.parentNode || root;
const index = Array.from(parent.childNodes).indexOf(node);
if (remaining <= length) return { node: parent, offset: remaining <= length / 2 ? index : index + 1 };
remaining -= length;
fallback = { node: parent, offset: index + 1 };
return null;
}
const children = Array.from(node.childNodes || []);
for (const child of children) {
const point = visit(child);
if (point) return point;
}
fallback = { node, offset: children.length };
return null;
}
return visit(root) || fallback;
}
function setCaretOffset(root, offset) {
const selection = window.getSelection();
if (!selection) return;
const point = findPointFromOffset(root, offset);
const range = document.createRange();
range.setStart(point.node, point.offset);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
function getRawSelectionText(root) {
const selection = window.getSelection();
if (!selection?.rangeCount) return "";
const range = selection.getRangeAt(0);
if (!root.contains(range.commonAncestorContainer)) return "";
const fragment = range.cloneContents();
return Array.from(fragment.childNodes).map(readNodeValue).join("");
}
export function MixTagsInput({
value = "",
onChange,
onBlur,
onFocus,
onKeyDown,
tokens = [],
placeholder = "",
disabled = false,
className = "",
wrapperClassName = "",
size = "default",
id,
title = "",
"aria-label": ariaLabel,
"aria-describedby": ariaDescribedBy,
inputRef,
inputMode,
spellCheck = "false",
insertToken = null,
formulaSpacing = false
}) {
const editorRef = useRef(null);
const valueRef = useRef(String(value ?? ""));
const pendingCaretRef = useRef(null);
const latestRef = useRef({});
const composingRef = useRef(false);
const [isFocused, setIsFocused] = useState(false);
const tokenDefinitions = useMemo(() => normalizeMixTagDefinitions(tokens), [tokens]);
const normalizedValue = normalizeMixTagText(String(value ?? ""), tokenDefinitions);
const segments = useMemo(() => tokenizeMixTagValue(normalizedValue, tokenDefinitions), [normalizedValue, tokenDefinitions]);
useEffect(() => {
latestRef.current = { onChange, onBlur, onFocus, onKeyDown, tokenDefinitions };
});
useEffect(() => {
valueRef.current = normalizedValue;
}, [normalizedValue]);
useLayoutEffect(() => {
const editor = editorRef.current;
if (!editor || pendingCaretRef.current == null) return;
editor.focus();
setCaretOffset(editor, pendingCaretRef.current);
pendingCaretRef.current = null;
}, [normalizedValue]);
const emitValue = useCallback((nextValue, nextCursor = null) => {
const latest = latestRef.current;
const nextNormalizedValue = normalizeMixTagText(nextValue, latest.tokenDefinitions);
valueRef.current = nextNormalizedValue;
pendingCaretRef.current = nextCursor;
latest.onChange?.(nextNormalizedValue);
}, []);
function removeTokenFromSelection(event, direction) {
const editor = editorRef.current;
if (!editor) return false;
const { start, end } = getSelectionOffsets(editor);
const next = removeMixTagAtOffset(valueRef.current, start, end, tokenDefinitions, direction);
if (!next) return false;
event.preventDefault();
emitValue(next.value, next.cursor);
return true;
}
function snapSelectionToTokenBoundary() {
const editor = editorRef.current;
if (!editor) return;
const selection = window.getSelection();
if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return;
const token = getTokenElement(selection.anchorNode, editor);
if (!token) return;
const { start } = getSelectionOffsets(editor);
setCaretOffset(editor, start);
}
function handleInput() {
const editor = editorRef.current;
if (!editor) return;
const { start } = getSelectionOffsets(editor);
if (composingRef.current) {
valueRef.current = readEditorValue(editor);
pendingCaretRef.current = start;
return;
}
emitValue(readEditorValue(editor), start);
}
function handleKeyDown(event) {
latestRef.current.onKeyDown?.(event);
if (event.defaultPrevented || (event.key !== "Backspace" && event.key !== "Delete")) return;
removeTokenFromSelection(event, event.key === "Backspace" ? "backward" : "forward");
}
function handleBeforeInput(event) {
if (event.defaultPrevented) return;
if (event.nativeEvent.inputType === "deleteContentBackward") removeTokenFromSelection(event, "backward");
if (event.nativeEvent.inputType === "deleteContentForward") removeTokenFromSelection(event, "forward");
}
function handleCompositionStart() {
composingRef.current = true;
}
function handleCompositionEnd() {
composingRef.current = false;
const editor = editorRef.current;
if (!editor) return;
const { start } = getSelectionOffsets(editor);
emitValue(readEditorValue(editor), start);
}
function handleCopy(event) {
const editor = editorRef.current;
const selectedText = editor ? getRawSelectionText(editor) : "";
if (!selectedText) return;
event.preventDefault();
event.clipboardData.setData("text/plain", selectedText);
}
function handlePaste(event) {
const editor = editorRef.current;
if (!editor) return;
event.preventDefault();
const { start, end } = getSelectionOffsets(editor);
const pastedText = event.clipboardData.getData("text/plain");
const nextValue = `${valueRef.current.slice(0, start)}${pastedText}${valueRef.current.slice(end)}`;
emitValue(nextValue, start + pastedText.length);
}
function handleFocus() {
setIsFocused(true);
latestRef.current.onFocus?.(createInputLikeEvent(valueRef.current, editorRef.current));
}
function handleBlur() {
setIsFocused(false);
latestRef.current.onBlur?.(createInputLikeEvent(valueRef.current, editorRef.current));
}
function handleInsertToken() {
const editor = editorRef.current;
const tokenValue = insertToken?.value || tokenDefinitions[0]?.value;
if (!editor || !tokenValue) return;
editor.focus();
const { start, end } = getSelectionOffsets(editor);
const next = buildInsertedMixTagValue(valueRef.current, start, end, tokenValue, { formulaSpacing });
emitValue(next.value, next.cursor);
}
const rootClassName = [
"mix-tags-input-wrap",
size === "small" ? "mix-tags-input-wrap--small" : "",
wrapperClassName
].filter(Boolean).join(" ");
return (
<span className={rootClassName}>
<span
aria-disabled={disabled || undefined}
aria-describedby={ariaDescribedBy}
aria-label={ariaLabel}
aria-multiline="true"
className={`mix-tags-input ${className} ${isFocused ? "is-focused" : ""}`.trim()}
contentEditable={!disabled}
data-placeholder={placeholder}
data-value={normalizedValue}
id={id}
key={normalizedValue}
inputMode={inputMode}
onBeforeInput={handleBeforeInput}
onBlur={handleBlur}
onCompositionEnd={handleCompositionEnd}
onCompositionStart={handleCompositionStart}
onCopy={handleCopy}
onFocus={handleFocus}
onInput={handleInput}
onKeyDown={handleKeyDown}
onKeyUp={snapSelectionToTokenBoundary}
onMouseUp={snapSelectionToTokenBoundary}
onPaste={handlePaste}
ref={(node) => {
editorRef.current = node;
assignRef(inputRef, node);
}}
role="textbox"
spellCheck={spellCheck}
suppressContentEditableWarning
tabIndex={disabled ? -1 : 0}
title={title}
>
{segments.length ? segments.map((segment) => (
segment.type === "text"
? <Fragment key={`${segment.start}:${segment.end}:text`}>{segment.text}</Fragment>
: (
<Fragment key={`${segment.start}:${segment.end}:${segment.token.value}`}>
{ZERO_WIDTH_SPACE}
<span className="mix-tags-input-tag" contentEditable={false} data-mix-tag-value={segment.token.value} tabIndex={-1} title={segment.token.title || segment.token.value}>
<span className="mix-tags-input-tag-text">{segment.token.label || segment.token.value}</span>
</span>
{ZERO_WIDTH_SPACE}
</Fragment>
)
)) : null}
</span>
{insertToken && (
<button
className="mix-tags-input-insert-button"
type="button"
onMouseDown={(event) => event.preventDefault()}
onClick={handleInsertToken}
aria-label={insertToken.title || insertToken.label || insertToken.value}
title={insertToken.title || insertToken.label || insertToken.value}
disabled={disabled}
>
{insertToken.icon ? <span className={`ui-icon ui-icon-${insertToken.icon}`} aria-hidden="true" /> : <span>{insertToken.label || insertToken.value}</span>}
</button>
)}
</span>
);
}