Skip to content

Commit

Permalink
fix(backlinks): use context uids to determine visibility
Browse files Browse the repository at this point in the history
  • Loading branch information
thesophiaxu committed Jan 1, 2022
1 parent 868fc04 commit b21953e
Show file tree
Hide file tree
Showing 8 changed files with 42 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export function AutoDynamicView({

const [DynamicViews, setDynamicViews] = React.useState({ ...window.unigraph.getState('registry/dynamicView').value, ...(component || {}) });

const viewEl = React.useRef(null);

React.useEffect(() => {
const cb = (newIts: any) => setDynamicViews({ ...window.unigraph.getState('registry/dynamicView').value, ...(component || {}) });
window.unigraph.getState('registry/dynamicView').subscribe(cb);
Expand Down Expand Up @@ -76,9 +78,12 @@ export function AutoDynamicView({
React.useEffect(() => {
if (object?.uid?.startsWith('0x') && shouldGetBacklinks) {
const cb = (newBacklinks: any) => {
// console.log(object.uid, " - Backlinks: ", backlinks)
const [pars, refs] = getParentsAndReferences(newBacklinks['~_value'], newBacklinks['unigraph.origin'], object.uid);
setBacklinks([pars, refs].map((it) => it.filter((el) => Object.keys(DynamicViews).includes(el?.type?.['unigraph.id']))));
// console.log(object.uid, getParents(viewEl.current));
setBacklinks([pars, refs].map((it) => it.filter((el) => (
Object.keys(DynamicViews).includes(el?.type?.['unigraph.id'])
&& !([...getParents(viewEl.current), callbacks?.context?.uid].includes(el.uid))
))));
};
subscribeToBacklinks(object.uid, cb);
return function cleanup() {
Expand Down Expand Up @@ -153,18 +158,20 @@ export function AutoDynamicView({
const contextEntity = typeof callbacks?.context === 'object' ? callbacks.context : null;

function getParents(elem: any) {
const parents = [];
const parents: any[] = [];
if (!elem) return parents;
while (elem.parentNode && elem.parentNode.nodeName.toLowerCase() != 'body') {
elem = elem.parentNode;
if (elem.id) parents.push(elem.id);
if (!elem) return parents;
if (elem.id?.startsWith?.('object-view-')) parents.push(elem.id.slice(12));
}
return parents;
}

const attach = React.useCallback((domElement) => {
if (domElement && object.uid) {
const ids = getParents(domElement);
if (ids.includes(`object-view-${object?.uid}`)) {
if (ids.includes(object?.uid)) {
// recursive - deal with it somehow
setIsRecursion(true);
} else setIsRecursion(false);
Expand All @@ -175,12 +182,13 @@ export function AutoDynamicView({
if (!noDrag) drag(domElement);
if (!noDrop) drop(domElement);
if (isMobile()) handlers.ref(domElement);
viewEl.current = domElement;
}, [isDragging, drag, callbacks]);

const BacklinkComponent = (
<div
style={{
display: (shouldGetBacklinks && (backlinks?.[1]?.length || (!noParents && (backlinks?.[0]?.length || 0) - (withParent ? 1 : 0) > 0))) ? '' : 'none',
display: (shouldGetBacklinks && (backlinks?.[1]?.length || (!noParents && backlinks?.[0]?.length > 0))) ? '' : 'none',
marginLeft: 'auto',
background: 'lightgray',
padding: '2px 6px',
Expand All @@ -198,13 +206,14 @@ export function AutoDynamicView({

const getEl = React.useCallback((viewId, setTitle) => {
if (isRecursion === false && object?.type && object.type['unigraph.id'] && Object.keys(DynamicViews).includes(object.type['unigraph.id']) && getObject()) {
console.log(object.uid, backlinks, noBacklinks, BacklinkComponent);
return React.createElement(DynamicViews[object.type['unigraph.id']].view, {
data: getObject(),
callbacks: {
viewId,
setTitle,
...(noBacklinks ? { BacklinkComponent } : {}),
...(callbacks || {}),
...(noBacklinks ? { BacklinkComponent } : {}),
},
...(attributes || {}),
inline,
Expand All @@ -223,7 +232,8 @@ export function AutoDynamicView({
);
}
return '';
}, [isRecursion, object, object.uid, callbacks, attributes, DynamicViews, isObjectStub, loadedObj, isFocused]);
}, [isRecursion, object, object?.uid, callbacks, attributes,
DynamicViews, isObjectStub, loadedObj, isFocused, backlinks]);

return (
<ErrorBoundary
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@ export const AutoDynamicViewDetailed: DynamicViewRenderer = ({
</div>
)}
>
<TabContext.Consumer>
{({ viewId, setTitle }) => React.createElement(DynamicViewsDetailed[object.type['unigraph.id']].view, {
<div style={{ display: 'contents' }} id={`object-view-${object.uid}`}>
<TabContext.Consumer>
{({ viewId, setTitle }) => React.createElement(DynamicViewsDetailed[object.type['unigraph.id']].view, {
data: isObjectStub
? loadedObj
: object,
Expand All @@ -61,7 +62,8 @@ export const AutoDynamicViewDetailed: DynamicViewRenderer = ({
context,
...(attributes || {}),
})}
</TabContext.Consumer>
</TabContext.Consumer>
</div>
</ErrorBoundary>
);
} if (useFallback) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { List } from '@material-ui/icons';
import { useDrop } from 'react-dnd';
import { onUnigraphContextMenu } from '../ObjectView/DefaultObjectContextMenu';
import { withUnigraphSubscription } from '../../unigraph-react';
import { AutoDynamicView } from '../ObjectView/AutoDynamicView';

export function MiniListView({ data }: any) {
const [{ isOver, canDrop }, dropSub] = useDrop(() => ({
Expand All @@ -21,7 +22,6 @@ export function MiniListView({ data }: any) {
return (
<Grid item xs={12} sm={6} ref={dropSub}>
<Card
onContextMenu={(event) => onUnigraphContextMenu(event, data)}
variant="outlined"
style={{ padding: '8px', display: 'flex' }}
onClick={() => {
Expand All @@ -33,7 +33,7 @@ export function MiniListView({ data }: any) {
{data?._value?.name?.['_value.%']}
{' '}
(
{(data?._value?.children?.items || 0).toString()}
{(data?._value?.children?.items || data?._value?.children?.['_value[']?.length || 0).toString()}
)
</Typography>
</Card>
Expand All @@ -44,7 +44,7 @@ export function MiniListView({ data }: any) {
export const ListsList = withUnigraphSubscription(({ data }: any) => (
<div>
<Grid container spacing={1}>
{(data || []).map((el: any) => <MiniListView data={el} />)}
{(data || []).map((el: any) => <MiniListView data={el} inline />)}
</Grid>
</div>
), { schemas: [], defaultData: [], packages: [] }, {
Expand All @@ -60,6 +60,7 @@ export const ListsList = withUnigraphSubscription(({ data }: any) => (
items: count(<_value[>)
}
}
type { <unigraph.id> }
}
var(func: eq(<unigraph.id>, "$/schema/list")) {
<~type> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ function NoteViewPageWrapper({ children, isRoot }: any) {
function NoteViewTextWrapper({
children, semanticChildren, isRoot, onContextMenu, callbacks,
}: any) {
// console.log(callbacks.BacklinkComponent);
return (
<div style={{ display: 'flex', alignItems: 'center' }}>
{children}
Expand Down Expand Up @@ -508,7 +509,6 @@ export function DetailedNoteBlock({
>
<AutoDynamicView
noDrag
withParent
allowSubentity
noBacklinks={el.type?.['unigraph.id'] === '$/schema/note_block'}
subentityExpandByDefault={!(el.type?.['unigraph.id'] === '$/schema/note_block')}
Expand All @@ -533,6 +533,7 @@ export function DetailedNoteBlock({
'focus-last-dfs-node': focusLastDFSNode,
'focus-next-dfs-node': focusNextDFSNode,
dataref,
context: data,
isEmbed: true,
}}
component={{ '$/schema/note_block': { view: DetailedNoteBlock, query: noteQuery }, '$/schema/view': { view: ViewViewDetailed } }}
Expand Down
3 changes: 2 additions & 1 deletion packages/unigraph-dev-explorer/src/examples/notes/init.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { MenuItem, Typography } from '@material-ui/core';
import { UnigraphObject } from 'unigraph-dev-common/lib/utils/utils';
import { AutoDynamicViewDetailed } from '../../components/ObjectView/AutoDynamicViewDetailed';
import { inlineRefsToChildren } from '../../components/UnigraphCore/InlineSearchPopup';
import {
registerDynamicViews, registerDetailedDynamicViews, registerContextMenuItems, registerQuickAdder,
Expand All @@ -10,7 +11,7 @@ import { noteQuery, noteQueryDetailed, journalQueryDetailed } from './noteQuery'
export const init = () => {
registerDynamicViews({ '$/schema/note_block': { view: NoteBlock, query: noteQuery } });
registerDetailedDynamicViews({ '$/schema/note_block': { view: DetailedNoteBlock, query: noteQueryDetailed } });
registerDetailedDynamicViews({ '$/schema/journal': { view: (props: any) => DetailedNoteBlock({ ...props, data: new UnigraphObject(props.data._value.note._value), callbacks: { ...props.callbacks, isEmbed: true } }), query: journalQueryDetailed } });
registerDetailedDynamicViews({ '$/schema/journal': { view: (props: any) => <AutoDynamicViewDetailed {...props} object={new UnigraphObject(props.data._value.note._value)} callbacks={{ ...props.callbacks, isEmbed: true }} />, query: journalQueryDetailed } });

// eslint-disable-next-line default-param-last
const quickAdder = async (inputStr: string, preview = true, callback: any, refs?: any) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,13 @@ export const Tweet: DynamicViewRenderer = ({ data, callbacks }) => {
if (elObj.type['unigraph.id'] === '$/schema/icon_url') {
return <img src={elObj['_value.%']} style={{ maxWidth: '240px', borderRadius: '8px' }} alt="" />;
}
return <AutoDynamicView object={new UnigraphObject(elObj)} withParent />;
return (
<AutoDynamicView
object={new UnigraphObject(elObj)}
withParent
callbacks={{ context: data }}
/>
);
})}
</div>
</div>
Expand Down
2 changes: 2 additions & 0 deletions packages/unigraph-dev-explorer/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { ListObjectQuery, ListObjectView } from './components/UnigraphCore/ListO
import { SubentityView } from './components/UnigraphCore/SubentityView';
import { ViewItem } from './components/ObjectView/ViewObjectView';
import { backlinkQuery } from './components/ObjectView/backlinksUtils';
import { MiniListView } from './components/UnigraphCore/ListsList';

window.reloadCommands = () => {
const commandsState = window.unigraph.getState('registry/commands');
Expand Down Expand Up @@ -144,6 +145,7 @@ function initRegistry() {
'$/schema/person': { view: BasicPersonView },
'$/schema/subentity': { view: SubentityView },
'$/schema/view': { view: ViewItem },
'$/schema/list': { view: MiniListView },
});
window.unigraph.addState('registry/dynamicViewDetailed', {
'$/schema/executable': { view: CodeOrComponentView },
Expand Down
2 changes: 2 additions & 0 deletions packages/unigraph-dev-explorer/src/unigraph-react.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export const subscribeToBacklinks = (uid: string[] | string, callback?: any, rem
: _.uniq([...uids, ...Object.keys(linksState.value)]);
linksState.setValue(
Object.fromEntries(newKeys.map((el) => [el, linksState.value[el]])),
true,
);
const cbState = window.unigraph.getState('registry/backlinksCallbacks');
const newCbs = _.uniq([...uids, ...Object.keys(cbState.value)]);
Expand All @@ -79,6 +80,7 @@ export const subscribeToBacklinks = (uid: string[] | string, callback?: any, rem
: (remove ? undefined : [callback]),
]),
),
true,
);
};

Expand Down

0 comments on commit b21953e

Please sign in to comment.