ui-dev-content/dist/hooks/useEditableContent.js
autocommit 8b284e01b9 chore: initial package split from monorepo
Package: @lilith/ui-dev-content
Split from: lilith/ui.git or lilith/build.git
Publish workflow: calls lilith/workflows/.forgejo/workflows/publish-npm.yml@main
2026-04-20 01:11:45 -07:00

62 lines
2 KiB
JavaScript

/**
* useEditableContent - Hook for programmatic content registration
*
* Use this hook when you need more control than the EditableContent wrapper.
*/
import { useEffect, useRef } from 'react';
import { useContentRegistry } from '../core/ContentEditingContext';
/**
* Register an element as editable content
*
* Returns a ref that should be attached to the element.
*
* @example
* ```tsx
* function Hero() {
* const ref = useEditableContent({
* source: 'locale',
* identifier: 'home.hero.title',
* transformers: ['truth-validation', 'seo-optimize']
* });
*
* return <h1 ref={ref}>{t('hero.title')}</h1>;
* }
* ```
*/
export function useEditableContent({ source, identifier, type = 'text', transformers, devOnly = true, }) {
const ref = useRef(null);
const registry = useContentRegistry();
useEffect(() => {
// Skip if dev-only and not in dev mode, or if no provider available
if (devOnly && !import.meta.env.DEV) {
return;
}
if (!ref.current || !registry) {
return;
}
// Add data attributes
ref.current.dataset.editable = 'true';
ref.current.dataset.contentSource = source;
ref.current.dataset.contentId = identifier;
ref.current.dataset.contentType = type;
if (transformers) {
ref.current.dataset.allowedTransformers = transformers.join(',');
}
// Trigger re-scan
const rescan = async () => {
await registry.detectContent();
};
rescan();
return () => {
// Cleanup
if (ref.current) {
delete ref.current.dataset.editable;
delete ref.current.dataset.contentSource;
delete ref.current.dataset.contentId;
delete ref.current.dataset.contentType;
delete ref.current.dataset.allowedTransformers;
}
};
}, [source, identifier, type, transformers, devOnly, registry]);
return ref;
}