Git Product home page Git Product logo

language-filter's Introduction

@sanity/language-filter

This is a Sanity Studio v3 plugin. For the v2 version, please refer to the v2 version.

Field-level translation filter Plugin for Sanity.io

A Sanity plugin that supports filtering localized fields by language

Language Filter UI

What this plugin solves

There are two popular methods of internationalization in Sanity Studio:

  • Field-level translation
    • A single document with many languages of content
    • Achieved by mapping over languages on each field, to create an object
    • Best for documents that have a mix of language-specific and common fields
    • Not recommended for Portable Text
  • Document-level translation
    • A unique document version for every language
    • Joined together by references and/or a predictable _id
    • Best for documents that have unique, language-specific fields and no common content across languages
    • Best for translating content using Portable Text

This plugin adds features to the Studio to improve handling field-level translations.

  • A "Filter Languages" button to show/hide fields in an object of language-specific fields
  • Configuration to set "default" languages which are always visible

For document-level translations you should use the @sanity/document-internationalization plugin.

Installation

npm install --save @sanity/language-filter

or

yarn add @sanity/language-filter

Usage

Add it as a plugin in sanity.config.ts (or .js), and configure it:

 import {defineConfig} from 'sanity'
 import {languageFilter} from '@sanity/language-filter'

 export const defineConfig({
     //...
     plugins: [
        languageFilter({
            supportedLanguages: [
              {id: 'nb', title: 'Norwegian (Bokmål)'},
              {id: 'nn', title: 'Norwegian (Nynorsk)'},
              {id: 'en', title: 'English'},
              {id: 'es', title: 'Spanish'},
              {id: 'arb', title: 'Arabic'},
              {id: 'pt', title: 'Portuguese'},
              //...
            ],
            // Select Norwegian (Bokmål) by default
            defaultLanguages: ['nb'],
            // Only show language filter for document type `page` (schemaType.name)
            documentTypes: ['page'],
            filterField: (enclosingType, member, selectedLanguageIds) =>
              !enclosingType.name.startsWith('locale') || selectedLanguageIds.includes(member.name),
       })
     ]
 })

