How to use the preact/hooks.useRef function in preact

To help you get started, we’ve selected a few preact examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github preactjs / preact-devtools / src / view / components / TreeView.tsx View on Github external
const onKeyDown = useKeyListNav({
		selected,
		onCollapse: collapseNode,
		canCollapse: id => {
			const node = store.nodes.$.get(id);
			return node ? node.children.length > 0 : false;
		},
		checkCollapsed: id => collapsed.has(id),
		onNext: selectNext,
		onPrev: selectPrev,
	});

	const onMouseLeave = useCallback(() => store.actions.highlightNode(null), []);
	const ref = useRef(null);
	const paneRef = useRef(null);

	useEffect(() => {
		if (ref.current && paneRef.current) {
			const available = ref.current.offsetWidth;
			const actual = paneRef.current.offsetWidth;
			const diff = actual - available;
			if (diff > 0) {
				const current = cssToPx(
					getComputedStyle(ref.current).getPropertyValue("--indent-depth"),
				);

				const indent =
					current - Math.round((diff / (treeDepth || 1)) * 100) / 100;

				// Only change indentation when it's smaller
				console.log({ indent, current });
github hypothesis / client / src / sidebar / components / annotation-share-control.js View on Github external
function AnnotationShareControl({
  analytics,
  flash,
  group,
  isPrivate,
  shareUri,
}) {
  const shareRef = useRef();
  const inputRef = useRef();

  const [isOpen, setOpen] = useState(false);
  const wasOpen = useRef(isOpen);

  const toggleSharePanel = () => setOpen(!isOpen);
  const closePanel = () => setOpen(false);

  // Interactions outside of the component when it is open should close it
  useElementShouldClose(shareRef, isOpen, closePanel);

  useEffect(() => {
    if (wasOpen.current !== isOpen) {
      wasOpen.current = isOpen;
      if (isOpen) {
        // Panel was just opened: select and focus the share URI for convenience
        inputRef.current.focus();
github hypothesis / client / src / sidebar / components / annotation-share-control.js View on Github external
function AnnotationShareControl({
  analytics,
  flash,
  group,
  isPrivate,
  shareUri,
}) {
  const shareRef = useRef();
  const inputRef = useRef();

  const [isOpen, setOpen] = useState(false);
  const wasOpen = useRef(isOpen);

  const toggleSharePanel = () => setOpen(!isOpen);
  const closePanel = () => setOpen(false);

  // Interactions outside of the component when it is open should close it
  useElementShouldClose(shareRef, isOpen, closePanel);

  useEffect(() => {
    if (wasOpen.current !== isOpen) {
      wasOpen.current = isOpen;
      if (isOpen) {
        // Panel was just opened: select and focus the share URI for convenience
github hypothesis / client / src / sidebar / store / use-store.js View on Github external
function useStore(callback) {
  const store = useService('store');

  // Store the last-used callback in a ref so we can access it in the effect
  // below without having to re-subscribe to the store when it changes.
  const lastCallback = useRef(null);
  lastCallback.current = callback;

  const lastResult = useRef(null);
  lastResult.current = callback(store);

  // Check for a performance issue caused by `callback` returning a different
  // result on every call, even if the store has not changed.
  if (process.env.NODE_ENV !== 'production') {
    if (!shallowEqual(lastResult.current, callback(store))) {
      warnOnce(
        'The output of a callback passed to `useStore` changes every time. ' +
          'This will lead to a component updating more often than necessary.'
      );
    }
  }

  // Abuse `useReducer` to force updates when the store state changes.
  const [, forceUpdate] = useReducer(x => x + 1, 0);
github GoogleChrome / lighthouse-ci / packages / server / src / ui / routes / build-view / audit-detail / audit-detail-pane.jsx View on Github external
export const AuditDetailPane = props => {
  /** @type {import('preact').Ref} */
  const paneElementRef = useRef(undefined);
  const previouslySelectedAuditId = usePreviousValue(props.selectedAuditId);

  // Scroll to the selected audit *when it changes*
  useEffect(() => {
    const auditId = props.selectedAuditId;
    const paneElement = paneElementRef.current;
    if (!paneElement || !auditId || auditId === previouslySelectedAuditId) return;

    const childElement = paneElement.querySelector(`#audit-detail-pane-audit--${auditId}`);
    if (!childElement || !(childElement instanceof HTMLElement)) return;

    paneElement.scrollTo(0, childElement.offsetTop);
  }, [props.selectedAuditId, previouslySelectedAuditId]);

  return (
    <div> (paneElementRef.current = el)}&gt;</div>
github preactjs / preact-www / src / components / code-block / index.js View on Github external
const value = initializer();
			if (value && value.then) {
				if ('_value' in value) return [value._value];
				if ('_error' in value) return [undefined, value._error];
				return [undefined, undefined, value];
			}
			return [value];
		} catch (err) {
			return [undefined, err];
		}
	};

	const [pair, setValue] = useState(getInitialState);

	// only run on changes, not initial mount
	const isFirstRun = useRef(true);
	useEffect(() => {
		if (isFirstRun.current) return (isFirstRun.current = false);
		setValue(getInitialState());
	}, params || []);

	const pending = pair[2];
	if (pending) {
		if (!pending._processing) {
			pending._processing = true;
			pending
				.then(value => {
					pending._value = value;
					setValue([value]);
				})
				.catch(err => {
					pending._error = err;
github hypothesis / client / src / sidebar / components / menu.js View on Github external
function Menu({
  align = 'left',
  arrowClass = '',
  children,
  containerPositioned = true,
  contentClass,
  defaultOpen = false,
  label,
  onOpenChanged,
  menuIndicator = true,
  title,
}) {
  const [isOpen, setOpen] = useState(defaultOpen);

  // Notify parent when menu is opened or closed.
  const wasOpen = useRef(isOpen);
  useEffect(() => {
    if (typeof onOpenChanged === 'function' && wasOpen.current !== isOpen) {
      wasOpen.current = isOpen;
      onOpenChanged(isOpen);
    }
  }, [isOpen, onOpenChanged]);

  // Toggle menu when user presses toggle button. The menu is shown on mouse
  // press for a more responsive/native feel but also handles a click event for
  // activation via other input methods.
  const toggleMenu = event => {
    // If the menu was opened on press, don't close it again on the subsequent
    // mouse up ("click") event.
    if (event.type === 'mousedown') {
      ignoreNextClick = true;
    } else if (event.type === 'click' && ignoreNextClick) {
github hypothesis / client / src / sidebar / components / search-input.js View on Github external
function SearchInput({ alwaysExpanded, query, onSearch }) {
  const isLoading = useStore(store => store.isLoading());
  const input = useRef();

  // The active filter query from the previous render.
  const [prevQuery, setPrevQuery] = useState(query);

  // The query that the user is currently typing, but may not yet have applied.
  const [pendingQuery, setPendingQuery] = useState(query);

  const onSubmit = e => {
    e.preventDefault();
    onSearch(input.current.value);
  };

  // When the active query changes outside of this component, update the input
  // field to match. This happens when clearing the current filter for example.
  if (query !== prevQuery) {
    setPendingQuery(query);
github preactjs / preact-devtools / src / view / components / TreeView.tsx View on Github external
export function TreeItem(props: { key: any; id: ID }) {
	const { id } = props;
	const store = useStore();
	const sel = useSelection();
	const { collapsed, toggle } = useCollapser();
	const filterFragments = useObserver(() =&gt; store.filter.filterFragment.$);
	const node = useObserver(() =&gt; store.nodes.$.get(id) || null);
	const onToggle = () =&gt; toggle(id);
	const ref = useRef();

	let isSelected = sel.selected === id;
	useEffect(() =&gt; {
		if (ref.current &amp;&amp; isSelected) {
			scrollIntoView(ref.current);
		}
	}, [ref.current, sel.selected, id]);

	if (!node) return null;

	return (
		<div class="{s.item}"> sel.selectById(id)}
			onMouseEnter={() =&gt; store.actions.highlightNode(id)}</div>
github Houdou / arkgraph / src / routes / table / components / UpgradeInputRow.js View on Github external
record: {
			operator,
			attribute,
			current,
			target,
			hidden,
			requirements,
		},
		setOperator,
		setAttribute,
		setCurrent,
		setTarget,
		setHidden,
	} = useRecord(init_record);

	const operatorInputRef = useRef(null);

	useEffect(() =&gt; {
		if (!operator) {
			operatorInputRef.current &amp;&amp; operatorInputRef.current.focus();
		}
	}, []);

	const options = Object.entries(ATTRIBUTES).map(([k, v]) =&gt; ({ key: k, value: v }));
	const operator_data = OPERATORS.find(o =&gt; o.name === operator);
	const unavailable_attributes = [];
	const render_map = {};

	if (operator_data) {
		if (operator_data.meta.max_elite_rank &lt; 2) {
			unavailable_attributes.push(ATTRIBUTES.LEVEL_ELITE_2);
		}