Skip to content

Commit

Permalink
Merge pull request #10 from tinloof/document-icon-preview
Browse files Browse the repository at this point in the history
Media preview now renders document icon + fix overflow styling issue
  • Loading branch information
thomasKn authored Mar 29, 2024
2 parents 1a54556 + 663bb7a commit f4547df
Show file tree
Hide file tree
Showing 14 changed files with 53 additions and 74 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
"publish-packages": "turbo run build --filter='./packages/*' lint && changeset version && changeset publish",
"postinstall": "manypkg check",
"fix:deps": "manypkg fix && pnpm install"
"fix:deps": "manypkg fix && pnpm install",
"typecheck": "turbo run typecheck"
},
"engines": {
"node": ">=18"
Expand Down
3 changes: 2 additions & 1 deletion packages/sanity-studio/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"lint": "eslint .",
"prepublishOnly": "run-s build",
"watch": "pkg-utils watch --strict",
"dev": "run-s watch"
"dev": "run-s watch",
"typecheck": "tsc --noEmit"
},
"exports": {
".": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export function PathnameFieldComponent(props: ObjectFieldProps<SlugValue>) {
locale: i18nOptions.enabled ? document.locale : undefined,
pathname: value?.current,
},
i18nOptions.defaultLocaleId
i18nOptions.defaultLocaleId || ""
);