Config properties:

  • supportedLanguages can be either: -- An static array of language objects with id and title. If your localized fields are defined using our recommended way described here (https://www.sanity.io/docs/localization), you probably want to share this list of supported languages between this config and your schema. -- A function that returns a promise resolving to an array of language objects with id and title. This is useful if you want to fetch the list of supported languages from an external source. See Loading languages for more details.
  • defaultLanguages (optional) is an array of strings where each entry must match an id from the supportedLanguages array. These languages will be listed by default and will not be possible to unselect. If no defaultLanguages is configured, all localized fields will be selected by default.
  • documentTypes (optional) is an array of strings where each entry must match a name from your document schemas. If defined, this property will be used to conditionally show the language filter on specific document schema types. If undefined, the language filter will show on all document schema types.
  • filterField (optional) is a function that must return true if the field should be displayed. It is passed the enclosing type (e.g the object type containing the localized fields, the field, and an array of the currently selected language ids. This function is called for all fields and in objects for documents that have language filter enabled. Default: !enclosingType.name.startsWith('locale') || selectedLanguageIds.includes(field.name)
  • apiVersion (optional) used for the Sanity Client when asynchronously loading languages.

Loading languages

Languages must be an array of objects with an id and title.

languages: [
  {id: 'en', title: 'English'},
  {id: 'fr', title: 'French'}
],

Or an asynchronous function that returns an array of objects with an id and title.

languages: async () => {
  const response = await fetch('https://example.com/languages')
  return response.json()
}

The async function contains a configured Sanity Client in the first parameter, allowing you to store Language options as documents. Your query should return an array of objects with an id and title.

languages: async (client) => {
  const response = await client.fetch(`*[_type == "language"]{ id, title }`)
  return response
},

@sanity/language-filter's asynchronous language loading does not currently support modifying the query based on a value in the current document.

Changes in V3

documentTypes

Language filter can now be enabled/disabled directly from a schema, using options.languageFilter: boolean. When documentTypes is omitted from plugin config, use options.languageFilter: false in a document-definition to hide the filter button. When documentTypes is provided in plugin config, use options.languageFilter: true in a document-definition to show the filter button.

Example:

export const myDocumentSchema = {
  type: 'document',
  name: 'my-enabled-language-filter-document',
  /** ... */
  options: {
    // show language filter for this document type, regardless of how documentTypes for the plugin is configured
    languageFilter: true,
  },
}

License

MIT-licensed. See LICENSE.

Develop & test

This plugin uses @sanity/plugin-kit with default configuration for build & watch scripts.

See Testing a plugin in Sanity Studio on how to run this plugin with hotreload in the studio.

Release new version

Run "CI & Release" workflow. Make sure to select the main branch and check "Release new version".

Semantic release will only release on configured branches, so it is safe to run release on any branch.

language-filter's People

Contributors

benja avatar renovate[bot] avatar semantic-release-bot avatar simeongriggs avatar snorrees avatar stipsan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

language-filter's Issues

Versions of language-filter above v3.0.1 don't work

We recently updated Sanity and all the plugins to the latest versions. For the language filter only the dropdown menu is shown, but when I choose different languages nothing happens, only the language gets deselected from the dropdown menu and nothing else.

We previously had Sanity v3.7, now we have v3.14.1
For the language-filter any version above v3.0.1 does not work from our testing.

Hide the translations fieldset if no languages are selected

When following the recommended implementation for field level translations, the translation fields are stored in a fieldset. If only the default language is selected, I expect the fieldset to be hidden, as there are no fields to be displayed.

While this can be implemented manually, I would expect this to be part of this plugin.

Screenshots

The first screenshot shows the behavior for a scenario where all (or at least one) language is selected.
image

As shown below, the fieldset legend is still visible, if no fields are displayed.
image

The expected behavior would be the removal of the fieldset, as demonstrated in the screenshot below.
image

Type '{ languageFilter: true; }' is not assignable to type 'EnumListProps<string>'.

What do I do wrong. can turn on localization for field
I have the following config

import {MdStar as icon} from 'react-icons/md'
import {defineField, defineType} from 'sanity'
import {LanguageFilterOptions} from '@sanity/language-filter'

export default defineType({
  name: 'ganre',
  title: 'Ganre',
  type: 'document',
  icon,
  fields: [
    defineField({
      name: 'name',
      title: 'Ganre',
      type: 'string',
      validation: (Rule) => Rule.required(),
    }),
    defineField({
      name: 'localeName',
      title: 'Locale',
      type: 'string',
      options: {
        languageFilter: true, // PROBLEM HERE
      },
    }),

    defineField({
      name: 'isFeatured',
      title: 'Is Featured',
      type: 'boolean',
      validation: (Rule) => Rule.required(),
    }),
    defineField({
      name: 'slug',
      title: 'Slug',
      type: 'slug',
      options: {
        source: 'name',
        maxLength: 100,
      },
    }),
    defineField({
      name: 'description',
      title: 'Description',
      type: 'string',
      validation: (Rule) => Rule.required(),
    }),
    defineField({
      name: 'image',
      title: 'Image',
      type: 'image',
      validation: (Rule) => Rule.required(),
      options: {
        hotspot: true,
      },
    }),
  ],
  initialValue: {
    isFeatured: false,
  },
})

Nested fields in arrays doesn't show up

I have made a localeString. It can filter as expected.

However it will not display if it is nested within an array.

Document > Array > Object > localeString

Even hardcoding true as return type for filterField doesn't help.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.


Using a curated preset maintained by


Sanity: The Composable Content Cloud

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency eslint-config-sanity to v7
  • chore(deps): update dependency eslint-plugin-prettier to v5
  • chore(deps): update dependency prettier to v3
  • chore(deps): update dependency rimraf to v4
  • chore(deps): update dependency typescript to v5
  • chore(deps): update linters to v6 (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/main.yml
  • actions/checkout v3@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8
  • actions/setup-node v3@8c91899e586c5b171469028077307d293428b516
  • actions/checkout v3@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8
  • actions/setup-node v3@8c91899e586c5b171469028077307d293428b516
  • actions/checkout v3@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8
  • actions/setup-node v3@8c91899e586c5b171469028077307d293428b516
npm
package.json
  • @sanity/icons ^2.0.0
  • @sanity/incompatible-plugin ^1.0.4
  • @sanity/ui ^1.0.0
  • @sanity/util ^3.0.0
  • @babel/preset-env ^7.19.4
  • @babel/preset-react ^7.18.6
  • @commitlint/cli ^17.2.0
  • @commitlint/config-conventional ^17.2.0
  • @sanity/pkg-utils ^2.4.9
  • @sanity/plugin-kit ^2.1.5
  • @sanity/semantic-release-preset ^2.0.2
  • @types/jest ^29.2.1
  • @types/styled-components ^5.1.26
  • @typescript-eslint/eslint-plugin ^5.42.0
  • @typescript-eslint/parser ^5.42.0
  • eslint ^8.26.0
  • eslint-config-prettier ^8.5.0
  • eslint-config-sanity ^6.0.0
  • eslint-plugin-prettier ^4.2.1
  • eslint-plugin-react ^7.31.10
  • eslint-plugin-react-hooks ^4.6.0
  • jest ^29.2.2
  • prettier ^2.7.1
  • prettier-plugin-packagejson ^2.3.0
  • react ^18
  • rimraf ^3.0.2
  • sanity ^3.0.0
  • styled-components ^5.3.8
  • ts-jest ^29.0.3
  • typescript ^4.8.4
  • react ^18
  • sanity ^3
  • styled-components ^5.2
  • node >=14

  • Check this box to trigger a request for Renovate to run again on this repository

"The page tool crashed"

Error: "The page tool crashed"

I'm using Next.js 14.0.3 App Router and Sanity.io v3. I'm getting the error shown in the image below. I'm connecting to Sanity.io using the "next-sanity" package in Nextjs. I think there is a problem with the "language-filter" of next-sanity. Can you help me please?

Screenshots:

Ekran Resmi 2023-11-28 11 07 14

These are sanity versions:

@sanity/cli (global)                   3.20.1 (up to date)
@sanity/cli                            3.20.1 (up to date)
@sanity/color                           2.2.5 (up to date)
@sanity/dashboard                       3.1.5 (up to date)
@sanity/document-internationalization   2.0.2 (up to date)
@sanity/icons                           2.7.0 (up to date)
@sanity/image-url                       1.0.2 (up to date)
@sanity/language-filter                 3.2.1 (up to date)
@sanity/preview-kit                     4.0.1 (up to date)
@sanity/types                          3.20.1 (up to date)
@sanity/ui                              1.9.3 (up to date)
@sanity/vision                         3.20.1 (up to date)
sanity                                 3.20.1 (up to date)

What operating system are you using?

  • macOS

Which versions of Node.js / npm are you running? npm -v && node -v

npm: 9.8.1
node: v18.18.2

Additional context:

// /sanity/client.ts
import { deskTool } from "sanity/desk";
import { visionTool } from "@sanity/vision";
import { PluginOptions, defineConfig } from "sanity";
import { languageFilter } from '@sanity/language-filter'

import { langs } from "@/encoded-url";
import { ApiIcon } from "@sanity/icons";
import { NEXT_PUBLIC_SANITY_DATASET_PRODUCTION, NEXT_PUBLIC_SANITY_DATASET_STAGING, NEXT_PUBLIC_SANITY_PROJECT_ID } from "@/utils/constants";
import { PAGES_NAME } from "@/sanity/schemas/constants";
import { i18nConfig } from "@/i18nConfig";

// Sanity plugins
import { settings, pages } from "@/sanity/plugins";

// Sanity schemas
import { schema } from "@/sanity/schemas";

const plugins: PluginOptions[] = [
	languageFilter({
		documentTypes: [PAGES_NAME], // <-- hangi sayfalar çevrilecek?
		defaultLanguages: [i18nConfig.defaultLocale],
		supportedLanguages: langs.map(m => ({ id: m.code, title: `${m.title} (${m.originalTitle})` })),
		filterField: (enclosingType, field, selectedLanguageIds) => !enclosingType.name.startsWith("locale") || selectedLanguageIds.includes(field.name),
	}),
	deskTool(pages),
	deskTool(settings),
];

export default defineConfig([
         // other configs and admin...
	{
		name: "admin",
		basePath: "/admin",
		projectId: NEXT_PUBLIC_SANITY_PROJECT_ID,
		dataset: NEXT_PUBLIC_SANITY_DATASET_PRODUCTION,
		schema,
		plugins: [
			...plugins,
			visionTool({
				name: "groq-query",
				title: "Vision",
				icon: ApiIcon,
			}),
		],
	}
]);
// sanity/sanity.config.tsx
import { deskTool } from "sanity/desk";
import { visionTool } from "@sanity/vision";
import { PluginOptions, defineConfig } from "sanity";
import { languageFilter } from '@sanity/language-filter'

import { langs } from "@/encoded-url";
import { ApiIcon } from "@sanity/icons";
import { NEXT_PUBLIC_SANITY_DATASET_PRODUCTION, NEXT_PUBLIC_SANITY_DATASET_STAGING, NEXT_PUBLIC_SANITY_PROJECT_ID } from "@/utils/constants";
import { PAGES_NAME } from "@/sanity/schemas/constants";
import { i18nConfig } from "@/i18nConfig";

// Sanity plugins
import { settings, pages } from "@/sanity/plugins";

// Sanity schemas
import { schema } from "@/sanity/schemas";

const plugins: PluginOptions[] = [
	languageFilter({
		documentTypes: [PAGES_NAME], // <-- hangi sayfalar çevrilecek?
		defaultLanguages: [i18nConfig.defaultLocale],
		supportedLanguages: langs.map(m => ({ id: m.code, title: `${m.title} (${m.originalTitle})` })),
		filterField: (enclosingType, field, selectedLanguageIds) => !enclosingType.name.startsWith("locale") || selectedLanguageIds.includes(field.name),
	}),
	deskTool(pages),
	deskTool(settings),
];

export default defineConfig([
	{
		name: "staging",
		basePath: "/staging",
		projectId: NEXT_PUBLIC_SANITY_PROJECT_ID,
		dataset: NEXT_PUBLIC_SANITY_DATASET_STAGING,
		schema,
		plugins: [
			...plugins,
			visionTool({
				name: "groq-query",
				title: "Vision",
				icon: ApiIcon,
			}),
		],
	},
	{
		name: "admin",
		basePath: "/admin",
		projectId: NEXT_PUBLIC_SANITY_PROJECT_ID,
		dataset: NEXT_PUBLIC_SANITY_DATASET_PRODUCTION,
		schema,
		plugins: [
			...plugins,
			visionTool({
				name: "groq-query",
				title: "Vision",
				icon: ApiIcon,
			}),
		],
	}
]);
// sanity/plugins/pages.tsx
import { upperFirst } from "lodash";
import { urls, langs } from "@/encoded-url";
import { SanityPluginInfos } from "./types";
import { PAGES_NAME } from "@/sanity/schemas/constants";
import { NEXT_PUBLIC_SANITY_API_VERSION } from "@/utils/constants";
import { DeskToolOptions, StructureBuilder, StructureResolverContext } from "sanity/desk";

import { TextIcon as icon, HomeIcon, EditIcon } from "@sanity/icons";

const plugin: SanityPluginInfos = {
	name: PAGES_NAME,
	title: upperFirst(PAGES_NAME),
	icon,
};

export const pages: DeskToolOptions = {
	name: PAGES_NAME,
	title: plugin.title,
	icon,
	structure: (S: StructureBuilder, context: StructureResolverContext) => {
		const { getClient, schema, currentUser } = context;
		return S.documentTypeList(plugin.name);
	},
};

styled-components missmatch

Hey when using the latest Sanity, Sanity Presentation (which is part of the core Sanity Studio) requires styled-components@^6.1.1 while language-filter requires styled-components@^5.2.

image

Could not resolve styled-component

Hi have sanity v3.7.0 nextjs 13.2. I have installed from yarn this package and now have this error

`9:38:08 PM [vite] page reload sanity.config.ts
✘ [ERROR] Could not resolve "sanity"

../node_modules/@sanity/language-filter/lib/index.esm.js:1:1275:
  1 │ ...om"react/jsx-runtime";import{definePlugin as d}from"sanity";import{createContext as u,useMemo as g,useContext...
    ╵                                                       ~~~~~~~~

You can mark the path "sanity" as external to exclude it from the bundle, which will remove this
error.

✘ [ERROR] Could not resolve "styled-components"

../node_modules/@sanity/language-filter/lib/index.esm.js:1:1544:
  1 │ ... I,Button as L}from"@sanity/ui";import T from"styled-components";const P=(e,n,t)=>!e.name.startsWith("locale"...
    ╵                                                 ~~~~~~~~~~~~~~~~~~~

You can mark the path "styled-components" as external to exclude it from the bundle, which will
remove this error.

✘ [ERROR] Could not resolve "styled-components"

../node_modules/@sanity/ui/dist/index.esm.js:6:97:
  6 │ ...t styled, { ThemeProvider as ThemeProvider$1, useTheme as useTheme$1, css, keyframes } from 'styled-components';
    ╵                                                                                                ~~~~~~~~~~~~~~~~~~~

You can mark the path "styled-components" as external to exclude it from the bundle, which will
remove this error.

9:38:11 PM [vite] error while updating dependencies:
Error: Build failed with 3 errors:
../node_modules/@sanity/language-filter/lib/index.esm.js:1:1275: ERROR: Could not resolve "sanity"
../node_modules/@sanity/language-filter/lib/index.esm.js:1:1544: ERROR: Could not resolve "styled-components"
../node_modules/@sanity/ui/dist/index.esm.js:6:97: ERROR: Could not resolve "styled-components"
at failureErrorWithLog (/Users/yaroslavkaplunskyi/nextjs-projects/nextjs_TS/sanity-cms/node_modules/esbuild/lib/main.js:1604:15)
at /Users/yaroslavkaplunskyi/nextjs-projects/nextjs_TS/sanity-cms/node_modules/esbuild/lib/main.js:1056:28
at runOnEndCallbacks (/Users/yaroslavkaplunskyi/nextjs-projects/nextjs_TS/sanity-cms/node_modules/esbuild/lib/main.js:1476:61)
at buildResponseToResult (/Users/yaroslavkaplunskyi/nextjs-projects/nextjs_TS/sanity-cms/node_modules/esbuild/lib/main.js:1054:7)
at /Users/yaroslavkaplunskyi/nextjs-projects/nextjs_TS/sanity-cms/node_modules/esbuild/lib/main.js:1166:14
at responseCallbacks. (/Users/yaroslavkaplunskyi/nextjs-projects/nextjs_TS/sanity-cms/node_modules/esbuild/lib/main.js:701:9)
at handleIncomingPacket (/Users/yaroslavkaplunskyi/nextjs-projects/nextjs_TS/sanity-cms/node_modules/esbuild/lib/main.js:756:9)
at Socket.readFromStdout (/Users/yaroslavkaplunskyi/nextjs-projects/nextjs_TS/sanity-cms/node_modules/esbuild/lib/main.js:677:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:324:12)`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.