npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@oasis-catalog/branding-widget

v1.1.3

Published

Работа с нанесениями на товары oasiscatalog из коробки

Downloads

538

Readme

Виджет редактирования нанесения

Работа с нанесениями на товары oasiscatalog из коробки

Установка

  1. Используйте скрипт с cdn, либо client/index.iife.js
https://unpkg.com/@oasis-catalog/branding-widget@^1/client/index.iife.js
https://unpkg.com/@oasis-catalog/branding-widget@^1/client/style.css
  1. Продвинутый вариант npm i @oasis-catalog/branding-widget

Быстрый старт

<link
    rel="stylesheet"
    href="https://unpkg.com/@oasis-catalog/branding-widget@^1/client/style.css"
/>
<form method="post">
    <div class="js--oasis-branding-widget" data-product-id="1-000081441"></div>

    <button type="submit">Отправить</button>
</form>
<script src="https://unpkg.com/@oasis-catalog/branding-widget@^1/client/index.iife.js"></script>

Простое использование

Подключите стили и скрипт на вашу страницу, можете воспользоваться cdn или скопировать файлы себе локально. Инициализировать виджет можно 2 способами:

  1. Просто разместите элемент с классом js--oasis-branding-widget на странице, и при помощи дата атрибутов передайте необходимые параметры. Для использования необходимо получить коэффициенты для выбранных товаров. Для получения коэффициентов необходимо сделать GET-запрос одним из способов:

    https://api.oasiscatalog.com/v4/branding/coef/1-000070661?key=key...
    https://api.oasiscatalog.com/v4/branding/coef?id=1-000070661,1-000070662,1-000070663&key=key...
    https://api.oasiscatalog.com/v4/branding/coef?id[]=1-000070661&id[]=1-000070662&id[]=1-000070663&key=key...

    Вы также можете передать:

    • data-product-id - В таком случае будет произведен запрос к апи oasiscatalog, с данным идентификатором (https://api.oasiscatalog.com/v4/branding/coef?id=productId&format=json).
    • data-coef-url - В таком случае запрос будет направлен по указаному url.
    • data-coef - В таком случае запроса не будет, а будут использованы переданные данные

    ВНИМАНИЕ: Не указывайте ваш ключ к api oasiscatalog в параметрах, чтобы не скомпроментировать его.

    data-item и data-branding можно не передавать тогда по умолчанию они будут:

    • data-item={productId: productId, quantity: 1, branding: []}
    • data-branding={}

    Но в таком случае обязательно нужно указать data-product-id

    data-form-name Добавит к инпутам в виджете параметр form, для связывания с конкретной формой на сайте

Пример

<head>
    <link
        rel="stylesheet"
        href="https://unpkg.com/@oasis-catalog/branding-widget@^1/client/style.css"
    />
    <!-- Или -->
    <!-- <link rel="stylesheet" href="client/style.css" /> -->
</head>
<body>
    <div class="js--oasis-branding-widget" data-product-id="1-000081441"></div>
    <form id="oasis-branding-widget-form" method="post">
        <button type="submit">Отправить</button>
    </form>
    <script src="https://unpkg.com/@oasis-catalog/branding-widget@^1/client/index.iife.js"></script>
    <!-- Или -->
    <!-- <script src="client/index.iife.js"></script> -->
</body>
  1. Проинициализоровать в скрипте, передав необходимые параметры
<head>
    <link rel="stylesheet" href="client/style.css" />
</head>
<body>
    <div id="oasis-branding-widget-test"></div>
    <script src="client/index.iife.js"></script>
    <script type="module">
        const item = {
            productId: '1-000072263',
            quantity: 1,
            // Методы нанесения что были заданы продукту
            branding: [],
        };
        const branding = {
            '1nn244ja91': {
                typeId: '1-000026380',
                placeId: '000013225',
                logoId: null,
                width: null,
                height: null,
            },
        };

        OasisBrandigWidget('#oasis-branding-widget-test', {
            productId: '1-000072263',
            coefUrl: 'http://localhost:3030/coef/1-000072263',
            item,
            branding,
        });
    </script>
</body>

Продвинутое использование (Требуется vue 3)

Установите @oasis-catalog/oasis-branding-widget. Вам будут доступны следующие компоненты: OasisBrandingWidget, OasisBrandingWidgetTogglers, OasisBrandingWidgetParams А также внешние функции useProvideBrandingWidgetStore, useBrandingWidgetStoreOrThrow подробнее о механизме работы описано здесь

Для полноценной работы потребуются следующие зависимости: vue, @vueuse/core, @floating-ui/vue

<template lang="pug">
.app
    oasis-branding-widget-total.mb-5(
        v-if="coef"
        :coef="coef"
        :item="item"
        :price="price"
        :branding="branding"
        :quantity="quantity"
        :with-readiness="false"
        :visible-rows="['client']"
    )
    oasis-branding-widget-togglers(
        v-if="coef"
        :coef="coef"
    )
</template>

<script lang="ts">
import {defineComponent} from 'vue';
import {useAsyncState} from '@vueuse/core';
import {
    OasisBrandingWidgetTotal,
    OasisBrandingWidgetTogglers,
} from '@oasis-catalog/oasis-branding-widget';
import type {CollectionBranding} from '@oasis-catalog/branding-price';

export default defineComponent({
    components: {
        OasisBrandingWidgetTotal
        OasisBrandingWidgetTogglers,
    },

    setup() {
        const {state: coef, isLoading: isLoadingCoef} = useAsyncState(
            async () => {
                // Нужно указать url для источника данных
                let coef = await fetch('fetch-data');
                coef = await coef.json();
                return coef:
            },
            undefined,
        );
        const item = ref({
            productId: '1-000072263',
            quantity: 1,
            branding: ['1nn244ja91'],
        });
        const branding = ref<Record<string, CollectionBranding>>({
            '1nn244ja91': {
                typeId: '1-000026380',
                placeId: '000013225',
                logoId: null,
                width: null,
                height: null,
            },
        });
        const price = ref({
            client: 356.1,
            dealer: 249.27,
        });
        const quantity = 1;
        // Данная функция объявит все необходимые для работы данные и функции
        useProvideBrandingWidgetStore(
            {
                coef: coef.value,
                item: item,
                branding: branding,
            },
        );

        return {
            coef,
            item,
            branding,
            price,
            quantity,
        };
    },
});
</script>

Типы

type Coef = {
    margin: number;
    setupMargin: number;
    vat?: number | null;
    discount?: number;
    setupDiscount?: number;
    hasOwnProduction?: boolean;
    items: CoefItem[];
    methods: CoefMethod[];
    groups: CoefGroup[];
};
type CollectionItem = {
    productId: string;
    quantity:
        | number
        | {
              [key: string]: number;
          };
    branding?: number[] | string[];
    multipliers?: {
        [key: string]: number;
    };
};
type CollectionBranding = {
    placeId: string;
    typeId: string;
    logoId?: number | null;
    width?: number | null;
    height?: number | null;
};
type PriceProp = {
    client: number;
    dealer: number;
};
type SelectionOption = {
    id: string | number;
    text: string;
};

type Params = {
    /**
     * Идентификатор продукта
     * Если не указан coef и item, является обязательным параметром
     */
    productId?: string;
    /** Url для загрузки коэффициентов по продукту */
    coefUrl?: string;
    /** Коэффициенты для выбранного товара */
    coef?: Coef;
    /** Выбранный товар */
    item?: CollectionItem;
    /** Объект с информацией по нанесениям */
    branding?: Record<string, CollectionBranding>;
    /** Название формы для нативной обработки данных */
    formName?: string;
    /** Локализация для форматирования цены */
    locale?: string;
    /** Отображаемая валюта, влияет на знак валюты */
    currency?: string;
};

function OasisBrandigWidget(mountEl: string | HTMLElement, params: Params): Promise<void>;