const pathInput = useMemo(() => {
Expand Down Expand Up @@ -141,7 +141,7 @@ export function PathnameFieldComponent(props: ObjectFieldProps<SlugValue>) {
disabled={readOnly}
/>
</Box>
<PreviewButton localizedPathname={localizedPathname} />
<PreviewButton localizedPathname={localizedPathname || ""} />
</Flex>
);
}
Expand All @@ -159,7 +159,7 @@ export function PathnameFieldComponent(props: ObjectFieldProps<SlugValue>) {
style={{ flex: 1 }}
/>
</Box>
<PreviewButton localizedPathname={localizedPathname} />
<PreviewButton localizedPathname={localizedPathname || ""} />
</Flex>
);
}, [
Expand Down
4 changes: 2 additions & 2 deletions packages/sanity-studio/src/plugins/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ export type SanityI18NPluginOptions = {
// Extracts the schema types that have a locale field
function extractTranslatableSchemaTypes(schemas: BaseSchemaDefinition[]) {
return schemas
.filter((schema: DocumentDefinition) =>
.filter((schema: any) =>
schema?.fields?.find((field) => field.name === "locale")
)
.map((schema: DocumentDefinition) => schema.name);
.map((schema) => schema.name);
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,15 @@ function DefaultPagesNavigator(props: PagesNavigatorOptions) {

const [data, loading] = useSanityFetch({
query: pagesRoutesQuery,
variables: {},
});

return (
<ThemeProvider>
<NavigatorProvider i18n={props.i18n} data={data || []}>
<Header pages={props.creatablePages}>
<SearchBox />
{props.i18n?.locales.length > 1 ? (
{props.i18n?.locales?.length && props.i18n.locales.length > 1 ? (
<LocaleSelect locales={props.i18n.locales} />
) : null}
</Header>
Expand Down
56 changes: 17 additions & 39 deletions packages/sanity-studio/src/plugins/navigator/components/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ const ListWrapper = styled(Box)`
border: 2px solid transparent;
padding: 2px;
border-radius: 8px;
width: 100%;
height: 88vh;
overflow-y: auto;
margin: 0;
display: flex;
gap: 0.25rem;
flex-direction: column;
`;

Expand Down Expand Up @@ -174,44 +174,30 @@ const List = ({ loading }: { loading: boolean }) => {
aria-label="Pages and folders"
aria-activedescendant={`item-${activeDescendant}`}
>
<div
style={{
height: `${virtualizer.getTotalSize()}px`,
width: "100%",
position: "relative",
}}
>
{virtualizer.getVirtualItems().map((virtualChild) => {
const item = items[virtualChild.index];
return (
<ListItem
key={virtualChild.index}
item={item}
active={activeDescendant}
setActive={setActiveDescendant}
idx={virtualChild.index}
virtualChild={virtualChild}
/>
);
})}
</div>
{virtualizer.getVirtualItems().map((virtualChild) => {
const item = items[virtualChild.index];
return (
<ListItem
key={virtualChild.index}
item={item}
active={activeDescendant}
setActive={setActiveDescendant}
idx={virtualChild.index}
virtualChild={virtualChild}
/>
);
})}
</ListWrapper>
</Card>
);
};

const ListItem = ({
item,
active,
setActive,
idx,
virtualChild,
}: ListItemProps) => {
const ListItem = ({ item, active, setActive, idx }: ListItemProps) => {
const { defaultLocaleId, setCurrentDir, currentDir } = useNavigator();
const innerRef = useRef<HTMLLIElement>(null);
const listItemId = `item-${idx}`;
const path = localizePathname({
pathname: item.pathname,
pathname: item.pathname || "",
localeId: item.locale,
isDefault: defaultLocaleId === item.locale,
});
Expand All @@ -229,7 +215,7 @@ const ListItem = ({
id: item._id,
});
} else {
setCurrentDir(item.pathname);
setCurrentDir(item.pathname || "");
}
};

Expand Down Expand Up @@ -278,14 +264,6 @@ const ListItem = ({
aria-selected={listItemId === active}
currentScheme={scheme}
isPreviewed={previewed}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: `${virtualChild?.size}px`,
transform: `translateY(${virtualChild?.start}px)`,
}}
>
<Flex align="center" gap={2} flex={1}>
<Flex
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ const PreviewElement = ({
item: Exclude<TreeNode, FolderTreeNode>; // Only accepts a PageTreeNode, FolderTreeNode is forbidden
type: "media" | "title" | "subtitle";
fallback?: React.ReactNode | string;
}): React.ReactElement => {
}): React.ReactElement | null => {
const schema = useSchema();
const { _id, _type } = item;

const documentPreviewStore = useDocumentPreviewStore();
const schemaType = schema.get(_type);

const { draft, published, isLoading } = useMemoObservable(
() => getPreviewStateObservable(documentPreviewStore, schemaType, _id, ""),
() => getPreviewStateObservable(documentPreviewStore, schemaType!, _id, ""),
[_id, documentPreviewStore, schemaType]
)!;

Expand All @@ -44,15 +44,16 @@ const PreviewElement = ({
});

const showPreview =
typeof schemaType.preview?.prepare === "function" && !isLoading;
schemaType?.icon ||
(typeof schemaType?.preview?.prepare === "function" && !isLoading);

if (type === "media") {
return showPreview ? (
<PreviewMedia
{...previewValues}
isPlaceholder={isLoading ?? true}
layout="default"
icon={schemaType.icon}
icon={schemaType?.icon}
/>
) : (
<>{!isLoading ? fallback : null}</>
Expand Down Expand Up @@ -118,10 +119,10 @@ const PreviewMedia = (props: SanityDefaultPreviewProps): React.ReactElement => {
.image(
mediaProp as SanityImageSource /*will only enter this code path if it's compatible*/
)
.width(dimensions?.width)
.height(dimensions.height)
.width(dimensions?.width || 100)
.height(dimensions.height || 100)
.fit(dimensions.fit)
.dpr(dimensions.dpr)
.dpr(dimensions.dpr || 1)
.url() || ""
}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export const NavigatorProvider = ({
const targetTree = findTreeByPath(rootTree, state.currentDir);
const currentTree = targetTree || rootTree;
const items = Object.values(currentTree || rootTree).sort((a, b) =>
a.pathname.localeCompare(b.pathname)
a.pathname && b.pathname ? a.pathname.localeCompare(b.pathname) : 0
);

useEffect(() => {
Expand Down Expand Up @@ -168,12 +168,12 @@ function searchTree({
const item: TreeNode = tree[key];
if (
item.title.toLowerCase().startsWith(q) ||
item.pathname.toLowerCase().startsWith(q) ||
item.pathname?.toLowerCase().startsWith(q) ||
item.title
.split(" ")
.some((word) => word.toLowerCase().startsWith(q)) ||
item.pathname
.toLowerCase()
?.toLowerCase()
.split("/")
.some((word) => {
return word.startsWith(q);
Expand Down
8 changes: 4 additions & 4 deletions packages/sanity-studio/src/plugins/navigator/utils/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { capitalize } from "lodash";
import { useMemoObservable } from "react-rx";
import { useDocumentStore } from "sanity";
import { QueryParams, useDocumentStore } from "sanity";

import {
NormalizedCreatablePage,
Expand All @@ -15,7 +15,7 @@ export const useSanityFetch = ({
variables,
}: {
query: string;
variables?: Record<string, any>;
variables: QueryParams;
}) => {
const documentStore = useDocumentStore();
const subscribe = useMemoObservable(
Expand Down Expand Up @@ -44,11 +44,11 @@ export function buildTree(list: Page[]): Tree {
for (const item of list) {
const isDraft = item._originalId.startsWith("drafts.");
const segments =
item.pathname === "/" ? [""] : item.pathname.split("/").filter(Boolean);
item.pathname === "/" ? [""] : item.pathname?.split("/").filter(Boolean);
let currentFolder = root;
let pathSoFar = "";

segments.forEach((segment, index) => {
segments?.forEach((segment, index) => {
const isFolder = index !== segments.length - 1;
pathSoFar += `/${segment}`;

Expand Down
7 changes: 4 additions & 3 deletions packages/sanity-studio/src/utils/definePathname.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { FieldDefinition, SlugValidationContext, defineField } from "sanity";
import { defineField, FieldDefinition, SlugValidationContext } from "sanity";

import { PathnameFieldComponent } from "../components/PathnameFieldComponent";
import { PathnameParams } from "../types";

Expand Down Expand Up @@ -29,12 +30,12 @@ async function isUnique(
): Promise<boolean> {
const { document, getClient } = context;
const client = getClient({ apiVersion: "2023-06-21" });
const id = document._id.replace(/^drafts\./, "");
const id = document?._id.replace(/^drafts\./, "");
const params = {
draft: `drafts.${id}`,
published: id,
slug,
locale: document.locale ?? null,
locale: document?.locale ?? null,
};
const query = `*[!(_id in [$draft, $published]) && pathname.current == $slug && locale == $locale]`;
const result = await client.fetch(query, params);
Expand Down
2 changes: 1 addition & 1 deletion packages/sanity-studio/tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"noImplicitAny": true,
"noImplicitAny": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
Expand Down
10 changes: 3 additions & 7 deletions packages/sanity-studio/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
{
"extends": "./tsconfig.base",
"compilerOptions": {
"incremental": true,
"noEmit": true,
"strictNullChecks": true
"incremental": false,
"noEmit": true
},
"include": [
"**/*.ts",
"**/*.tsx",
],
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["dist", "node_modules"]
}
1 change: 0 additions & 1 deletion packages/sanity-studio/tsconfig.tsbuildinfo

This file was deleted.

3 changes: 2 additions & 1 deletion turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"dev": {
"cache": false,
"persistent": true
}
},
"typecheck": {}
}
}

0 comments on commit f4547df

Please sign in to comment.