Skip to content

Commit

Permalink
feat: scroll context (#1108)
Browse files Browse the repository at this point in the history
Every scrollable components - `ScrollView`, `FlatList`, `SectionList`
and `KeyboardAwareScrollView` - now optionally report their scroll
position to a shared context. This scroll context can then be used by
custom elements.

This PR adds to the demo app a new `scroll-opacity` element that syncs
its opacity with the position of the scroll view. A practical example is
added to make the title of a page fade in/out as it leaves/comes back
into view.

Implementation details: see commits breakdown.



https://github.com/user-attachments/assets/f84ad40d-0b07-4b2a-a871-c9f4a9638eb6

---------

Co-authored-by: flochtililoch <flochtililoch@gmail.com>
  • Loading branch information
flochtililoch and flochtililoch authored Mar 4, 2025
1 parent 9b50ce0 commit e65f2b6
Show file tree
Hide file tree
Showing 21 changed files with 344 additions and 15 deletions.
6 changes: 4 additions & 2 deletions demo/backend/_includes/templates/base.xml.njk
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
{% endblock %}
</styles>
<body style="body" safe-area="true">
{% include 'templates/header.xml.njk' %}
{% block container %}{% endblock %}
{% block body %}
{% include 'templates/header.xml.njk' %}
{% block container %}{% endblock %}
{% endblock %}
</body>
</screen>
{% block custom_screen %}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<style
id="text"
marginHorizontal="24"
marginBottom="16"
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
permalink: "/backend/advanced/community/scroll-opacity.xml"
tags: "Advanced/Community/Elements"
hv_title: "Scroll Opacity"
---

{% extends 'templates/base.xml.njk' %}

{% block styles %}
{% include './_styles.xml.njk' %}
{% endblock %}

{% block body %}
<header style="header">
<view action="back" href="#" style="header-btn">
{% include 'icons/back.svg' %}
</view>
<scroll-opacity:scroll-opacity
xmlns:scroll-opacity="https://hyperview.org/scroll-opacity"
scroll-opacity:context-key="scroll-view"
scroll-opacity:distance="20"
scroll-opacity:initial-opacity="0"
>
<text style="header-title" key="title">{{ hv_title }}</text>
</scroll-opacity:scroll-opacity>
</header>
<view
style="main"
xmlns:scroll="https://hyperview.org/hyperview-scroll"
scroll="true"
scroll:context-key="scroll-view"
scroll:event-throttle="24"
>
<text style="header-title text">{{ hv_title }}</text>
<text style="text">
Velit voluptas et alias atque provident sapiente consequuntur deserunt. Dolorem et
non error dolorem voluptate amet accusantium. Corporis rerum sed labore quae sed qui quis quasi. Illo pariatur sint qui.
Quasi quaerat id molestias. Necessitatibus et ipsa quia asperiores laborum neque. Quisquam dolorem consequatur illum. Ut
magni iusto explicabo blanditiis quasi laborum incidunt earum. Eius ut in rerum ipsam. Officiis dolores suscipit
consequatur placeat commodi eum. Vel possimus placeat aut eos tempore saepe. Esse assumenda eum illo sed aut earum quia
voluptatibus. Recusandae qui iusto corporis sed atque. Veniam et possimus praesentium. Cum molestiae non velit minus
voluptatibus quos illo sed. Et omnis ut soluta qui inventore molestias. Dolores voluptatem perspiciatis exercitationem
consectetur minus illum. Quos quaerat omnis aut eius eos dolores velit. Et quia vel ea unde eum repudiandae. Repellat et
ab sed.
</text>
<text style="text">
Velit voluptas et alias atque provident sapiente consequuntur deserunt. Dolorem et
non error dolorem voluptate amet accusantium. Corporis rerum sed labore quae sed qui quis quasi. Illo pariatur sint qui.
Quasi quaerat id molestias. Necessitatibus et ipsa quia asperiores laborum neque. Quisquam dolorem consequatur illum. Ut
magni iusto explicabo blanditiis quasi laborum incidunt earum. Eius ut in rerum ipsam. Officiis dolores suscipit
consequatur placeat commodi eum. Vel possimus placeat aut eos tempore saepe. Esse assumenda eum illo sed aut earum quia
voluptatibus. Recusandae qui iusto corporis sed atque. Veniam et possimus praesentium. Cum molestiae non velit minus
voluptatibus quos illo sed. Et omnis ut soluta qui inventore molestias. Dolores voluptatem perspiciatis exercitationem
consectetur minus illum. Quos quaerat omnis aut eius eos dolores velit. Et quia vel ea unde eum repudiandae. Repellat et
ab sed.
</text>
<text style="text">
Velit voluptas et alias atque provident sapiente consequuntur deserunt. Dolorem et
non error dolorem voluptate amet accusantium. Corporis rerum sed labore quae sed qui quis quasi. Illo pariatur sint qui.
Quasi quaerat id molestias. Necessitatibus et ipsa quia asperiores laborum neque. Quisquam dolorem consequatur illum. Ut
magni iusto explicabo blanditiis quasi laborum incidunt earum. Eius ut in rerum ipsam. Officiis dolores suscipit
consequatur placeat commodi eum. Vel possimus placeat aut eos tempore saepe. Esse assumenda eum illo sed aut earum quia
voluptatibus. Recusandae qui iusto corporis sed atque. Veniam et possimus praesentium. Cum molestiae non velit minus
voluptatibus quos illo sed. Et omnis ut soluta qui inventore molestias. Dolores voluptatem perspiciatis exercitationem
consectetur minus illum. Quos quaerat omnis aut eius eos dolores velit. Et quia vel ea unde eum repudiandae. Repellat et
ab sed.
</text>
<text style="text">
Velit voluptas et alias atque provident sapiente consequuntur deserunt. Dolorem et
non error dolorem voluptate amet accusantium. Corporis rerum sed labore quae sed qui quis quasi. Illo pariatur sint qui.
Quasi quaerat id molestias. Necessitatibus et ipsa quia asperiores laborum neque. Quisquam dolorem consequatur illum. Ut
magni iusto explicabo blanditiis quasi laborum incidunt earum. Eius ut in rerum ipsam. Officiis dolores suscipit
consequatur placeat commodi eum. Vel possimus placeat aut eos tempore saepe. Esse assumenda eum illo sed aut earum quia
voluptatibus. Recusandae qui iusto corporis sed atque. Veniam et possimus praesentium. Cum molestiae non velit minus
voluptatibus quos illo sed. Et omnis ut soluta qui inventore molestias. Dolores voluptatem perspiciatis exercitationem
consectetur minus illum. Quos quaerat omnis aut eius eos dolores velit. Et quia vel ea unde eum repudiandae. Repellat et
ab sed.
</text>
</view>
{% endblock %}
9 changes: 9 additions & 0 deletions demo/schema/hyperview.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,17 @@
xmlns:hv="https://hyperview.org/hyperview"
xmlns:alert="https://hyperview.org/hyperview-alert"
xmlns:filter="https://hyperview.org/filter"
xmlns:scroll="https://hyperview.org/hyperview-scroll"
xmlns:share="https://hyperview.org/share"
>
<xs:import
namespace="https://hyperview.org/hyperview-alert"
schemaLocation="../../schema/alert.xsd"
/>
<xs:import
namespace="https://hyperview.org/hyperview-scroll"
schemaLocation="../../schema/scroll.xsd"
/>
<xs:import
namespace="https://hyperview.org/bottom-sheet"
schemaLocation="bottom-sheet.xsd"
Expand All @@ -32,6 +37,10 @@
namespace="https://hyperview.org/progress-bar"
schemaLocation="progress-bar.xsd"
/>
<xs:import
namespace="https://hyperview.org/scroll-opacity"
schemaLocation="scroll-opacity.xsd"
/>
<xs:import
namespace="https://hyperview.org/share"
schemaLocation="share.xsd"
Expand Down
31 changes: 31 additions & 0 deletions demo/schema/scroll-opacity.xsd
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
attributeFormDefault="qualified"
elementFormDefault="qualified"
targetNamespace="https://hyperview.org/scroll-opacity"
xmlns:hv="https://hyperview.org/hyperview"
>
<xs:import
namespace="https://hyperview.org/hyperview"
schemaLocation="hyperview.xsd"
/>
<xs:element name="scroll-opacity">
<xs:complexType>
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="context-key" type="xs:token" />
<xs:attribute name="axis">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="horizontal" />
<xs:enumeration value="vertical" />
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="distance" type="xs:nonNegativeInteger" />
<xs:attribute name="duration" type="xs:nonNegativeInteger" />
<xs:attribute name="initial-opacity" type="xs:nonNegativeInteger" />
</xs:complexType>
</xs:element>
</xs:schema>
61 changes: 61 additions & 0 deletions demo/src/Components/ScrollOpacity/ScrollOpacity.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { HvComponentProps, LocalName } from 'hyperview';
import Hyperview, { useScrollContext } from 'hyperview';
import React, { useEffect, useRef } from 'react';
import { getNumberAttr, namespaceURI } from './utils';
import { Animated } from 'react-native';

const ScrollOpacity = (props: HvComponentProps) => {
const contextKey = props.element.getAttributeNS(namespaceURI, 'context-key');
const axis = props.element.getAttributeNS(namespaceURI, 'axis') || 'vertical';
const distance = getNumberAttr(props.element, 'distance', 0);
const duration = getNumberAttr(props.element, 'duration', 0);
const initialOpacity = getNumberAttr(props.element, 'initial-opacity', 1);
const opacity = useRef(new Animated.Value(initialOpacity)).current;
const { offsets } = useScrollContext();

const defaultPosition = { x: 0, y: 0 };
const { x, y } = (() => {
if (!contextKey) {
return defaultPosition;
}
if (!offsets[contextKey]) {
return defaultPosition;
}
return offsets[contextKey];
})();
const position = (() => {
if (axis === 'horizontal') {
return x;
}
if (axis === 'vertical') {
return y;
}
throw new Error(`Invalid axis: ${axis}`);
})();

useEffect(() => {
const toValue = Math.min(
Math.max(position / Math.max(distance, 2) - 1, 0),
1,
);
Animated.timing(opacity, {
duration,
toValue,
useNativeDriver: true,
}).start();
}, [axis, contextKey, distance, duration, opacity, position, x, y]);

const children = (Hyperview.renderChildren(
props.element,
props.stylesheets,
props.onUpdate,
props.options,
) as unknown) as JSX.Element;
return <Animated.View style={{ opacity }}>{children}</Animated.View>;
};

ScrollOpacity.namespaceURI = namespaceURI;
ScrollOpacity.localName = 'scroll-opacity' as LocalName;
ScrollOpacity.localNameAliases = [] as LocalName[];

export { ScrollOpacity };
1 change: 1 addition & 0 deletions demo/src/Components/ScrollOpacity/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { ScrollOpacity } from './ScrollOpacity';
13 changes: 13 additions & 0 deletions demo/src/Components/ScrollOpacity/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const namespaceURI = 'https://hyperview.org/scroll-opacity';

export const getNumberAttr = (
element: Element,
attrName: string,
defaultValue: number | null = null,
): number => {
const value: string | null = element.getAttributeNS(namespaceURI, attrName);
if (!value) {
return defaultValue || 0;
}
return parseInt(value, 10);
};
2 changes: 2 additions & 0 deletions demo/src/Components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { BottomTabBar, BottomTabBarItem } from './BottomTabBar';
import { Map, MapMarker } from './Map';
import { Filter } from './Filter';
import { ProgressBar } from './ProgressBar';
import { ScrollOpacity } from './ScrollOpacity';
import { Svg } from './Svg';

export default [
Expand All @@ -19,5 +20,6 @@ export default [
Map,
MapMarker,
ProgressBar,
ScrollOpacity,
Svg,
];
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"test:generators": "yarn generate test && git diff --quiet HEAD",
"test:lint": "eslint src && prettier --check 'schema/**/*.xsd' 'test/**/*.xml' '**/*.md' && yarn format-njk -c",
"test:render": "npx patch-package && jest test/render.test.ts --forceExit",
"test:unit": "jest --testPathPattern src",
"test:unit": "jest --runInBand --testPathPattern src",
"test:validate-xml": "find test/schema -name '*.xml' | xargs xmlschema-validate --schema schema/hyperview.xsd --version 1.1",
"test": "yarn generate test && yarn test:ts && yarn test:lint && yarn test:render && yarn test:unit && yarn test:validate-xml"
},
Expand Down
2 changes: 2 additions & 0 deletions schema/scroll.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,7 @@
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="context-key" type="xs:token" />
<xs:attribute name="event-throttle" type="xs:nonNegativeInteger" />
</xs:attributeGroup>
</xs:schema>
3 changes: 2 additions & 1 deletion src/components/hv-list/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ import type {
} from 'hyperview/src/types';
import {
RefreshControl as DefaultRefreshControl,
FlatList,
Platform,
} from 'react-native';
import React, { PureComponent } from 'react';
import type { ScrollParams, State } from './types';
import { DOMParser } from '@instawork/xmldom';
import type { ElementRef } from 'react';
import { FlatList } from 'hyperview/src/core/components/scroll';
import { LOCAL_NAME } from 'hyperview/src/types';
import { getAncestorByTagName } from 'hyperview/src/services';

Expand Down Expand Up @@ -243,6 +243,7 @@ export default class HvList extends PureComponent<HvComponentProps, State> {
<FlatList
ref={this.onRef}
data={this.getItems()}
element={this.props.element}
horizontal={horizontal}
keyboardDismissMode={Keyboard.getKeyboardDismissMode(
this.props.element,
Expand Down
3 changes: 2 additions & 1 deletion src/components/hv-section-list/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ import type {
import {
RefreshControl as DefaultRefreshControl,
Platform,
SectionList,
} from 'react-native';
import { LOCAL_NAME, NODE_TYPE } from 'hyperview/src/types';
import React, { PureComponent } from 'react';
import type { ScrollParams, State } from './types';
import { DOMParser } from '@instawork/xmldom';
import type { ElementRef } from 'react';
import { SectionList } from 'hyperview/src/core/components/scroll';
import { getAncestorByTagName } from 'hyperview/src/services';

const getSectionIndex = (
Expand Down Expand Up @@ -356,6 +356,7 @@ export default class HvSectionList extends PureComponent<
return (
<SectionList
ref={this.onRef}
element={this.props.element}
keyboardDismissMode={Keyboard.getKeyboardDismissMode(
this.props.element,
)}
Expand Down
8 changes: 6 additions & 2 deletions src/components/hv-view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ import {
KeyboardAvoidingView,
Platform,
SafeAreaView,
ScrollView,
View,
ViewStyle,
} from 'react-native';
import {
KeyboardAwareScrollView,
ScrollView,
} from 'hyperview/src/core/components/scroll';
import React, { PureComponent } from 'react';
import { ATTRIBUTES } from './types';
import KeyboardAwareScrollView from 'hyperview/src/core/components/keyboard-aware-scroll-view';
import { LOCAL_NAME } from 'hyperview/src/types';
import { addHref } from 'hyperview/src/core/hyper-ref';
import { createStyleProp } from 'hyperview/src/services';
Expand Down Expand Up @@ -195,6 +197,7 @@ export default class HvView extends PureComponent<HvComponentProps> {
return React.createElement(
KeyboardAwareScrollView,
{
element: this.props.element,
...this.getCommonProps(),
...this.getScrollViewProps(children),
...this.getKeyboardAwareScrollViewProps(inputFieldRefs),
Expand All @@ -205,6 +208,7 @@ export default class HvView extends PureComponent<HvComponentProps> {
return React.createElement(
ScrollView,
{
element: this.props.element,
...this.getCommonProps(),
...this.getScrollViewProps(children),
},
Expand Down
2 changes: 1 addition & 1 deletion src/components/hv-view/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ export type KeyboardAwareScrollViewProps = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getTextInputRefs?: () => Array<any> | null | undefined;
keyboardShouldPersistTaps?: string | null | undefined;
scrollEventThrottle?: number | null | undefined;
scrollEventThrottle?: number | undefined;
scrollToInputAdditionalOffset?: number | null | undefined;
};
3 changes: 2 additions & 1 deletion src/core/components/hv-screen/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as Dom from 'hyperview/src/services/dom';
import * as Events from 'hyperview/src/services/events';
import * as Namespaces from 'hyperview/src/services/namespaces';
import * as Render from 'hyperview/src/services/render';
import * as Scroll from 'hyperview/src/core/components/scroll';
import * as Stylesheets from 'hyperview/src/services/stylesheets';
import { createProps, createStyleProp, later } from 'hyperview/src/services';
import { HvScreenRenderError } from './errors';
Expand Down Expand Up @@ -309,7 +310,7 @@ export default class HvScreen extends React.Component {
onPressReload: () => this.reload(),
})
: null}
{screenElement}
<Scroll.Provider>{screenElement}</Scroll.Provider>
</Contexts.DateFormatContext.Provider>
</Contexts.DocContext.Provider>
);
Expand Down
Loading

0 comments on commit e65f2b6

Please sign in to comment.