Passo 14: Utilizar Estilos Customizados Quando o Componente é Apresentado numa Moldura Inline

Os componentes apresentados numa moldura inline não têm acesso direto ao ficheiro design.css. Em vez de disso, existe um passo adicional para obter o URL para o design.css no seu componente, o que deverá ser acrescentado à página. Em seguida, deve atualizar o seu componente para refletir o estilo selecionado pelo utilizador.

Para incluir e utilizar o ficheiro design.css no seu componente, são necessárias alterações no ficheiro render.html:
  1. Localizar e incluir o URL no ficheiro design.css

  2. Obter o valor da classe de estilo selecionado quando alterar

  3. Atualizar o modelo para refletir a styleClass selecionada

  4. Reflita as alterações da classe de estilo selecionado no seu componente.

  5. Certifique-se de que a moldura inline é redimensionada quando o estilo for alterado.

Seguem-se instruções detalhadas para a edição do ficheiro render.html:

  1. Localize e inclua o URL no ficheiro design.css.

    Acrescente de forma dinâmica o ficheiro design.css à secção <head> da página. Depois de ser carregado, defina a altura da moldura inline porque poderá ter sido alterada ao aplicar os estilos.

    Acrescente o seguinte código no objeto viewModel:

    // Dynamically add any theme design URL to the <head> of the page
    self.loadStyleSheet = function (url) {
        var $style,
            styleSheetDeferred = new $.Deferred(),
            attempts = 100,
            numAttempts = 0,
            interval = 50,
            pollFunction = function () {
                // try to locate the style sheet
                for (var i = 0; i < document.styleSheets.length; i++) {
                    try {
                        // locate the @import sheet that has an href based on our expected URL
                        var sheet = document.styleSheets[i],
                            rules = sheet && sheet.cssRules,
                            rule = rules && rules[0];
                        // check whether style sheet has been loaded
                        if (rule && (rule.href === url)) {
                            styleSheetDeferred.resolve();
                            return;
                        }
                    } catch (e) {}
                }
                if (numAttempts < attempts) {
                    numAttempts++;
                    setTimeout(pollFunction, interval);
                } else {
                    // didn't find style sheet so complete anyway
                    styleSheetDeferred.resolve();
                }
            };
     
        // add the themeDesign stylesheet to <head>
        // use @import to avoid cross domain security issues when determining when the stylesheet is loaded
        $style = $('<style type="text/css">@import url("' + url + '")</style>');
        $style.appendTo('head');
     
        // kickoff the polling
        pollFunction();
     
        // return the promise
        return styleSheetDeferred.promise();
    };
     
    // update with the design.css from the Sites Page
    SitesSDK.getSiteProperty('themeDesign', function (data) {
        if (data && data.themeDesign && typeof data.themeDesign === 'string') {
            // load the style sheet and then set the height
            self.loadStyleSheet(data.themeDesign).done(self.setHeight);
        }
    });
  2. Obtenha o valor da classe de estilo selecionado quando alterar.

    Crie um elemento observável para controlar quando o valor da propriedade styleClass é alterado.

    self.selectedStyleClass = ko.observable();

    Note que só podemos apresentar quando tivermos classe de estilo. Altere este código:

    self.customSettingsDataInitialized = ko.observable(false);
    self.initialized = ko.computed(function () {
        return self.customSettingsDataInitialized();
    }, self);

    Utilize este código como alternativa:

    self.customSettingsDataInitialized = ko.observable(false);
    self.styleClassInitialized = ko.observable(false);
    self.initialized = ko.computed(function () {
        return self.customSettingsDataInitialized() && self.styleClassInitialized();
    }, self);

    Obtenha o valor inicial para a classe de estilo selecionada acrescentando:

    self.updateStyleClass = function (styleClass) {
        self.selectedStyleClass((typeof styleClass === 'string') ? styleClass : 'hello-world-default-style'); // note that this 'hello-world' prefix is based on the app name
        self.styleClassInitialized(true);
    };
    SitesSDK.getProperty('styleClass', self.updateStyleClass);
  3. Atualize o modelo para refletir a styleClass. Altere este código:

    <p data-bind="attr: {id: 'titleId'}, text: titleText"></p>

    Utilize este código como alternativa:

    <p data-bind="attr: {id: 'titleId'}, text: titleText, css: selectedStyleClass"></p>
  4. Reflita as alterações da classe de estilo selecionado no seu componente. Altere este código:

    if (settings.property === 'customSettingsData') {
        self.updateCustomSettingsData(settings.value);
    }

    Utilize este código como alternativa:

    if (settings.property === 'customSettingsData') {
        self.updateCustomSettingsData(settings.value);
    }
    if (settings.property === 'styleClass') {
        self.updateStyleClass(settings.value);
    }
  5. Certifique-se de que a moldura inline é redimensionada quando o estilo for alterado. Altere este código:

    // create dependencies on any observables so this handler is called whenever it changes
    var imageWidth = viewModel.imageWidth(),
          imageUrl = viewModel.imageUrl(),
          titleText = viewModel.titleText(),
          userText = viewModel.userText();

    Utilize este código como alternativa:

    // create dependencies on any observables so this handler is called whenever it changes
    var imageWidth = viewModel.imageWidth(),
          imageUrl = viewModel.imageUrl(),
          titleText = viewModel.titleText(),
          userText = viewModel.userText(),
          selectedStyleClass = viewModel.selectedStyleClass();  
  6. Grave e sincronize os seus ficheiros com o servidor da instância do Oracle Content Management.

Verificar os Resultados para o Passo 14

  1. Renove a sua página no site para que o Criador de Sites possa escolher alterações para o componente.

  2. Apresente a página no modo de edição.

  3. Arraste e largue o seu componente na página.

  4. Abra o painel Definições com o seu componente.

  5. Aceda ao separador Estilo.

  6. Alterne entre os estilos Gothic e Plain definidos no seu ficheiro design.json.

    Irá reparar que o tamanho do tipo de letra no seu componente ajusta-se para refletir as alterações quando alterna entre a classe CSS aplicada para cada seleção.

Avance para Passo 15: Integração com o Comportamento Desfazer e Refazer Página.